commands.ts 23 KB

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