index.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. export type ConversationSource =
  2. | "api"
  3. | "cron"
  4. | "task"
  5. | "background-task"
  6. | "team"
  7. | "thread-goal"
  8. | "questionnaire"
  9. | "communication"
  10. | "code_review"
  11. | "greeting"
  12. | "channel:wechat"
  13. | "channel:feishu"
  14. | "channel:telegram";
  15. export type ConversationSessionKind =
  16. | "conversation"
  17. | "task"
  18. | "peek"
  19. | "channel"
  20. | "cron"
  21. | "unknown";
  22. export type ConversationSessionStatus =
  23. | "idle"
  24. | "started"
  25. | "error"
  26. | "aborted"
  27. | "interrupted";
  28. /**
  29. * Durable line marker written only after a historical Agent root is verified
  30. * against an adopted IM credential route. It lets Project queries surface the
  31. * one trusted legacy root without treating every Agent root as a project task.
  32. */
  33. export const TRUSTED_LEGACY_IM_ROOT_PURPOSE_MARKER =
  34. "[mavis:trusted-legacy-im-root]";
  35. /** A user-selected model thinking configuration persisted with one Conversation. */
  36. export interface ConversationModelThinkingSelection {
  37. readonly effort?: string;
  38. readonly off_behavior?: string;
  39. readonly budgets?: ConversationModelThinkingBudgets;
  40. }
  41. export interface ConversationModelThinkingBudgets {
  42. readonly minimal?: number | string;
  43. readonly low?: number | string;
  44. readonly medium?: number | string;
  45. readonly high?: number | string;
  46. }
  47. /** Sparse Task-owned overrides resolved with the target Agent and parent Session model groups. */
  48. export interface ConversationTaskModelSelection {
  49. readonly model?: string;
  50. readonly effort?: string;
  51. }
  52. /** Prevent an empty Task override from changing the Runtime default selection semantics. */
  53. export function hasConversationTaskModelSelection(
  54. selection: ConversationTaskModelSelection | undefined,
  55. ): selection is ConversationTaskModelSelection {
  56. return selection?.model !== undefined || selection?.effort !== undefined;
  57. }
  58. export const SESSION_TITLE_MAX_UNICODE_LENGTH = 50;
  59. /** Normalizes user-supplied Session titles to the same boundary as generated titles. */
  60. export function normalizeConversationSessionTitle(
  61. input: string | null | undefined,
  62. ): string | undefined {
  63. if (typeof input !== "string") return undefined;
  64. const title = input.replace(/\s+/gu, " ").trim();
  65. return title && Array.from(title).length <= SESSION_TITLE_MAX_UNICODE_LENGTH
  66. ? title
  67. : undefined;
  68. }
  69. export interface ConversationRunLocation {
  70. readonly mode: "current" | "new-worktree" | "existing-worktree";
  71. readonly resolvedDir: string;
  72. readonly resolvedBranch?: string;
  73. readonly parentRepoDir?: string;
  74. readonly createdAt: number;
  75. }
  76. export interface ConversationSession {
  77. readonly sessionId: string;
  78. readonly agentName: string;
  79. readonly workspaceDir: string;
  80. readonly runtime: "pi-agent" | "opencode";
  81. readonly sessionType: "root" | "branch";
  82. readonly sessionKind: ConversationSessionKind;
  83. readonly archived: boolean;
  84. readonly status: ConversationSessionStatus;
  85. readonly isDefaultWorkspace?: boolean;
  86. readonly title?: string | null;
  87. readonly parentSessionId?: string | null;
  88. readonly visibility?: "visible" | "hidden";
  89. readonly purpose?: string;
  90. readonly originCronId?: string;
  91. readonly runLocation?: ConversationRunLocation;
  92. readonly appMode?: "coding" | "work";
  93. readonly errorMessage?: string;
  94. readonly errorCode?: number;
  95. readonly errorSource?: string;
  96. readonly errorDetail?: string;
  97. readonly errorProviderId?: string;
  98. readonly effectiveModel?: string | null;
  99. readonly effectiveModelVariant?: string | null;
  100. readonly effectiveModelThinking?: ConversationModelThinkingSelection | null;
  101. readonly scratchpadPath?: string;
  102. readonly createdAtMs: number;
  103. readonly updatedAtMs: number;
  104. }
  105. export interface ConversationSessionListOptions {
  106. readonly agentName?: string;
  107. readonly originCronId?: string;
  108. readonly parentSessionId?: string | null;
  109. readonly archived?: boolean;
  110. readonly includeHidden?: boolean;
  111. readonly includeSessionKinds?: readonly ConversationSessionKind[];
  112. readonly excludeSessionKinds?: readonly ConversationSessionKind[];
  113. readonly includePurposePrefix?: string;
  114. readonly excludePurposePrefix?: string;
  115. readonly sessionType?: "root" | "branch";
  116. readonly search?: string;
  117. readonly cursor?: string;
  118. readonly offset?: number;
  119. readonly limit?: number;
  120. readonly scanLimit?: number;
  121. }
  122. export interface ConversationSessionCreateInput {
  123. readonly agentName: string;
  124. readonly workspaceDir?: string;
  125. readonly sessionType?: "root" | "branch";
  126. readonly sessionKind?: ConversationSessionKind;
  127. readonly title?: string | null;
  128. readonly parentSessionId?: string | null;
  129. readonly visibility?: "visible" | "hidden";
  130. readonly purpose?: string;
  131. readonly originCronId?: string;
  132. readonly runLocation?: ConversationRunLocation;
  133. readonly appMode?: "coding" | "work";
  134. readonly effectiveModel?: string | null;
  135. readonly effectiveModelVariant?: string | null;
  136. readonly effectiveModelThinking?: ConversationModelThinkingSelection | null;
  137. /** Explicit sparse Task model request resolved atomically with the frozen Task Agent binding. */
  138. readonly taskModelSelection?: ConversationTaskModelSelection;
  139. readonly isDefaultWorkspace?: boolean;
  140. readonly origin?: "user" | "root-repair";
  141. }
  142. export interface ConversationSessionUpdate {
  143. readonly title?: string | null;
  144. readonly visibility?: "visible" | "hidden";
  145. readonly purpose?: string;
  146. readonly workspaceDir?: string;
  147. readonly isDefaultWorkspace?: boolean;
  148. readonly sessionType?: "root" | "branch";
  149. readonly parentSessionId?: string | null;
  150. readonly archived?: boolean;
  151. readonly effectiveModel?: string | null;
  152. readonly effectiveModelVariant?: string | null;
  153. readonly effectiveModelThinking?: ConversationModelThinkingSelection | null;
  154. }
  155. export interface ConversationRootReplacement {
  156. readonly nextRoot: ConversationSession;
  157. readonly previousRoots: readonly ConversationSession[];
  158. readonly archivedRootTitle: string;
  159. readonly fallbackName: string;
  160. }
  161. export interface ConversationSessionQuery {
  162. getSession(sessionId: string): Promise<ConversationSession | undefined>;
  163. listSessions(
  164. options?: ConversationSessionListOptions,
  165. ): Promise<ConversationSession[]>;
  166. listMessages(
  167. sessionId: string,
  168. options?: { readonly limit?: number; readonly before?: string },
  169. ): Promise<{
  170. readonly messages: readonly ConversationCommittedMessage[];
  171. readonly nextCursor?: string;
  172. readonly hasMore: boolean;
  173. }>;
  174. }
  175. export interface ConversationSessionLifecycle {
  176. createSession(
  177. input: ConversationSessionCreateInput,
  178. ): Promise<ConversationSession>;
  179. createRootSession(input: {
  180. readonly agentName: string;
  181. readonly workspaceDir?: string;
  182. }): Promise<ConversationSession>;
  183. replaceRootSession(
  184. agentName: string,
  185. sessionId: string,
  186. ): Promise<ConversationRootReplacement>;
  187. updateSession(
  188. sessionId: string,
  189. fields: ConversationSessionUpdate,
  190. ): Promise<ConversationSession>;
  191. deleteSession(sessionId: string): Promise<void>;
  192. }
  193. export interface ConversationAttachment {
  194. readonly type?: string;
  195. readonly filePath?: string;
  196. readonly fileName?: string;
  197. readonly mimeType?: string;
  198. readonly dataUrl?: string;
  199. readonly assetId?: string;
  200. readonly error?: string;
  201. }
  202. export interface ConversationChannelContext {
  203. readonly platform: string;
  204. readonly chatType: string;
  205. readonly chatId: string;
  206. readonly senderId: string;
  207. readonly clientName: string;
  208. readonly threadId?: string;
  209. readonly sourceMessageId?: string;
  210. readonly contextToken?: string;
  211. readonly channel?: string;
  212. readonly channel_id?: string;
  213. }
  214. export interface ConversationModelSelection {
  215. readonly reasoning?: boolean;
  216. readonly contextLimit?: number;
  217. readonly thinking?: ConversationModelThinkingSelection;
  218. readonly providerId?: string;
  219. readonly modelId?: string;
  220. readonly variant?: string;
  221. }
  222. export interface ConversationMessageInput {
  223. readonly content: string;
  224. readonly attachments?: readonly ConversationAttachment[];
  225. readonly hideUserMessage?: boolean;
  226. readonly displayContent?: string;
  227. readonly origin?: unknown;
  228. readonly channelContext?: ConversationChannelContext;
  229. readonly quotedMessage?: {
  230. readonly text: string;
  231. readonly senderName?: string;
  232. };
  233. readonly model?: ConversationModelSelection;
  234. }
  235. export type ConversationToolCallStatus = 1 | 2 | 3;
  236. export interface ConversationToolCall {
  237. readonly tool_name: string;
  238. readonly tool_call_id: string;
  239. readonly tool_call_status: ConversationToolCallStatus;
  240. readonly tool_call_args?: string;
  241. readonly tool_call_result_data?: string;
  242. readonly tool_call_duration_ms?: number;
  243. }
  244. export interface ConversationCommittedMessage {
  245. readonly msgId?: string;
  246. readonly role?: string;
  247. readonly text?: string;
  248. readonly thinking?: string;
  249. readonly toolCalls?: readonly ConversationToolCall[];
  250. readonly kind?: string;
  251. readonly raw?: Readonly<Record<string, unknown>>;
  252. }
  253. /**
  254. * Facts observed while settling one turn. These are deliberately neutral
  255. * conversation facts: they describe what the runtime recorded, but do not
  256. * claim that the observation is a filesystem security guarantee.
  257. */
  258. export type ConversationFileChangeObservation =
  259. | "no_observed_change"
  260. | "change_observed"
  261. | "uncertain"
  262. | "recording_failed";
  263. export interface TurnFileChangeObservation {
  264. readonly fileChange: ConversationFileChangeObservation;
  265. readonly changedFiles?: readonly string[];
  266. readonly observationNotes: readonly string[];
  267. }
  268. export interface TurnCommittedFacts {
  269. readonly fileChangeObservation?: TurnFileChangeObservation;
  270. }
  271. export interface ConversationTurnResult {
  272. readonly turnId: string;
  273. readonly status: "completed" | "aborted" | "failed";
  274. readonly messages: readonly ConversationCommittedMessage[];
  275. readonly workspaceDir?: string;
  276. readonly error?: string;
  277. readonly committedFacts?: TurnCommittedFacts;
  278. }
  279. export interface ConversationAcceptedTurn {
  280. readonly turnId: string;
  281. readonly mode: "started" | "queued";
  282. readonly queue?: {
  283. readonly itemId: string;
  284. readonly position: number;
  285. readonly ahead: number;
  286. };
  287. readonly completion: Promise<ConversationTurnResult>;
  288. }
  289. export type ConversationTurnRejectionReason =
  290. | "invalid-session"
  291. | "active-turn"
  292. | "compaction-active"
  293. | "session-deleting"
  294. | "session-mutating"
  295. | "priority-blocked"
  296. | "ingress-conflict"
  297. | `policy:${string}`
  298. | "duplicate"
  299. | "invalid-input"
  300. | "active-model-override-unsupported"
  301. | "delivery-closed";
  302. export class ConversationTurnRejectedError extends Error {
  303. readonly code = "CONVERSATION_TURN_REJECTED";
  304. constructor(
  305. readonly sessionId: string,
  306. readonly reason: ConversationTurnRejectionReason,
  307. ) {
  308. super(`Conversation Turn was rejected for ${sessionId}: ${reason}`);
  309. this.name = "ConversationTurnRejectedError";
  310. }
  311. }
  312. export type ConversationDisplaySource =
  313. | ConversationSource
  314. | "cron-report"
  315. | (string & { readonly __conversationDisplaySourceBrand?: never });
  316. export interface ConversationDisplayProvenance {
  317. readonly source?: ConversationDisplaySource;
  318. readonly origin?: unknown;
  319. }
  320. export interface ConversationSubmitInput {
  321. readonly sessionId: string;
  322. readonly source: ConversationSource;
  323. readonly message: ConversationMessageInput;
  324. readonly allowQueue: boolean;
  325. /** Internal control-plane continuation that must precede already queued ordinary input. */
  326. readonly queuePlacement?: "front";
  327. readonly clientRequestId?: string;
  328. readonly requestedTurnId?: string;
  329. readonly dedupeKey?: string;
  330. readonly expiresAt?: number;
  331. }
  332. /**
  333. * Resumes a persisted user-input wait. This is a narrow internal admission
  334. * seam: it never joins the ordinary Queue, and requestId is its durable replay
  335. * identity.
  336. */
  337. export interface ConversationResumeUserInput {
  338. readonly sessionId: string;
  339. readonly source: "questionnaire";
  340. readonly requestId: string;
  341. /** Product owner whose suspended Turn this persisted reply continues. */
  342. readonly owner?: UserInputResumeOwner;
  343. /** Server-owned Turn identity for a Runtime-owned continuation such as Plan. */
  344. readonly requestedTurnId?: string;
  345. readonly message: ConversationMessageInput;
  346. }
  347. export interface UserInputResumeOwner {
  348. readonly kind: "thread-goal";
  349. readonly goalId: string;
  350. }
  351. export interface ConversationResumeUserInputResult {
  352. readonly turnId: string;
  353. readonly mode: "started" | "duplicate";
  354. }
  355. export interface ConversationSteerInput {
  356. readonly sessionId: string;
  357. readonly source: ConversationSource;
  358. readonly message: ConversationMessageInput;
  359. readonly producerId: string;
  360. readonly idempotencyKey: string;
  361. readonly requestedTurnId?: string;
  362. /**
  363. * Internal, opt-in admission hook for a producer that must verify the exact
  364. * Turn before its content is handed to the runtime. Ordinary steering does
  365. * not provide this hook and keeps its existing semantics.
  366. */
  367. readonly preDelivery?: ConversationSteerPreDelivery;
  368. }
  369. export interface ConversationSteerPreDelivery {
  370. accept(input: {
  371. readonly mode: "activated" | "steered";
  372. readonly turnId: string;
  373. }): void | Promise<void>;
  374. }
  375. /**
  376. * `activated` means the steer had no Turn to join and started one instead, so
  377. * it owns a completion just like `submit`. `steered` and `duplicate` join an
  378. * existing Turn owned by another producer and only carry the admission ACK.
  379. */
  380. export type ConversationSteerResult =
  381. | {
  382. readonly turnId: string;
  383. readonly mode: "steered" | "duplicate";
  384. }
  385. | {
  386. readonly turnId: string;
  387. readonly mode: "activated";
  388. readonly completion: Promise<ConversationTurnResult>;
  389. };
  390. export interface ConversationQueuedItem {
  391. readonly itemId: string;
  392. readonly sessionId: string;
  393. readonly agentName: string;
  394. readonly source: ConversationSource;
  395. readonly status: "queued" | "claimed";
  396. readonly message: ConversationMessageInput;
  397. readonly createdAt: number;
  398. readonly clientRequestId?: string;
  399. readonly dedupeKey?: string;
  400. readonly expiresAt?: number;
  401. }
  402. export interface ConversationQueueUpdate {
  403. readonly message?: ConversationMessageInput;
  404. readonly model?: ConversationModelSelection | null;
  405. readonly expiresAt?: number;
  406. }
  407. export interface ConversationIngress {
  408. submit(input: ConversationSubmitInput): Promise<ConversationAcceptedTurn>;
  409. resumeUserInput(
  410. input: ConversationResumeUserInput,
  411. ): Promise<ConversationResumeUserInputResult>;
  412. steer(input: ConversationSteerInput): Promise<ConversationSteerResult>;
  413. listQueued(sessionId: string): Promise<ConversationQueuedItem[]>;
  414. /**
  415. * Exact idempotency lookup. Unlike listQueued(), this includes an item that
  416. * is currently claimed so a producer does not mistake in-flight work for
  417. * completed work.
  418. */
  419. findQueuedByClientRequestId(
  420. sessionId: string,
  421. clientRequestId: string,
  422. ): Promise<ConversationQueuedItem | undefined>;
  423. updateQueued(
  424. sessionId: string,
  425. itemId: string,
  426. update: ConversationQueueUpdate,
  427. ): Promise<ConversationQueuedItem | "not_editable" | undefined>;
  428. promoteQueuedSource(
  429. sessionId: string,
  430. itemId: string,
  431. source: ConversationSource,
  432. ): Promise<ConversationQueuedItem | "not_editable" | undefined>;
  433. cancelQueued(
  434. sessionId: string,
  435. itemId: string,
  436. ): Promise<ConversationQueuedItem | "not_editable" | undefined>;
  437. reorderQueued(
  438. sessionId: string,
  439. itemIds: readonly string[],
  440. ): Promise<ConversationQueuedItem[]>;
  441. abort(sessionId: string, reason?: string, turnId?: string): Promise<boolean>;
  442. dispatchQueue(sessionId: string): Promise<void>;
  443. }
  444. export interface ConversationCompactionInput {
  445. readonly sessionId: string;
  446. readonly agentName: string;
  447. readonly customInstructions?: string;
  448. readonly reason?: string;
  449. readonly onStarted?: () => Promise<void>;
  450. }
  451. export interface ConversationCompactionOutcome {
  452. readonly success: boolean;
  453. readonly code: string;
  454. readonly status: number;
  455. readonly sessionId?: string;
  456. readonly compactionId?: string;
  457. readonly messagesBefore?: number;
  458. readonly messagesAfter?: number;
  459. readonly tokensBefore?: number;
  460. readonly tokensAfter?: number;
  461. readonly error?: string;
  462. }
  463. export interface ConversationMaintenance {
  464. compact(
  465. input: ConversationCompactionInput,
  466. ): Promise<ConversationCompactionOutcome>;
  467. }
  468. export interface RuntimeConversation {
  469. readonly query: ConversationSessionQuery;
  470. readonly lifecycle: ConversationSessionLifecycle;
  471. readonly ingress: ConversationIngress;
  472. readonly maintenance: ConversationMaintenance;
  473. }
  474. export interface RuntimeConversationChannelView {
  475. readonly query: Pick<ConversationSessionQuery, "getSession" | "listSessions">;
  476. readonly lifecycle: Pick<
  477. ConversationSessionLifecycle,
  478. "createSession" | "createRootSession" | "deleteSession"
  479. >;
  480. readonly ingress: Pick<
  481. ConversationIngress,
  482. "submit" | "abort" | "dispatchQueue"
  483. >;
  484. readonly maintenance: Pick<ConversationMaintenance, "compact">;
  485. }
  486. export const RUNTIME_CONVERSATION_UNAVAILABLE_CODE =
  487. "RUNTIME_CONVERSATION_UNAVAILABLE";
  488. export const RUNTIME_CONVERSATION_SHUTDOWN_CODE =
  489. "RUNTIME_CONVERSATION_SHUTDOWN";
  490. export class RuntimeConversationUnavailableError extends Error {
  491. readonly code = RUNTIME_CONVERSATION_UNAVAILABLE_CODE;
  492. readonly originalError?: unknown;
  493. constructor(
  494. message = "Runtime conversation is unavailable.",
  495. options?: { readonly cause?: unknown },
  496. ) {
  497. super(message);
  498. this.name = "RuntimeConversationUnavailableError";
  499. if (options && "cause" in options) this.originalError = options.cause;
  500. }
  501. }
  502. export class RuntimeConversationShutdownError extends Error {
  503. readonly code = RUNTIME_CONVERSATION_SHUTDOWN_CODE;
  504. readonly originalError?: unknown;
  505. constructor(
  506. message = "Runtime conversation is shutting down.",
  507. options?: { readonly cause?: unknown },
  508. ) {
  509. super(message);
  510. this.name = "RuntimeConversationShutdownError";
  511. if (options && "cause" in options) this.originalError = options.cause;
  512. }
  513. }
  514. export function isRuntimeConversationUnavailableError(error: unknown): boolean {
  515. return hasRuntimeConversationCode(
  516. error,
  517. RUNTIME_CONVERSATION_UNAVAILABLE_CODE,
  518. );
  519. }
  520. export function isRuntimeConversationShutdownError(error: unknown): boolean {
  521. return hasRuntimeConversationCode(error, RUNTIME_CONVERSATION_SHUTDOWN_CODE);
  522. }
  523. export class DeferredRuntimeConversation implements RuntimeConversation {
  524. private readonly readiness: Promise<RuntimeConversation>;
  525. private resolveReady!: (conversation: RuntimeConversation) => void;
  526. private rejectReady!: (error: unknown) => void;
  527. private bound?: RuntimeConversation;
  528. private terminalError?: unknown;
  529. private settled = false;
  530. readonly query: ConversationSessionQuery = {
  531. getSession: (sessionId) =>
  532. this.use((conversation) => conversation.query.getSession(sessionId)),
  533. listSessions: (options) =>
  534. this.use((conversation) => conversation.query.listSessions(options)),
  535. listMessages: (sessionId, options) =>
  536. this.use((conversation) =>
  537. conversation.query.listMessages(sessionId, options),
  538. ),
  539. };
  540. readonly lifecycle: ConversationSessionLifecycle = {
  541. createSession: (input) =>
  542. this.use((conversation) => conversation.lifecycle.createSession(input)),
  543. createRootSession: (input) =>
  544. this.use((conversation) =>
  545. conversation.lifecycle.createRootSession(input),
  546. ),
  547. replaceRootSession: (agentName, sessionId) =>
  548. this.use((conversation) =>
  549. conversation.lifecycle.replaceRootSession(agentName, sessionId),
  550. ),
  551. updateSession: (sessionId, fields) =>
  552. this.use((conversation) =>
  553. conversation.lifecycle.updateSession(sessionId, fields),
  554. ),
  555. deleteSession: (sessionId) =>
  556. this.use((conversation) =>
  557. conversation.lifecycle.deleteSession(sessionId),
  558. ),
  559. };
  560. readonly ingress: ConversationIngress = {
  561. submit: (input) =>
  562. this.use((conversation) => conversation.ingress.submit(input)),
  563. resumeUserInput: (input) =>
  564. this.use((conversation) => conversation.ingress.resumeUserInput(input)),
  565. steer: (input) =>
  566. this.use((conversation) => conversation.ingress.steer(input)),
  567. listQueued: (sessionId) =>
  568. this.use((conversation) => conversation.ingress.listQueued(sessionId)),
  569. findQueuedByClientRequestId: (sessionId, clientRequestId) =>
  570. this.use((conversation) =>
  571. conversation.ingress.findQueuedByClientRequestId(
  572. sessionId,
  573. clientRequestId,
  574. ),
  575. ),
  576. updateQueued: (sessionId, itemId, update) =>
  577. this.use((conversation) =>
  578. conversation.ingress.updateQueued(sessionId, itemId, update),
  579. ),
  580. promoteQueuedSource: (sessionId, itemId, source) =>
  581. this.use((conversation) =>
  582. conversation.ingress.promoteQueuedSource(sessionId, itemId, source),
  583. ),
  584. cancelQueued: (sessionId, itemId) =>
  585. this.use((conversation) =>
  586. conversation.ingress.cancelQueued(sessionId, itemId),
  587. ),
  588. reorderQueued: (sessionId, itemIds) =>
  589. this.use((conversation) =>
  590. conversation.ingress.reorderQueued(sessionId, itemIds),
  591. ),
  592. abort: (sessionId, reason, turnId) =>
  593. this.use((conversation) =>
  594. conversation.ingress.abort(sessionId, reason, turnId),
  595. ),
  596. dispatchQueue: (sessionId) =>
  597. this.use((conversation) => conversation.ingress.dispatchQueue(sessionId)),
  598. };
  599. readonly maintenance: ConversationMaintenance = {
  600. compact: (input) =>
  601. this.use((conversation) => conversation.maintenance.compact(input)),
  602. };
  603. constructor() {
  604. this.readiness = new Promise<RuntimeConversation>((resolve, reject) => {
  605. this.resolveReady = resolve;
  606. this.rejectReady = reject;
  607. });
  608. void this.readiness.catch(() => undefined);
  609. }
  610. bind(conversation: RuntimeConversation): void {
  611. if (this.settled)
  612. throw new Error("Runtime conversation binding is already settled.");
  613. this.settled = true;
  614. this.bound = conversation;
  615. this.resolveReady(conversation);
  616. }
  617. fail(error: unknown): void {
  618. if (this.settled) return;
  619. this.settled = true;
  620. this.terminalError = normalizeUnavailableError(error);
  621. this.rejectReady(this.terminalError);
  622. }
  623. shutdown(error?: unknown): void {
  624. if (isRuntimeConversationShutdownError(this.terminalError)) return;
  625. const normalized = normalizeShutdownError(error);
  626. this.terminalError = normalized;
  627. this.bound = undefined;
  628. if (!this.settled) {
  629. this.settled = true;
  630. this.rejectReady(normalized);
  631. }
  632. }
  633. private async use<T>(
  634. operation: (conversation: RuntimeConversation) => Promise<T>,
  635. ): Promise<T> {
  636. if (this.terminalError) throw this.terminalError;
  637. const conversation = this.bound ?? (await this.readiness);
  638. if (this.terminalError) throw this.terminalError;
  639. return operation(conversation);
  640. }
  641. }
  642. function normalizeUnavailableError(error: unknown): unknown {
  643. if (
  644. isRuntimeConversationUnavailableError(error) ||
  645. isRuntimeConversationShutdownError(error)
  646. ) {
  647. return error;
  648. }
  649. const message = error instanceof Error ? error.message : String(error);
  650. return new RuntimeConversationUnavailableError(message, { cause: error });
  651. }
  652. function normalizeShutdownError(
  653. error: unknown,
  654. ): RuntimeConversationShutdownError {
  655. if (error instanceof RuntimeConversationShutdownError) return error;
  656. const message = error instanceof Error ? error.message : undefined;
  657. return new RuntimeConversationShutdownError(message, { cause: error });
  658. }
  659. function hasRuntimeConversationCode(error: unknown, code: string): boolean {
  660. return (
  661. typeof error === "object" &&
  662. error !== null &&
  663. Reflect.get(error, "code") === code
  664. );
  665. }
  666. export type {
  667. ProcessLocalContext,
  668. ProcessLocalStreamResult,
  669. } from "./process-local.js";