commands.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /** Session commands whose activation policy is explicit at each Remote method. */
  2. import { randomUUID } from 'node:crypto'
  3. import type { Context } from '@deepseek-ai/cordis'
  4. import type { Agent, ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent'
  5. import {
  6. PresetMountError, UnknownPresetError, resolveSessionPreset,
  7. } from '@deepseek-ai/dsh-agent-presets'
  8. import { AttachmentError, admitEncodedImages } from '@deepseek-ai/dsh-attachment'
  9. import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
  10. import {
  11. ReasoningEffortId, createUserMessage, freezeMessage,
  12. } from '@deepseek-ai/dsh-llm'
  13. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  14. import { SessionId } from '@deepseek-ai/dsh-session'
  15. import type { Session, SessionEvent, SessionHeader, UserMessage } from '@deepseek-ai/dsh-session'
  16. import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title'
  17. import { TypertRemoteFailure } from '@deepseek-ai/dsh-typert-protocol'
  18. import type { Workspace } from '@deepseek-ai/dsh-workspace'
  19. import {
  20. ApiSessionAgentController,
  21. ApiSessionCwdConflict,
  22. ApiSessionNotFound,
  23. ApiSessionPresetConflict,
  24. ApiSessionSubagentOwnership,
  25. apiSessionSubagentOwnershipError,
  26. hasApiSessionSubagentOwner,
  27. inspectApiSession,
  28. } from './agent.ts'
  29. import { buildModelCatalog } from './catalog.ts'
  30. import type {
  31. SessionAttachmentRequest,
  32. SessionAttachmentValue,
  33. SessionCancelRequest,
  34. SessionCancelValue,
  35. SessionCreateRequest,
  36. SessionCreateValue,
  37. SessionForkRequest,
  38. SessionForkValue,
  39. SessionModels,
  40. SessionModelsRequest,
  41. SessionPromptRequest,
  42. SessionPromptValue,
  43. SessionRenameRequest,
  44. SessionRenameValue,
  45. SessionSelectModelRequest,
  46. SessionSelectModelValue,
  47. SessionUpdateQueueRequest,
  48. SessionUpdateQueueValue,
  49. } from './types.ts'
  50. interface SessionReadState {
  51. readonly id: SessionId
  52. readonly header: SessionHeader
  53. readonly events: SessionEvent[]
  54. }
  55. /** Implements Session business commands delegated by the Session Controller Remote service. */
  56. export class SessionCommandController {
  57. /**
  58. * @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
  59. * @param agents - sole owner of create, resume, and Session-local model selection.
  60. * @param defaultCwd - project directory used when create names neither a Workspace nor a cwd.
  61. */
  62. constructor(
  63. private readonly ctx: Context,
  64. private readonly agents: ApiSessionAgentController,
  65. private readonly defaultCwd: string,
  66. ) {}
  67. /**
  68. * Create or idempotently adopt one ordinary Session.
  69. * @param request - requested identity, location, and Agent preset.
  70. * @returns the Session identity and resolved preset when configured.
  71. */
  72. async create(request: SessionCreateRequest): Promise<SessionCreateValue> {
  73. if (request.workspaceId !== undefined && request.cwd !== undefined) {
  74. reject('bad-request', 'session.create accepts workspaceId or cwd, not both', {})
  75. }
  76. const sessionId = request.sessionId ?? SessionId(`session-${randomUUID()}`)
  77. let workspace: Workspace | undefined
  78. if (request.workspaceId !== undefined) {
  79. workspace = this.ctx.workspaceRegistry.get(request.workspaceId)
  80. if (workspace === undefined) {
  81. reject('workspace-not-found', `workspace "${request.workspaceId}" not found`, {
  82. workspaceId: request.workspaceId,
  83. })
  84. }
  85. }
  86. const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd
  87. let adopted: Agent
  88. try {
  89. adopted = await this.agents.ensureSession(
  90. sessionId,
  91. cwd,
  92. request.sessionId !== undefined,
  93. request.agentPreset,
  94. )
  95. } catch (error) {
  96. this.rejectCreation(sessionId, error)
  97. }
  98. if (workspace !== undefined) {
  99. try {
  100. await workspace.attachSession(sessionId)
  101. } catch (error) {
  102. reject(
  103. 'workspace-attach-failed',
  104. `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`,
  105. { sessionId, workspaceId: workspace.id },
  106. )
  107. }
  108. }
  109. const agentPreset = resolveSessionPreset(adopted.session)
  110. return { sessionId, ...(agentPreset === undefined ? {} : { agentPreset }) }
  111. }
  112. /**
  113. * Read the current selection and advisory model catalog, explicitly resuming the Session.
  114. * @param request - Session whose model state is requested.
  115. * @returns the current selection and available model groups.
  116. */
  117. async models(request: SessionModelsRequest): Promise<SessionModels> {
  118. const agent = await this.resolveAgent(request.sessionId)
  119. const current = this.agents.selectionFor(agent).current
  120. const { groups, failures } = await buildModelCatalog(this.ctx)
  121. return {
  122. current: { ...current },
  123. routable: routeServed(this.ctx, current.provider),
  124. groups,
  125. failures,
  126. }
  127. }
  128. /**
  129. * Validate and install one Session-local model selection.
  130. * @param request - Session identity and requested model selection.
  131. * @returns the normalized selection installed for the Session.
  132. */
  133. async selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
  134. const agent = await this.resolveAgent(request.sessionId)
  135. return this.agents.serializeImageAdmission(agent, async () => {
  136. try {
  137. const resolved = await this.ctx.llm.resolveCallConfig({
  138. provider: request.provider,
  139. model: request.model,
  140. ...(request.reasoningEffort === undefined
  141. ? {}
  142. : { reasoningEffort: ReasoningEffortId(request.reasoningEffort) }),
  143. })
  144. const selected: AgentModelSelection = {
  145. provider: resolved.provider,
  146. model: resolved.model,
  147. ...(resolved.reasoningEffort === undefined
  148. ? {}
  149. : { reasoningEffort: resolved.reasoningEffort }),
  150. }
  151. this.agents.selectionFor(agent).current = selected
  152. try {
  153. await this.ctx.agentDefaultModel.saveSelection(selected)
  154. } catch (error) {
  155. this.ctx.logger.warn(
  156. `session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`,
  157. )
  158. }
  159. return { selected: { ...selected } }
  160. } catch (error) {
  161. if (error instanceof TypertRemoteFailure) throw error
  162. reject(
  163. 'model-unavailable',
  164. error instanceof Error ? error.message : String(error),
  165. { provider: request.provider, model: request.model },
  166. )
  167. }
  168. })
  169. }
  170. /**
  171. * Normalize and append a user-owned Session title.
  172. * @param request - Session identity and proposed title.
  173. * @returns the accepted title and durable event sequence.
  174. */
  175. async rename(request: SessionRenameRequest): Promise<SessionRenameValue> {
  176. const agent = await this.resolveAgent(request.sessionId)
  177. const titles = this.ctx.get('sessionTitle')
  178. if (titles === undefined) {
  179. reject('internal', 'renaming is unavailable: this deployment mounts no session-title service', {})
  180. }
  181. try {
  182. const accepted = titles.rename(agent.session, request.title)
  183. return { title: accepted.title, seq: accepted.eventSeq }
  184. } catch (error) {
  185. if (error instanceof SessionTitleInvalidError) {
  186. reject('title-invalid', error.message, { sessionId: request.sessionId })
  187. }
  188. reject(
  189. 'internal',
  190. `failed to rename session "${request.sessionId}": ${String(error)}`,
  191. {},
  192. )
  193. }
  194. }
  195. /**
  196. * Create a new ordinary Session from one completed-turn prefix.
  197. * @param request - source Session and optional event anchor.
  198. * @returns the new Session identity.
  199. */
  200. async fork(request: SessionForkRequest): Promise<SessionForkValue> {
  201. if (request.atSeq !== undefined
  202. && (!Number.isInteger(request.atSeq) || request.atSeq < 0)) {
  203. reject('bad-request', 'atSeq must be a non-negative integer', {})
  204. }
  205. let source: SessionReadState
  206. try {
  207. source = await this.readSessionState(request.sessionId)
  208. } catch (error) {
  209. if (error instanceof ApiSessionNotFound) {
  210. reject('session-not-found', error.message, { sessionId: request.sessionId })
  211. }
  212. reject(
  213. 'internal',
  214. `fork source unavailable for session "${request.sessionId}": ${String(error)}`,
  215. {},
  216. )
  217. }
  218. const lastSeq = source.events.at(-1)?.seq ?? -1
  219. const atSeq = request.atSeq
  220. const anchoredBoundary = atSeq === undefined
  221. ? undefined
  222. : source.events.find(event => event.type === 'turn/end' && event.seq >= atSeq)
  223. const boundary = anchoredBoundary
  224. ?? (atSeq === undefined || atSeq > lastSeq
  225. ? source.events.findLast(event => event.type === 'turn/end')
  226. : undefined)
  227. if (boundary === undefined) {
  228. reject(
  229. 'fork-unavailable',
  230. atSeq !== undefined && atSeq <= lastSeq
  231. ? `session "${request.sessionId}" has not completed the turn containing event ${String(atSeq)}`
  232. : `session "${request.sessionId}" has no completed turn to fork from`,
  233. { sessionId: request.sessionId },
  234. )
  235. }
  236. let cut = boundary.seq + 1
  237. while (cut < source.events.length && source.events[cut]?.type !== 'turn/start') cut++
  238. let workspace: Workspace | undefined
  239. try {
  240. workspace = await this.forkWorkspace(source)
  241. } catch (error) {
  242. reject(
  243. 'internal',
  244. `failed to resolve fork workspace for session "${request.sessionId}": ${String(error)}`,
  245. {},
  246. )
  247. }
  248. const childId = SessionId(`session-${randomUUID()}`)
  249. const composition = await this.agents.composeAgent(resolveSessionPreset(source))
  250. try {
  251. const { provider, model } = this.ctx.agentDefaultModel.currentSelection()
  252. await this.ctx.agents.create({
  253. sessionId: childId,
  254. seed: source.events.slice(0, cut),
  255. meta: {
  256. ...(source.header.cwd === undefined ? {} : { cwd: source.header.cwd }),
  257. parentSession: source.id,
  258. seedLength: cut,
  259. ...(composition.agentPreset === undefined
  260. ? {}
  261. : { agentPreset: composition.agentPreset }),
  262. },
  263. agentOptions: { provider, model },
  264. setup: composition.setup,
  265. })
  266. } catch (error) {
  267. reject(
  268. 'internal',
  269. `failed to fork session "${request.sessionId}": ${String(error)}`,
  270. {},
  271. )
  272. }
  273. if (workspace !== undefined) {
  274. try {
  275. await workspace.attachSession(childId)
  276. } catch (error) {
  277. reject(
  278. 'workspace-attach-failed',
  279. `session "${childId}" was forked but could not attach to workspace "${workspace.id}": ${String(error)}`,
  280. { sessionId: childId, workspaceId: workspace.id },
  281. )
  282. }
  283. }
  284. return { sessionId: childId }
  285. }
  286. /**
  287. * Admit one browser prompt after explicit Agent resume and image validation.
  288. * @param request - Session identity, prompt content, source metadata, and delivery mode.
  289. * @returns acknowledgement that the Agent accepted the prompt.
  290. */
  291. async prompt(request: SessionPromptRequest): Promise<SessionPromptValue> {
  292. const clientTimeZone = request.clientTimeZone === undefined
  293. ? undefined
  294. : canonicalClientTimeZone(request.clientTimeZone)
  295. if (request.clientTimeZone !== undefined && clientTimeZone === undefined) {
  296. reject(
  297. 'invalid-time-zone',
  298. 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  299. { value: request.clientTimeZone },
  300. )
  301. }
  302. const agent = await this.resolveAgent(request.sessionId)
  303. const selection = this.agents.selectionFor(agent).current
  304. if (!routeServed(this.ctx, selection.provider)) {
  305. reject(
  306. 'model-unavailable',
  307. `no adapter serves provider "${selection.provider}"; select a model for this session`,
  308. { provider: selection.provider, model: selection.model },
  309. )
  310. }
  311. const source: MessageSource = {
  312. kind: 'user',
  313. rpcId: request.requestId,
  314. ...(clientTimeZone === undefined ? {} : { clientTimeZone }),
  315. }
  316. const hasImage = request.content.some(part => part.type === 'image')
  317. const admit = async (): Promise<SessionPromptValue> => {
  318. try {
  319. if (hasImage) {
  320. const current = this.agents.selectionFor(agent).current
  321. const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model)
  322. if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {
  323. reject(
  324. 'attachment-error',
  325. `Model "${current.model}" does not support image input.`,
  326. { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' },
  327. )
  328. }
  329. }
  330. const content = await durablePromptContent(this.ctx, request.content)
  331. const message: UserMessage = createUserMessage({ content, source })
  332. if (request.mode === 'steer') agent.steer(message)
  333. else agent.followup(message)
  334. } catch (error) {
  335. if (error instanceof TypertRemoteFailure) throw error
  336. if (error instanceof AttachmentError) {
  337. reject('attachment-error', error.message, { reason: error.code })
  338. }
  339. reject('agent-busy', 'prompt rejected', { reason: String(error) })
  340. }
  341. return { accepted: true }
  342. }
  343. return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit()
  344. }
  345. /**
  346. * Read one durable image after proving the Session log references it.
  347. * @param request - Session and attachment identities used for authorization.
  348. * @returns the durable attachment reference and base64-encoded bytes.
  349. */
  350. async attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
  351. let source: SessionReadState
  352. try {
  353. source = await this.readSessionState(request.sessionId)
  354. } catch (error) {
  355. if (error instanceof ApiSessionNotFound) {
  356. reject('session-not-found', error.message, { sessionId: request.sessionId })
  357. }
  358. reject(
  359. 'internal',
  360. `attachment authorization unavailable for session "${request.sessionId}": ${String(error)}`,
  361. {},
  362. )
  363. }
  364. const ref = referencedImage(source.events, String(request.attachmentId))
  365. if (ref === undefined) {
  366. reject(
  367. 'attachment-error',
  368. 'Image is not referenced by this session.',
  369. { reason: 'ATTACHMENT_NOT_REFERENCED' },
  370. )
  371. }
  372. try {
  373. const stored = await this.ctx.attachments.readImage(ref)
  374. return {
  375. attachment: stored.ref,
  376. data: Buffer.from(stored.data).toString('base64'),
  377. }
  378. } catch (error) {
  379. if (error instanceof AttachmentError) {
  380. reject('attachment-error', error.message, { reason: error.code })
  381. }
  382. reject('internal', 'Unable to read image attachment.', {})
  383. }
  384. }
  385. /**
  386. * Mutate one still-pending queue occurrence without resuming a cold Agent.
  387. * @param request - Session, queue item, and requested mutation.
  388. * @returns acknowledgement that the queue mutation was applied.
  389. */
  390. updateQueue(request: SessionUpdateQueueRequest): SessionUpdateQueueValue {
  391. if (request.action.kind === 'edit'
  392. && request.action.content.some(block => block.type !== 'text')) {
  393. reject(
  394. 'attachment-error',
  395. 'queue edits accept text content only',
  396. { reason: 'QUEUE_EDIT_NON_TEXT' },
  397. )
  398. }
  399. const agent = this.ctx.agents.get(request.sessionId)
  400. if (agent !== undefined && hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
  401. rejectFailure(apiSessionSubagentOwnershipError(request.sessionId))
  402. }
  403. if (agent === undefined) {
  404. reject('queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId })
  405. }
  406. const nextTurn = agent.inbox.nextTurn.find(message => message.id === request.itemId)
  407. const nextStep = agent.inbox.nextStep.find(message => message.id === request.itemId)
  408. const located = nextTurn === undefined
  409. ? nextStep === undefined ? undefined : { target: 'next-step' as const, message: nextStep }
  410. : { target: 'next-turn' as const, message: nextTurn }
  411. if (located === undefined) {
  412. reject('queue-item-not-found', 'queued item is no longer pending', { itemId: request.itemId })
  413. }
  414. const { target, message } = located
  415. if (request.action.kind === 'steer' && (target !== 'next-turn' || agent.status !== 'running')) {
  416. reject('steer-unavailable', 'current turn no longer accepts steering', { itemId: request.itemId })
  417. }
  418. if (request.action.kind === 'edit') {
  419. agent.inbox.replace(request.itemId, freezeMessage<UserMessage>({
  420. ...message,
  421. content: [...request.action.content],
  422. }))
  423. } else {
  424. agent.inbox.remove(request.itemId)
  425. if (request.action.kind === 'steer') agent.steer(message)
  426. }
  427. return { accepted: true }
  428. }
  429. /**
  430. * Cancel one live ordinary Agent while retaining pending inbox work.
  431. * @param request - Session whose active Agent turn is cancelled.
  432. * @returns acknowledgement that cancellation was requested.
  433. */
  434. cancel(request: SessionCancelRequest): SessionCancelValue {
  435. const agent = this.ctx.agents.get(request.sessionId)
  436. if (agent === undefined) {
  437. reject(
  438. 'session-not-found',
  439. `session "${request.sessionId}" not found (not attached)`,
  440. { sessionId: request.sessionId },
  441. )
  442. }
  443. if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
  444. rejectFailure(apiSessionSubagentOwnershipError(request.sessionId))
  445. }
  446. agent.cancel({ kind: 'user' }, { keepInbox: true })
  447. return { accepted: true }
  448. }
  449. private async resolveAgent(sessionId: SessionId): Promise<Agent> {
  450. const found = await this.agents.resolveAgent(sessionId)
  451. if ('error' in found) rejectFailure(found.error)
  452. return found.agent
  453. }
  454. private rejectCreation(sessionId: SessionId, error: unknown): never {
  455. if (error instanceof ApiSessionPresetConflict) {
  456. reject('agent-preset-conflict', error.message, {
  457. sessionId: error.sessionId,
  458. requestedPreset: error.requestedPreset,
  459. ...(error.existingPreset === undefined ? {} : { existingPreset: error.existingPreset }),
  460. })
  461. }
  462. if (error instanceof UnknownPresetError) {
  463. reject('agent-preset-not-found', error.message, {
  464. agentPreset: error.presetId,
  465. available: [...error.available],
  466. })
  467. }
  468. if (error instanceof PresetMountError) {
  469. reject('agent-preset-invalid', error.message, {
  470. agentPreset: error.presetId,
  471. reason: error.reason,
  472. })
  473. }
  474. if (error instanceof ApiSessionCwdConflict) {
  475. reject('session-conflict', error.message, {
  476. sessionId: error.sessionId,
  477. requestedCwd: error.requestedCwd,
  478. ...(error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd }),
  479. })
  480. }
  481. if (error instanceof ApiSessionSubagentOwnership) {
  482. rejectFailure(apiSessionSubagentOwnershipError(error.sessionId))
  483. }
  484. reject('internal', `failed to create session "${sessionId}": ${String(error)}`, {})
  485. }
  486. private async readSessionState(sessionId: SessionId): Promise<SessionReadState> {
  487. const attached = this.ctx.sessions.get(sessionId)
  488. if (attached !== undefined) {
  489. return { id: attached.id, header: attached.header, events: [...attached.events] }
  490. }
  491. const inspected = await inspectApiSession(this.ctx, sessionId)
  492. return { id: inspected.meta.id, header: inspected.meta, events: inspected.events }
  493. }
  494. private async forkWorkspace(source: Pick<Session, 'id' | 'header'>): Promise<Workspace | undefined> {
  495. const workspaces = this.ctx.workspaceRegistry.list()
  496. const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id))
  497. if (direct !== undefined || source.header.origin !== 'subagent') return direct
  498. const lineage = await this.ctx.sessionQuery.traceSession(source.id)
  499. for (const ancestor of lineage.ancestors) {
  500. const workspace = workspaces.find(candidate => candidate.sessionIds.includes(ancestor.header.id))
  501. if (workspace !== undefined) return workspace
  502. }
  503. return undefined
  504. }
  505. }
  506. function rejectFailure(error: { readonly code: string; readonly message: string; readonly details: object }): never {
  507. throw new TypertRemoteFailure(error)
  508. }
  509. function reject(code: string, message: string, details: object): never {
  510. throw new TypertRemoteFailure({ code, message, details })
  511. }
  512. async function durablePromptContent(
  513. ctx: Context,
  514. content: readonly SessionPromptRequest['content'][number][],
  515. ): Promise<ContentBlock[]> {
  516. if (content.every(part => part.type === 'text')) {
  517. return content.map(part => ({ type: 'text', text: part.text }))
  518. }
  519. const refs = await admitEncodedImages(ctx.attachments, content.filter(part => part.type === 'image'))
  520. let next = 0
  521. return content.map(part => part.type === 'text'
  522. ? { type: 'text', text: part.text }
  523. // admitEncodedImages returns one reference per image part in order.
  524. : { type: 'image', attachment: refs[next++] as ImageAttachmentRef })
  525. }
  526. function imageBlockIn(
  527. content: unknown,
  528. match: (ref: ImageAttachmentRef) => boolean,
  529. ): ImageAttachmentRef | undefined {
  530. if (!Array.isArray(content)) return undefined
  531. for (const value of content) {
  532. if (typeof value !== 'object' || value === null || Array.isArray(value)) continue
  533. const block = value as { readonly type?: unknown; readonly attachment?: unknown; readonly content?: unknown }
  534. if (block.type === 'image' && typeof block.attachment === 'object' && block.attachment !== null) {
  535. const ref = block.attachment as ImageAttachmentRef
  536. if (match(ref)) return ref
  537. }
  538. if (block.type === 'tool-result') {
  539. const nested = imageBlockIn(block.content, match)
  540. if (nested !== undefined) return nested
  541. }
  542. }
  543. return undefined
  544. }
  545. function imageInEvent(
  546. event: SessionEvent,
  547. match: (ref: ImageAttachmentRef) => boolean,
  548. ): ImageAttachmentRef | undefined {
  549. const data = event.data as {
  550. readonly content?: unknown
  551. readonly message?: { readonly content?: unknown }
  552. readonly inserted?: readonly { readonly content?: unknown }[]
  553. readonly chunk?: { readonly type?: unknown; readonly block?: unknown }
  554. }
  555. const direct = imageBlockIn(data.content, match)
  556. if (direct !== undefined) return direct
  557. const message = imageBlockIn(data.message?.content, match)
  558. if (message !== undefined) return message
  559. for (const inserted of data.inserted ?? []) {
  560. const found = imageBlockIn(inserted.content, match)
  561. if (found !== undefined) return found
  562. }
  563. return event.type === 'assistant/chunk' && data.chunk?.type === 'block-end'
  564. ? imageBlockIn([data.chunk.block], match)
  565. : undefined
  566. }
  567. function referencedImage(
  568. events: readonly SessionEvent[],
  569. attachmentId: string,
  570. ): ImageAttachmentRef | undefined {
  571. for (const event of events) {
  572. const found = imageInEvent(event, ref => String(ref.attachmentId) === attachmentId)
  573. if (found !== undefined) return found
  574. }
  575. return undefined
  576. }
  577. const IANA_TIME_ZONE = /^[A-Za-z][A-Za-z0-9_+.-]*(?:\/[A-Za-z0-9_+.-]+)+$/
  578. function canonicalClientTimeZone(value: string): string | undefined {
  579. if (value.length === 0 || value.trim() !== value
  580. || (value !== 'UTC' && !IANA_TIME_ZONE.test(value))) return undefined
  581. try {
  582. return new Intl.DateTimeFormat('en-US', { timeZone: value }).resolvedOptions().timeZone
  583. } catch {
  584. return undefined
  585. }
  586. }
  587. function routeServed(ctx: Context, provider: string): boolean {
  588. return ctx.llm.listProviders().some(entry => entry.id === provider)
  589. }