commands.ts 22 KB

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