commands.ts 26 KB

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