@tangle-network/agent-app 4.0.35 → 4.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +19 -11
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-PZTBXHPE.js → chunk-725RZ5JQ.js} +2 -2
  17. package/dist/{chunk-ONIIKYVV.js → chunk-77UNTK66.js} +357 -290
  18. package/dist/chunk-77UNTK66.js.map +1 -0
  19. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  20. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  21. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  22. package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
  23. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  24. package/dist/chunk-DPD7LY3T.js.map +1 -0
  25. package/dist/{chunk-5WVGSCBN.js → chunk-MGW25KMR.js} +4 -4
  26. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  27. package/dist/{chunk-QFT2V2OE.js → chunk-RSSK6FUF.js} +2 -2
  28. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  29. package/dist/{chunk-LTCRS46I.js → chunk-VUI4IUIM.js} +25 -7
  30. package/dist/chunk-VUI4IUIM.js.map +1 -0
  31. package/dist/operator/index.js +2 -2
  32. package/dist/preset-cloudflare/index.js +6 -6
  33. package/dist/public-consultation/index.d.ts +1 -1
  34. package/dist/public-consultation/index.js +8 -8
  35. package/dist/runtime/index.js +3 -3
  36. package/dist/runtime/router-turn.js +2 -2
  37. package/dist/sandbox/index.js +4 -4
  38. package/dist/turn-stream/cancellation.d.ts +16 -0
  39. package/dist/turn-stream/core.d.ts +4 -0
  40. package/dist/turn-stream/do.d.ts +4 -2
  41. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  42. package/dist/turn-stream/index.js +122 -5
  43. package/dist/turn-stream/index.js.map +1 -1
  44. package/dist/turn-trace/index.js +1 -1
  45. package/dist/web-react/chat-stream.d.ts +4 -2
  46. package/dist/web-react/index.js +13 -5
  47. package/package.json +1 -1
  48. package/dist/chunk-7VJCMEEE.js.map +0 -1
  49. package/dist/chunk-K2JPSXKI.js.map +0 -1
  50. package/dist/chunk-LTCRS46I.js.map +0 -1
  51. package/dist/chunk-NAMSFODC.js.map +0 -1
  52. package/dist/chunk-ONIIKYVV.js.map +0 -1
  53. /package/dist/{chunk-PZTBXHPE.js.map → chunk-725RZ5JQ.js.map} +0 -0
  54. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  55. /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
  56. /package/dist/{chunk-5WVGSCBN.js.map → chunk-MGW25KMR.js.map} +0 -0
  57. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  58. /package/dist/{chunk-QFT2V2OE.js.map → chunk-RSSK6FUF.js.map} +0 -0
  59. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -1,5 +1,14 @@
1
1
  /** Stream framing, event inspection and cancellation around a chat producer. */
2
2
  import type { ChatRouteEvent } from './turn-route-contracts.js';
3
+ /** A view queues bytes without making execution wait for a connected reader. */
4
+ export declare function createTurnView(): {
5
+ readable: ReadableStream<Uint8Array<ArrayBufferLike>>;
6
+ readonly disconnected: boolean;
7
+ write(chunk: Uint8Array): void;
8
+ close(): void;
9
+ };
10
+ /** One safe pre-execution response for the server-owned host control signal. */
11
+ export declare function turnControlResponse(signal: AbortSignal): Response;
3
12
  /** The original data of a failure event whose reason a producer withheld from the person. A Symbol key: JSON, and so
4
13
  * the wire and the turn buffer, drops it, while the route's own hooks read it through {@link serverFailureData}. */
5
14
  export declare const WITHHELD_FAILURE: unique symbol;
@@ -29,7 +38,7 @@ export declare function withStreamHeartbeat(source: AsyncIterable<ChatRouteEvent
29
38
  /** Sequential concat of byte streams (marker line, then the engine body). */
30
39
  export declare function concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array>;
31
40
  /**
32
- * Stop a producer pull as soon as an opted-in caller disconnects.
41
+ * Stop a producer pull when its request or maintained owner control aborts.
33
42
  * `AsyncIterator.return()` alone cannot interrupt a pending `next()` call, so
34
43
  * race each pull with the request signal and close the source in `finally`.
35
44
  */
@@ -1,7 +1,9 @@
1
+ import { type BufferedTurnTap } from '../stream/index.js';
1
2
  import type { TurnTraceSink } from '../turn-trace/recorder.js';
2
- import { type AssistantDraftStore, type DraftPersistenceTuning } from './draft-persistence.js';
3
+ import { type NativeTimingTransfer } from './native-turn-timing.js';
4
+ import { type AssistantDraftStore, type AssistantDraftWriter, type DraftPersistenceTuning } from './draft-persistence.js';
3
5
  import { type AdmittedTurn, type TurnProgressCallback } from './turn-admission.js';
4
- import type { ChatTurnRequestContext, ChatTurnTraceOptions } from './turn-route-contracts.js';
6
+ import type { ChatTurnLifecycleComplete, ChatTurnRequestContext, ChatTurnRouteProducer, ChatTurnTraceOptions } from './turn-route-contracts.js';
5
7
  import type { TurnRoutePhase } from './turn-progress.js';
6
8
  import type { ResolvedChatTurnRoutesOptions } from './route-storage.js';
7
9
  import type { AfterAuthorizeWork } from './early-turn-work.js';
@@ -13,8 +15,37 @@ interface TurnExecutionOptions<TContext, TResource> {
13
15
  traceOptions: ChatTurnTraceOptions<TContext> | undefined;
14
16
  traceSink: TurnTraceSink | undefined;
15
17
  traceReceipt(request: Request, executionId: string): Record<string, string>;
16
- startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined;
18
+ startIntentLine(admitted: AdmittedTurn<TContext>, stop?: AbortSignal): Promise<string | null> | undefined;
17
19
  log(message: string, meta?: Record<string, unknown>): void;
18
20
  }
21
+ /** Bind the route's construction-time dependencies; each invocation retains its own turn state. */
19
22
  export declare function createAdmittedTurnRunner<TContext, TResource>(dependencies: TurnExecutionOptions<TContext, TResource>): (request: Request, ctx: ChatTurnRequestContext | undefined, admitted: AdmittedTurn<TContext>, early: AfterAuthorizeWork<TResource>, progress?: TurnProgressCallback | undefined, startedIntent?: Promise<string | null> | undefined) => Promise<Response>;
23
+ export interface AdmittedTurnState<TContext> {
24
+ executionAbort: AbortController;
25
+ closeCancellation: (() => Promise<void>) | undefined;
26
+ draft: AssistantDraftWriter | undefined;
27
+ tap: BufferedTurnTap | undefined;
28
+ nativeTiming: NativeTimingTransfer | undefined;
29
+ completionHandoff: boolean;
30
+ completionHandoffPromise: Promise<void> | undefined;
31
+ lockAcquired: boolean;
32
+ lockHandle: unknown;
33
+ lockReleased: boolean;
34
+ cancellationAbort?: AbortController;
35
+ producer: ChatTurnRouteProducer | undefined;
36
+ producerError: unknown;
37
+ assistantMessageId: string | null | undefined;
38
+ runFailed: boolean;
39
+ lastFailureData: Record<string, unknown> | undefined;
40
+ turnStartedAtMs: number;
41
+ firstVisibleAtMs: number | undefined;
42
+ firstTextAtMs: number | undefined;
43
+ turnStarted: boolean;
44
+ lifecycleSettled: boolean;
45
+ settledTurn: ChatTurnLifecycleComplete<TContext> | undefined;
46
+ gatedTurn: boolean;
47
+ legacyHandoff: boolean;
48
+ pendingTraceExport: (() => void | Promise<void>) | undefined;
49
+ traceEnded: boolean;
50
+ }
20
51
  export {};
@@ -0,0 +1,5 @@
1
+ /** Optional intent preview for an already admitted turn; never owns execution. */
2
+ import type { AdmittedTurn } from './turn-admission.js';
3
+ import type { ResolvedChatTurnRoutesOptions } from './route-storage.js';
4
+ /** Start the admitted turn's intent line; resolves to the line, or null. Never rejects. */
5
+ export declare function startTurnIntentLine<TContext, TResource>(options: ResolvedChatTurnRoutesOptions<TContext, TResource>, log: (message: string, meta?: Record<string, unknown>) => void, admitted: AdmittedTurn<TContext>, stop?: AbortSignal): Promise<string | null> | undefined;
@@ -19,6 +19,11 @@
19
19
  * caller already handles. A client that does not send the header gets exactly
20
20
  * the responses it got before.
21
21
  *
22
+ * The separate opt-in host-control envelope starts after identity/editor/thread
23
+ * authorization, before paid admission. Its control event grants no execution
24
+ * permission. Full admission still precedes accepted progress and all execution;
25
+ * a later refusal is carried by turn.response. Legacy callers are unchanged.
26
+ *
22
27
  * Product work that only an admitted turn may do (resolving its profile and
23
28
  * model, any write) belongs in `prepareTurn`, which runs after admission and,
24
29
  * on a progress-first stream, inside it with its own named stages.
@@ -31,6 +36,24 @@
31
36
  export declare const TURN_PROGRESS_HEADER = "x-turn-progress";
32
37
  /** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */
33
38
  export declare const TURN_PROGRESS_FIRST = "first";
39
+ /** Opt in to the hosted invocation's identity envelope before paid admission. */
40
+ export declare const TURN_HOST_CONTROL_HEADER = "x-turn-host-control";
41
+ export declare const TURN_HOST_CONTROL_FIRST = "first";
42
+ /** A control address, never paid admission, execution authority or assistant content. */
43
+ export declare const TURN_HOST_CONTROL_EVENT = "turn.host.control";
44
+ export interface TurnHostControlTarget {
45
+ hostId: string;
46
+ workspaceId: string;
47
+ threadId: string;
48
+ clientTurnId?: string;
49
+ retryAttemptId?: string;
50
+ }
51
+ export type TurnHostControlEvent = {
52
+ type: typeof TURN_HOST_CONTROL_EVENT;
53
+ data: TurnHostControlTarget;
54
+ };
55
+ /** Validate the envelope without interpreting its opaque host id as authority. */
56
+ export declare function isTurnHostControlEvent(value: unknown): value is TurnHostControlEvent;
34
57
  /** Stream event naming the turn's current stage. Non-terminal and never turn content. */
35
58
  export declare const TURN_PHASE_EVENT = "session.run.phase";
36
59
  /**
@@ -118,5 +141,6 @@ export declare function turnResponseEventFor(response: Response): Promise<{
118
141
  * handling runs unchanged. Any other event resolves to a `Response` whose body
119
142
  * starts at that event and continues with the rest of the stream. A response
120
143
  * that is not progress-first is returned as it is.
144
+ * Opt-in host envelopes require onHostControl; its receipt is not admission.
121
145
  */
122
- export declare function settleTurnResponse(response: Response, onPhase: (phase: TurnPhaseData) => void, onIntent?: (intent: TurnIntentData) => void): Promise<Response>;
146
+ export declare function settleTurnResponse(response: Response, onPhase: (phase: TurnPhaseData) => void, onIntent?: (intent: TurnIntentData) => void, onHostControl?: (target: TurnHostControlTarget) => void): Promise<Response>;
@@ -10,9 +10,11 @@ import type { InteractionAnswerRoute, InteractionAnswerRouteOptions } from '../i
10
10
  import type { ModelFailoverAttempt } from '../model-resolution/failover.js';
11
11
  import type { ModelPolicy } from '../policy-filters/index.js';
12
12
  import type { PersistedChatMessageForTurn, TurnEventStore } from '../stream/index.js';
13
+ import type { TurnStreamAuth } from '../turn-stream/adapters.js';
14
+ import type { TurnHostControlNamespace } from '../turn-stream/cancellation.js';
13
15
  import type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder.js';
14
16
  import type { TurnTraceReader } from '../turn-trace/otel.js';
15
- import type { TurnRoutePhase } from './turn-progress.js';
17
+ import type { TurnHostControlTarget, TurnRoutePhase } from './turn-progress.js';
16
18
  import type { AgentProfile } from '@tangle-network/agent-interface';
17
19
  import type { AgentMention, ChatTurnPartInput, ChatTurnRequestPayload } from './wire.js';
18
20
  import type { RouterTurnProducerOptions } from './router-producer.js';
@@ -238,6 +240,16 @@ export interface ChatTurnRequestContext {
238
240
  executionLimits?: ChatTurnExecutionLimits;
239
241
  /** Set by `TurnStreamDO` on the turn it runs for `turnHost`: the route runs it there, never forwarding it again. */
240
242
  hosted?: boolean;
243
+ /** Supplied only by the existing per-turn host. Independent of browser disconnect;
244
+ * retain through the owned drain/disposal and forward this context unchanged. */
245
+ hostControl?: {
246
+ readonly hostId: string;
247
+ readonly signal: AbortSignal;
248
+ bind(target: TurnHostControlTarget, owner: {
249
+ namespace: TurnHostControlNamespace;
250
+ auth: TurnStreamAuth;
251
+ }): Promise<void>;
252
+ };
241
253
  }
242
254
  /** A workspace agent a turn is addressed to, resolved by the product from an
243
255
  * `@` mention. `id` is the stable profile id the mention carried. */
@@ -693,6 +705,22 @@ export interface CreateChatTurnRoutesOptions<TContext = void, TResource = unknow
693
705
  * - The class's `turnRoutes` must pass `ctx` through unchanged: its `hosted` mark stops the object forwarding the
694
706
  * turn again. */
695
707
  turnHost?: import('../turn-stream/adapters.js').TurnHost;
708
+ /** Opt-in early host-control identity, before full paid authorization. Verify the
709
+ * caller's identity, editor access and the actual thread's workspace. Return the
710
+ * canonical workspace as tenantId; this grants no permission to execute. Only
711
+ * requests with x-turn-host-control:first call it; an unavailable host still
712
+ * refuses execution after this identity check. Legacy HTTP refusals
713
+ * are unchanged. Any authorized editor may Stop the exact workspace invocation. */
714
+ authorizeHostControl?(args: {
715
+ request: Request;
716
+ body: ChatTurnRequestPayload;
717
+ }): Promise<{
718
+ ok: true;
719
+ tenantId: string;
720
+ } | {
721
+ ok: false;
722
+ response: Response;
723
+ }>;
696
724
  /** Pre-turn readiness gate that can short-circuit with a product `Response`
697
725
  * before the producer runs (the user row is already persisted). Runs after
698
726
  * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.
@@ -850,7 +878,8 @@ export interface ChatTurnRoutes {
850
878
  * event protocol. Pass the platform's `waitUntil` so the turn keeps
851
879
  * running (and buffering) after a client disconnect. A request with
852
880
  * `TURN_PROGRESS_HEADER` gets a progress-first stream once it is
853
- * authorized (`./turn-progress`). */
881
+ * authorized (`./turn-progress`). The separate opt-in hosted control
882
+ * envelope requires authorizeHostControl and a client control handler. */
854
883
  turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>;
855
884
  /** POST — stop the exact authorized execution; unavailable unless configured. */
856
885
  cancel(request: Request): Promise<Response>;
@@ -0,0 +1,23 @@
1
+ /** Lifecycle hooks and trace settlement for the route's existing live projection. */
2
+ import type { ChatTurnIdentity } from '@tangle-network/agent-runtime/durable';
3
+ import type { TurnTraceSink, TurnTraceSnapshot } from '../turn-trace/recorder.js';
4
+ import type { AdmittedTurn } from './turn-admission.js';
5
+ import type { AdmittedTurnState } from './turn-execution.js';
6
+ import type { ResolvedChatTurnRoutesOptions } from './route-storage.js';
7
+ import type { ChatTurnModelAttribution, ChatTurnRequestContext, ChatTurnTraceOptions } from './turn-route-contracts.js';
8
+ /** One requested-versus-served projection for persistence and both completion receipts. */
9
+ export declare function modelAttributionFields(attribution: ChatTurnModelAttribution | undefined): {
10
+ requestedModel?: string | undefined;
11
+ servedModel?: string | undefined;
12
+ servedProvider?: string | undefined;
13
+ servedSource?: "environment" | "profile" | "request" | undefined;
14
+ };
15
+ export declare function createTurnSettlement<TContext, TResource>(state: AdmittedTurnState<TContext>, trace: AdmittedTurn<TContext>['trace'], options: ResolvedChatTurnRoutesOptions<TContext, TResource>, executionId: string, traceSink: TurnTraceSink | undefined, identity: ChatTurnIdentity, traceOptions: ChatTurnTraceOptions<TContext> | undefined, context: TContext, turnStreamId: `${string}-${string}-${string}-${string}-${string}`, log: (message: string, meta?: Record<string, unknown>) => void, ctx: ChatTurnRequestContext | undefined, userMessageId: () => string | null | undefined): {
16
+ endTrace: (failed: boolean, terminalError: unknown) => TurnTraceSnapshot;
17
+ exportTraceInBackground: () => void;
18
+ startLifecycle: (gated?: boolean) => Promise<void> | undefined;
19
+ fireTerminalLifecycle: (failed: boolean, terminalError: unknown) => Promise<void>;
20
+ assistantRowId: () => string | null;
21
+ exportTrace: () => Promise<void>;
22
+ runAfterSettle: () => Promise<void>;
23
+ };
@@ -16,13 +16,13 @@ import {
16
16
  mentionInputToPart,
17
17
  mentionPartsFromMessageParts,
18
18
  toChatMessageParts
19
- } from "../chunk-4YZKDWMB.js";
19
+ } from "../chunk-SADNHPAY.js";
20
20
  import "../chunk-ZVEEWGDK.js";
21
21
  import {
22
22
  attachmentPartKey
23
23
  } from "../chunk-JM6ANMOA.js";
24
24
  import "../chunk-TB6KNPFI.js";
25
- import "../chunk-K2JPSXKI.js";
25
+ import "../chunk-6YLVFV3F.js";
26
26
  import "../chunk-T3C2BX7N.js";
27
27
  import "../chunk-TXD5HXLE.js";
28
28
 
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-QUV5M7SZ.js";
4
4
  import {
5
5
  toChatMessageParts
6
- } from "./chunk-4YZKDWMB.js";
6
+ } from "./chunk-SADNHPAY.js";
7
7
  import {
8
8
  asRecord,
9
9
  asString
@@ -11,6 +11,10 @@ import {
11
11
  import {
12
12
  SandboxRunError
13
13
  } from "./chunk-2IGXFHUO.js";
14
+ import {
15
+ TurnCancellationRequestedError,
16
+ TurnControlUnavailableError
17
+ } from "./chunk-AOSQ5JCO.js";
14
18
  import {
15
19
  ModelFailoverExhaustedError,
16
20
  isUpstreamUnavailable,
@@ -683,6 +687,46 @@ function createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstRe
683
687
  }
684
688
 
685
689
  // src/chat-routes/turn-event-stream.ts
690
+ function createTurnView() {
691
+ let disconnected = false;
692
+ let controller;
693
+ const readable = new ReadableStream({
694
+ start(value) {
695
+ controller = value;
696
+ },
697
+ cancel() {
698
+ disconnected = true;
699
+ }
700
+ });
701
+ return {
702
+ readable,
703
+ get disconnected() {
704
+ return disconnected;
705
+ },
706
+ write(chunk) {
707
+ if (disconnected) return;
708
+ try {
709
+ controller.enqueue(chunk);
710
+ } catch {
711
+ disconnected = true;
712
+ }
713
+ },
714
+ close() {
715
+ if (disconnected) return;
716
+ try {
717
+ controller.close();
718
+ } catch {
719
+ }
720
+ }
721
+ };
722
+ }
723
+ function turnControlResponse(signal) {
724
+ const requested = signal.reason instanceof TurnCancellationRequestedError;
725
+ return Response.json({
726
+ error: requested ? "Stop was requested for this turn." : "Turn control was lost.",
727
+ code: requested ? "turn_cancel_requested" : "turn_control_unavailable"
728
+ }, { status: requested ? 409 : 503 });
729
+ }
686
730
  var WITHHELD_FAILURE = /* @__PURE__ */ Symbol("withheld failure");
687
731
  function serverFailureData(data) {
688
732
  const original = data?.[WITHHELD_FAILURE];
@@ -803,7 +847,7 @@ async function* abortOnSignal(source, signal) {
803
847
  }
804
848
  }
805
849
  function nextWithAbort(iterator, signal) {
806
- if (signal.aborted) return Promise.reject(new Error("chat turn cancelled"));
850
+ if (signal.aborted) return Promise.reject(cancellationReason(signal));
807
851
  return new Promise((resolve, reject) => {
808
852
  let settled = false;
809
853
  const cleanup = () => signal.removeEventListener("abort", onAbort);
@@ -811,7 +855,7 @@ function nextWithAbort(iterator, signal) {
811
855
  if (settled) return;
812
856
  settled = true;
813
857
  cleanup();
814
- reject(new Error("chat turn cancelled"));
858
+ reject(cancellationReason(signal));
815
859
  };
816
860
  signal.addEventListener("abort", onAbort, { once: true });
817
861
  if (signal.aborted) {
@@ -834,6 +878,10 @@ function nextWithAbort(iterator, signal) {
834
878
  );
835
879
  });
836
880
  }
881
+ function cancellationReason(signal) {
882
+ const reason = signal.reason;
883
+ return reason instanceof TurnCancellationRequestedError || reason instanceof TurnControlUnavailableError ? reason : new Error("chat turn cancelled");
884
+ }
837
885
  var ABORT_CLEANUP_TIMEOUT_MS = 50;
838
886
  async function closeIteratorAfterAbort(iterator) {
839
887
  let closing;
@@ -1111,6 +1159,8 @@ export {
1111
1159
  createAssistantDraftWriter,
1112
1160
  storeSupportsDraftPersistence,
1113
1161
  rowIdOf,
1162
+ createTurnView,
1163
+ turnControlResponse,
1114
1164
  WITHHELD_FAILURE,
1115
1165
  serverFailureData,
1116
1166
  failureReasonOf,
@@ -1144,4 +1194,4 @@ export {
1144
1194
  sandboxStreamFailureDiagnostic,
1145
1195
  withoutToolList
1146
1196
  };
1147
- //# sourceMappingURL=chunk-NAMSFODC.js.map
1197
+ //# sourceMappingURL=chunk-4YBNKXUE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/visible-text.ts","../src/chat-routes/draft-persistence.ts","../src/chat-routes/model-failover-stream.ts","../src/chat-routes/turn-event-stream.ts","../src/chat-routes/failure-wording.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Apply a product's final-text transform (a PII redactor, for example) to every\n * stored part a reader sees as words: the answer's text parts and the reasoning\n * parts, which also hold a Router turn's pre-tool narration. One rule for the\n * final row, the draft row and the detached-turn row.\n */\nexport function transformVisibleTextParts<T>(\n parts: readonly T[],\n transform: (text: string) => string | Promise<string>,\n): Promise<T[]> {\n return Promise.all(parts.map(async (part) => {\n const type = String((part as { type?: unknown }).type ?? '')\n return type === 'text' || type === 'reasoning'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part\n }))\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY, in serialized UTF-8\n * bytes (including JSON escaping and the preview marker). A tool returning\n * a large blob would otherwise be rewritten in full on every draft.\n * `draftTruncated` marks a clipped preview even if the cap cannot fit its\n * text marker; below 2 bytes the draft omits the output value. The final\n * write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. This is not a bound on the whole parts array. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\nconst encoder = new TextEncoder()\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. Metadata marks every\n * clipped preview, with a text marker when it fits. Finalization restores the\n * untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined) return part\n const text = typeof output === 'string' ? output : safeStringify(output)\n // A longer string cannot fit even before escaping. Avoid serializing and\n // encoding the entire large tool body just to establish that lower bound.\n const serialized = typeof output === 'string' && text.length <= maxBytes ? safeStringify(text) : text\n if (serialized.length <= maxBytes && encoder.encode(serialized).byteLength <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: draftOutputPreview(text, maxBytes),\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\n/** A preview is a string even when the retained output is structured. Bound\n * that stored string, whose JSON escaping may expand the source a second\n * time. Never cut a valid surrogate pair while finding the fitting prefix. */\nfunction draftOutputPreview(text: string, maxBytes: number): string | undefined {\n if (maxBytes < 2) return undefined\n const marker = '…[draft-truncated]'\n const suffix = serializedBytes(marker) <= maxBytes ? marker : ''\n const prefix = (end: number): string => {\n if (end > 0 && (text.codePointAt(end - 1) ?? 0) > 0xffff) end -= 1\n return text.slice(0, end)\n }\n let low = 0\n let high = Math.min(text.length, Math.floor(maxBytes))\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if (serializedBytes(prefix(middle) + suffix) <= maxBytes) low = middle\n else high = middle - 1\n }\n return prefix(low) + suffix\n}\n\nfunction serializedBytes(value: unknown): number {\n return encoder.encode(safeStringify(value)).byteLength\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? serializedBytes(values.parts) : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\nexport { assistantRowIdForTurn } from '../turn-trace/url'\n","/**\n * Model failover for a STREAMING turn.\n *\n * `/model-resolution`'s `runWithModelFailover` already owns the policy: walk a\n * chain, classify a resolved-or-thrown signal, re-throw a non-outage failure\n * immediately, and carry the attempt trail. This module does NOT re-implement\n * any of that — it composes it. What it adds is the one thing a whole-call\n * primitive cannot express, because a stream fails PARTWAY:\n *\n * **A turn may only fail over before its first client-visible byte.**\n *\n * Once a text delta, tool call, or ask has reached the browser (and the\n * persisted transcript), restarting on another model would duplicate the\n * answer. So each attempt is probed: open the stream, pull events into a small\n * buffer, and decide at the first meaningful event whether this model is\n * serving. Committing replays the buffer and hands the live iterator through;\n * abandoning discards the buffer (those events describe the dead model's\n * session — including its `step-finish` usage, which must never be billed) and\n * lets `runWithModelFailover` walk to the next model.\n *\n * `liveLifecycleEvents` relaxes the buffer for progress only. `start`,\n * `status`, `model-processing`, and session lifecycle carry no answer and no\n * receipt, so a product may take them the moment they arrive and show what\n * the turn is waiting on.\n * OpenCode reports whole parts, so the buffer held every event for 16 s and\n * the product could show nothing through provisioning and agent startup. Off\n * by default: with it on, an abandoned model's progress stays in the stream.\n *\n * The classification itself is `isUpstreamUnavailable` verbatim, so this path\n * inherits the measured facts from the 2026-07-25 outage — above all that an\n * outage is NOT always a thrown error: the sandbox RESOLVES a terminal `error`\n * event carrying `{ errorCode: 'provider_inference_unavailable' }`, which a\n * classifier inspecting only `catch` misses entirely. That resolved shape is\n * the whole reason the breakage went unnoticed, so it is classified here first.\n *\n * Conservative by construction:\n * - A terminal failure that is NOT an outage (400, bad schema, content filter)\n * COMMITS rather than failing over — it surfaces to the user exactly as it\n * does today. Those fail identically on every model; walking the chain would\n * only multiply latency and spend to reach the same error.\n * - A clean stream that produced nothing NEVER walks the chain. An empty answer\n * is not evidence of a dead upstream, and a silent re-roll on another model is\n * precisely the unattributable downgrade this work exists to prevent. Opt-in\n * `emptyTurnRetries` re-runs the SAME model instead, which leaves attribution\n * untouched — measured on production 2026-07-27, an empty turn is a transient\n * platform flake that a same-model re-run recovers (8 hard cases: 7/8\n * delivered on the first pass, 8/8 with one re-run, at a cost of 1 extra turn\n * in 9). Default `0`, so the behavior is unchanged unless a product asks.\n * - A responsive chain of length 1 costs no extra call or latency and remains\n * byte-identical to no failover. A silent chain of two or more models is\n * bounded by the first-answer deadline; one model keeps only its open deadline.\n */\n\nimport {\n isUpstreamUnavailable,\n ModelFailoverExhaustedError,\n readUpstreamUnavailableCode,\n readHttpStatusHint,\n runWithModelFailover,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { asRecord, asString } from '../stream/index'\n\n/** Terminal event types that end an attempt with a failure verdict. */\nconst TERMINAL_FAILURE_TYPES = new Set(['error', 'session.run.failed'])\n\n/**\n * Part types that carry no transcript content. They are buffered like anything\n * else — replayed verbatim when the attempt commits — but their presence alone\n * never commits a model, so an outage arriving right after a `step-start` is\n * still recoverable. `step-finish` matters most: it carries the abandoned\n * attempt's token/cost receipt, which must be discarded rather than billed.\n */\nconst NON_COMMITTING_PART_TYPES = new Set(['step-start', 'step-finish'])\n\n/**\n * True when `event` puts content in front of the user (or in the persisted\n * transcript), making a restart on another model unsafe.\n *\n * Deliberately an allow-list of KNOWN-INERT types rather than a deny-list: an\n * unrecognized event commits. Getting this wrong in the safe direction costs a\n * missed failover; getting it wrong the other way duplicates a user's answer.\n */\nexport function isCommittingSandboxEvent(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (!type) return false\n\n if (type === 'message.part.updated') {\n const data = asRecord(record.data)\n const part = asRecord(data?.part)\n const partType = asString(part?.type) ?? ''\n if (NON_COMMITTING_PART_TYPES.has(partType)) return false\n // A text/reasoning part with NO content yet (the platform opens the part\n // with `text: \"\"` before the first token — verbatim in the 2026-07-26\n // capture) puts nothing in front of the user; discarding it cannot\n // duplicate an answer. The first real token commits.\n if (partType === 'text' || partType === 'reasoning') {\n return [data?.delta, part?.text, part?.content]\n .some(value => typeof value === 'string' && value.length > 0)\n }\n return true\n }\n\n // Session/turn lifecycle, progress status, and warnings belong to the\n // attempt, not the transcript — discardable with an abandoned model.\n // Captured examples: a dead model\n // emits `start`, `execution.started`, `status`×3, `session.updated`×2,\n // `warning`×2 BEFORE its terminal `error` — any one of them committing\n // would pin the turn to the dead model and kill the failover.\n if (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle' ||\n type === 'step-start' ||\n type === 'step-finish' ||\n type === 'turn' ||\n type === 'warning'\n ) {\n return false\n }\n\n // Everything else — text/tool shapes the producer folds, asks, plans,\n // `result`/`done`, and any type this shell does not recognize — commits.\n return true\n}\n\n/**\n * Condense an abandoned attempt's raw failure text into something safe to show\n * a customer in the transcript.\n *\n * Measured on the live router 2026-07-27 19:40 UTC: an edge 5xx arrives as\n * Cloudflare's full HTML error PAGE, so the verbatim reason began\n * `<!DOCTYPE html>\\n<!--[if lt IE 7]> <html class=\"no-js ie6 oldie\"…` and the\n * fallback notice pasted 200 bytes of that markup into the answer the customer\n * reads. The cause is worth stating; the markup is not.\n *\n * Only the DISPLAY string is condensed. The full text stays on\n * `modelFailover.attempts[].reason` for the operator, so nothing is lost —\n * this narrows what the customer sees, never what telemetry records.\n */\nexport function summarizeFailoverReason(reason: string): string {\n const collapsed = reason.replace(/\\s+/g, ' ').trim()\n if (!collapsed) return 'upstream unavailable'\n\n // An HTML error page carries no message worth quoting — the status is the\n // whole content. Detected on the ORIGINAL text, before collapsing, because\n // that is the form the producer hands over.\n if (/<!doctype html|<html[\\s>]/i.test(collapsed)) {\n const status = readHttpStatusHint(collapsed)\n return status ? `HTTP ${status}` : 'upstream returned an error page'\n }\n\n // Anything else is a real message. Cap it so a verbose upstream cannot push\n // the answer off the screen, and cut on a word boundary when one is near.\n const LIMIT = 160\n if (collapsed.length <= LIMIT) return collapsed\n const clipped = collapsed.slice(0, LIMIT)\n const lastSpace = clipped.lastIndexOf(' ')\n return `${(lastSpace > LIMIT - 30 ? clipped.slice(0, lastSpace) : clipped).trimEnd()}…`\n}\n\n/** A terminal failure event, classified. `outage` decides failover vs surface. */\ninterface TerminalFailure {\n outage: boolean\n reason: string\n code?: string\n}\n\n/**\n * Classify a terminal failure event. Returns `null` for any non-terminal event.\n *\n * The RESOLVED shape is checked first and deliberately: the sandbox reports an\n * upstream outage by resolving `{ success: false, errorCode:\n * 'provider_inference_unavailable' }` inside a terminal `error` event's `data`,\n * never by throwing. Both `data` and the whole record are offered to\n * `isUpstreamUnavailable` so a payload nested either way is caught.\n */\n/**\n * Progress the consumer may see before the commit point: it names no model\n * output and carries no billing receipt, so streaming it live cannot duplicate\n * an answer or bill an abandoned attempt. `warning` and every\n * `message.part.updated` (including `step-start`/`step-finish`) stay buffered.\n */\nexport function isLiveLifecycleEvent(event: unknown): boolean {\n const type = asString(asRecord(event)?.type) ?? ''\n return (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle'\n )\n}\n\nexport function classifyTerminalFailure(event: unknown): TerminalFailure | null {\n const record = asRecord(event)\n if (!record) return null\n const type = asString(record.type) ?? ''\n if (!TERMINAL_FAILURE_TYPES.has(type)) return null\n\n const data = asRecord(record.data)\n const outage = isUpstreamUnavailable(data) || isUpstreamUnavailable(record)\n const reason =\n asString(data?.message) ??\n asString(data?.error) ??\n asString(data?.reason) ??\n asString(record.message) ??\n `sandbox stream reported ${type}`\n const code =\n readUpstreamUnavailableCode(data) ??\n asString(data?.errorCode) ??\n asString(data?.code) ??\n readUpstreamUnavailableCode(record) ??\n asString(record.errorCode) ??\n asString(record.code)\n return { outage, reason, ...(code ? { code } : {}) }\n}\n\n/** A model that served: its buffered preamble plus the still-live iterator. */\ninterface AttemptCommit {\n committed: true\n buffered: unknown[]\n /** `null` when the stream already ended during the probe. */\n iterator: AsyncIterator<unknown> | null\n /** Cancel transport work when this attempt is drained or abandoned. */\n abort: () => void\n}\n\n/**\n * A model whose upstream is down. `error`/`errorCode` are read by\n * `runWithModelFailover`'s attempt-trail describe(), so the trail names the\n * real upstream cause rather than a wrapper's own words.\n */\ninterface AttemptOutage {\n committed: false\n error: string\n errorCode?: string\n timeoutCode?: ModelAttemptTimeoutCode\n}\n\ntype AttemptOutcome = AttemptCommit | AttemptOutage\n\n/** Open the raw turn stream for one specific model. */\nexport type OpenModelStream = (args: {\n model: string\n /** 1 for the preferred model, 2 for the first fallback, and so on. */\n attempt: number\n /** Aborted when this attempt times out, is abandoned, or finishes. Forward\n * this to `streamSandboxPrompt(..., { signal })` so a blocked transport is\n * cancelled immediately rather than only receiving iterator.return(). */\n signal: AbortSignal\n}) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>\n\n/** Fired when a model is abandoned and the next one is about to be tried. */\nexport interface ModelFallbackInfo {\n from: string\n to: string\n reason: string\n}\n\n/** Define inputs for streaming a turn across a model failover chain */\nexport interface ModelFailoverStreamOptions {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n open: OpenModelStream\n /**\n * Product admission policy applied to EVERY chain member before its stream\n * is opened — see `runWithModelFailover`'s `policy`. A member the policy\n * refuses is skipped (never opened, never sent the turn's data) and the walk\n * continues; an all-refused chain ends in `ModelFailoverExhaustedError`.\n */\n policy?: ModelPolicy\n /**\n * Maximum time to open/start one model's event source, including its first\n * iterator pull. Default 120 seconds, matching the sandbox provisioning\n * ceiling so cold infrastructure startup is bounded independently from\n * provider inference.\n */\n openTimeoutMs?: number\n /**\n * Hard deadline from the source's first lifecycle event to its first\n * answer-bearing event. Default 60 seconds when the chain has another model\n * to fail over to; a one-model chain has no default deadline, because ending\n * its only attempt loses an answer a slow first token was still bringing.\n * Processing/lifecycle events do not commit the attempt and do not extend\n * this deadline.\n */\n firstResponseTimeoutMs?: number\n /** Override the commit-point rule. Default {@link isCommittingSandboxEvent}. */\n isCommitting?: (event: unknown) => boolean\n /**\n * Stream {@link isLiveLifecycleEvent} progress to the consumer as it arrives\n * instead of holding it until the attempt commits. Default `false`, which\n * keeps an abandoned model's events entirely off the wire. With it on, such\n * an event is never replayed from the buffer, and one from an abandoned\n * attempt stays in the stream — it describes the sandbox, not the answer.\n */\n liveLifecycleEvents?: boolean\n onFallback?: (info: ModelFallbackInfo) => void\n /**\n * How many times to RE-RUN THE SAME MODEL when a turn completes having\n * produced no assistant text at all. Default `0` — byte-identical to no\n * retry.\n *\n * This is deliberately not a chain walk. Falling over to a different model\n * on an empty answer is the unattributable downgrade this module refuses to\n * do; re-running the SAME model changes nothing about attribution, because\n * the model that serves is the model that was asked for.\n *\n * Bounded by the same commit rule as failover: only a turn whose ONLY\n * committing event is a terminal receipt with no text is retried, so nothing\n * that reached the user can ever be produced twice.\n */\n emptyTurnRetries?: number\n /** Fired when an empty turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** One same-model re-run of a turn that completed with no assistant text. */\nexport interface EmptyTurnRetryInfo {\n model: string\n /** 1 for the first re-run. */\n retry: number\n /** How many re-runs remain after this one. */\n remaining: number\n}\n\n/** The failover-wrapped stream plus the attribution every consumer needs. */\nexport interface ModelFailoverStreamHandle {\n events: AsyncGenerator<unknown, void, unknown>\n /** The model that actually served. `undefined` until the first pull resolves it. */\n servingModel(): string | undefined\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts(): ModelFailoverAttempt[]\n /** True when the preferred model did not serve — the attributability signal. */\n usedFallback(): boolean\n}\n\n/** Default ceiling for opening/starting one source through its first event. */\nexport const DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS = 120_000\n\n/** Default ceiling for the first answer-bearing event after the source's first event. */\nexport const DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS = 60_000\n\n/** Structured timeout codes surfaced by the producer on final exhaustion. */\nexport type ModelAttemptTimeoutCode =\n | 'model_stream_open_timeout'\n | 'provider_first_response_timeout'\n\n/** Every configured model was exhausted and the final one timed out. */\nexport class ModelFailoverTimeoutError extends ModelFailoverExhaustedError {\n readonly code: ModelAttemptTimeoutCode\n readonly model: string\n readonly timeoutMs: number\n\n constructor(input: {\n attempts: ModelFailoverAttempt[]\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n }) {\n super(input.attempts)\n this.name = 'ModelFailoverTimeoutError'\n this.code = input.code\n this.model = input.model\n this.timeoutMs = input.timeoutMs\n this.message = input.code === 'model_stream_open_timeout'\n ? `Opening the model event source for ${input.model} exceeded ${input.timeoutMs}ms.`\n : `Model ${input.model} produced no first answer-bearing event within ${input.timeoutMs}ms.`\n }\n}\n\nfunction resolveTimeoutMs(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${label} must be a finite number greater than 0`)\n }\n return Math.max(1, Math.trunc(value))\n}\n\nconst TIMED_OUT = Symbol('model-attempt-timed-out')\n\nfunction deadlineAfter(timeoutMs: number | null): {\n promise: Promise<typeof TIMED_OUT>\n clear: () => void\n} {\n let timer: ReturnType<typeof setTimeout> | undefined\n // No deadline: a promise that never settles, so the race is the stream alone.\n const promise = new Promise<typeof TIMED_OUT>((resolve) => {\n if (timeoutMs !== null) timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs)\n })\n return {\n promise,\n clear: () => {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n },\n }\n}\n\n/**\n * True when `event` is a terminal receipt (`result` / `done`) carrying no\n * assistant text.\n *\n * Measured on production `sandbox.tangle.tools` (28 turns through\n * the gtm-agent profile): a turn can end `{ outcome: { type: 'completed' } }`\n * with `finalText: ''` and zero token events — the platform reports success and\n * the customer's message is blank. It is not an outage, nothing throws, and\n * `isUpstreamUnavailable` correctly declines to classify it, so before this the\n * blank answer committed and shipped.\n */\nfunction isEmptyTerminalReceipt(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (type !== 'result' && type !== 'done') return false\n const data = asRecord(record.data)\n const text = asString(data?.finalText) ?? asString(data?.text) ?? ''\n return text.trim().length === 0\n}\n\n/**\n * Hard ceiling on same-model re-runs. A turn that comes back blank three times\n * running is not a flake this can retry away, and each pass costs a full\n * sandbox turn — so the budget is capped rather than trusted.\n */\nexport const MAX_EMPTY_TURN_RETRIES = 3\n\n/**\n * Coerce the caller's budget to a finite, bounded, non-negative integer.\n *\n * `Math.trunc(NaN)` is `NaN` and `retry >= NaN` is false for every `retry`, so\n * a naive clamp turns a bad config value into a loop that opens sandbox streams\n * until the worker dies. `Infinity` has the same shape. Both resolve to `0` —\n * an unusable budget disables the retry rather than running unbounded.\n */\nexport function resolveEmptyTurnRetries(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return 0\n const truncated = Math.trunc(value)\n if (truncated <= 0) return 0\n return Math.min(truncated, MAX_EMPTY_TURN_RETRIES)\n}\n\n/** Abandon a dead attempt's iterator. Never allowed to mask the outage. */\nasync function closeIterator(iterator: AsyncIterator<unknown>, log?: ModelFailoverStreamOptions['log']): Promise<void> {\n try {\n await iterator.return?.()\n } catch (err) {\n log?.('[chat-routes] abandoning a failed model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n}\n\n/**\n * Wrap `open` in reactive model failover, streaming from the first model in\n * `models` that reaches its commit point.\n *\n * Zero added latency on the happy path: the preferred model is opened first and,\n * the moment it emits anything meaningful, its events flow straight through.\n *\n * @throws ModelFailoverTimeoutError when the final model times out,\n * ModelFailoverExhaustedError when every model's upstream is down, and\n * re-throws a non-outage error from the FIRST model without walking the\n * chain (the latter behaviors are inherited from\n * `runWithModelFailover`).\n */\nexport function streamWithModelFailover(\n options: ModelFailoverStreamOptions,\n): ModelFailoverStreamHandle {\n const committing = options.isCommitting ?? isCommittingSandboxEvent\n const emptyTurnRetries = resolveEmptyTurnRetries(options.emptyTurnRetries)\n const openTimeoutMs = resolveTimeoutMs(\n options.openTimeoutMs,\n DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS,\n 'openTimeoutMs',\n )\n // A deadline exists to walk the chain. With one model there is nowhere to\n // walk, so the default only turned a slow first token into a lost answer:\n // a 2026-11-13 Discovery director turn ended at 60 s on its only model, and\n // on 2026-11-18 the same director's first reasoning token took 296 s on a\n // 295k-token context. The open deadline still bounds a stream that never\n // opens; a product that wants this bound for one model names it.\n const firstResponseTimeoutMs = options.firstResponseTimeoutMs === undefined && options.models.length < 2\n ? null\n : resolveTimeoutMs(\n options.firstResponseTimeoutMs,\n DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS,\n 'firstResponseTimeoutMs',\n )\n const liveLifecycle = options.liveLifecycleEvents === true\n const progress = createProgressQueue()\n let serving: string | undefined\n let trail: ModelFailoverAttempt[] = []\n let fellBack = false\n const attemptState = { index: 0 }\n let finalTimeout: {\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n } | undefined\n\n /**\n * One open-and-drain pass. `empty` marks the pass as an EMPTY TURN — the\n * only committing event was a terminal receipt with no assistant text, so\n * nothing reached the user and the pass can be discarded without any risk of\n * producing an answer twice. It still carries the outcome it would otherwise\n * have returned, so exhausting the retry budget is byte-identical to no\n * retry at all.\n */\n const { drainOnce } = createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress)\n\n const probe = async (model: string): Promise<AttemptOutcome> => {\n // Only the FINAL attempted model decides the exhaustion code. Clear a\n // prior model's timeout before this model can throw a different outage.\n finalTimeout = undefined\n for (let retry = 0; ; retry += 1) {\n const pass = await drainOnce(model)\n if (!pass.empty || retry >= emptyTurnRetries) {\n if (!pass.outcome.committed && pass.outcome.timeoutCode) {\n finalTimeout = {\n code: pass.outcome.timeoutCode,\n model,\n timeoutMs: pass.outcome.timeoutCode === 'model_stream_open_timeout'\n ? openTimeoutMs\n : firstResponseTimeoutMs ?? 0,\n }\n } else {\n finalTimeout = undefined\n }\n return pass.outcome\n }\n // Discard the empty pass entirely — including its `step-finish` token\n // receipt, which must not be billed — and re-run the same model.\n const iterator = pass.outcome.committed ? pass.outcome.iterator : null\n if (pass.outcome.committed) pass.outcome.abort()\n if (iterator) void closeIterator(iterator, options.log)\n const info: EmptyTurnRetryInfo = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 }\n options.log?.('[chat-routes] turn completed with no assistant text; re-running the same model', {\n ...info,\n })\n options.onEmptyTurnRetry?.(info)\n }\n }\n\n const events = (async function* (): AsyncGenerator<unknown, void, unknown> {\n let handle: AttemptCommit\n // Progress arrives while the probe is still running. The queue closes only\n // after the verdict settles, so every event pushed before it is delivered\n // in order and ahead of the replayed buffer.\n const settled = runWithModelFailover<AttemptOutcome>({\n models: options.models,\n run: probe,\n ...(options.policy ? { policy: options.policy } : {}),\n // The probe has already classified the raw payload with\n // `isUpstreamUnavailable`; this reads its verdict rather than\n // re-classifying a wrapper object, so the two can never disagree.\n isUnavailableResult: (result) => result.committed === false,\n onFallback: (attempt, nextModel) => {\n const info: ModelFallbackInfo = {\n from: attempt.model,\n to: nextModel,\n reason: attempt.reason ?? 'upstream unavailable',\n }\n options.log?.('[chat-routes] model upstream unavailable; falling over', { ...info })\n options.onFallback?.(info)\n },\n }).finally(() => progress.close())\n // The verdict is read after the drain; mark the rejection handled until then.\n settled.catch(() => undefined)\n for (;;) {\n const item = await progress.pull()\n if (item === PROGRESS_CLOSED) break\n yield item\n }\n try {\n const outcome = await settled\n serving = outcome.model\n trail = outcome.attempts\n fellBack = outcome.usedFallback\n handle = outcome.value as AttemptCommit\n } catch (err) {\n // Exhaustion carries the full trail; keep it so the receipt still names\n // every model tried even though the turn produced nothing.\n const attempts = (err as { attempts?: ModelFailoverAttempt[] })?.attempts\n if (Array.isArray(attempts)) trail = attempts\n if (err instanceof ModelFailoverExhaustedError && finalTimeout) {\n throw new ModelFailoverTimeoutError({\n attempts: trail,\n ...finalTimeout,\n })\n }\n throw err\n }\n\n for (const event of handle.buffered) yield event\n\n const live = handle.iterator\n if (!live) {\n handle.abort()\n return\n }\n try {\n for (;;) {\n const next = await live.next()\n if (next.done) return\n yield next.value\n }\n } finally {\n // The consumer may abandon this generator mid-turn (client drop); close\n // the underlying stream rather than leaking it.\n handle.abort()\n await closeIterator(live, options.log)\n }\n })()\n\n return {\n events,\n servingModel: () => serving,\n attempts: () => trail,\n usedFallback: () => fellBack,\n }\n}\n\nconst PROGRESS_CLOSED: unique symbol = Symbol('progress-closed')\n\n/**\n * FIFO handoff from the probe (a plain promise chain) to the event generator.\n * `close` is idempotent and queues one sentinel behind everything pushed\n * before it, so a consumer never loses a progress event to the verdict.\n */\nfunction createProgressQueue(): {\n push(event: unknown): void\n close(): void\n pull(): Promise<unknown>\n} {\n const items: unknown[] = []\n const waiters: Array<(value: unknown) => void> = []\n let closed = false\n const deliver = (value: unknown): void => {\n const waiter = waiters.shift()\n if (waiter) waiter(value)\n else items.push(value)\n }\n return {\n push(event) {\n if (closed) return\n deliver(event)\n },\n close() {\n if (closed) return\n closed = true\n deliver(PROGRESS_CLOSED)\n },\n pull() {\n if (items.length > 0) return Promise.resolve(items.shift())\n if (closed) return Promise.resolve(PROGRESS_CLOSED)\n return new Promise((resolve) => waiters.push(resolve))\n },\n }\n}\n\nfunction createModelAttemptDrainer(\n attemptState: { index: number },\n options: ModelFailoverStreamOptions,\n openTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n firstResponseTimeoutMs: number | null,\n committing: (event: unknown) => boolean,\n liveLifecycle: boolean,\n progress: ReturnType<typeof createProgressQueue>,\n) {\n const drainOnce = async (model: string): Promise<{ outcome: AttemptOutcome; empty: boolean }> => {\n attemptState.index += 1\n const controller = new AbortController()\n const abort = (): void => {\n if (!controller.signal.aborted) controller.abort()\n }\n const opening = Promise.resolve().then(() => options.open({\n model,\n attempt: attemptState.index,\n signal: controller.signal,\n }))\n const openDeadline = deadlineAfter(openTimeoutMs)\n let opened: AsyncIterable<unknown> | typeof TIMED_OUT\n try {\n opened = await Promise.race([opening, openDeadline.promise])\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n if (opened === TIMED_OUT) {\n openDeadline.clear()\n abort()\n // A Promise cannot be forcibly cancelled. If the abandoned open settles\n // later, close its iterator immediately so it cannot leak a connection.\n void opening.then(\n (lateSource) => {\n try {\n void closeIterator(lateSource[Symbol.asyncIterator](), options.log)\n } catch (err) {\n options.log?.('[chat-routes] closing a late model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n (err) => {\n options.log?.('[chat-routes] abandoned model stream open rejected after timeout', {\n error: err instanceof Error ? err.message : String(err),\n })\n },\n )\n return {\n outcome: {\n committed: false,\n error: `Opening the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n\n const source = opened\n let iterator: AsyncIterator<unknown>\n try {\n iterator = source[Symbol.asyncIterator]()\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n const buffered: unknown[] = []\n // Starting the source includes its first pull. `streamSandboxPrompt` is an\n // async generator, so its cold-start work does not execute until `next()`;\n // counting that time as provider inference would collapse the two phases.\n let next: IteratorResult<unknown> | typeof TIMED_OUT\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n openDeadline.promise,\n ])\n } catch (err) {\n openDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n openDeadline.clear()\n if (next === TIMED_OUT) {\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Starting the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n abort()\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n\n // One deadline for the WHOLE provider pre-response phase. Pulling a\n // lifecycle or processing event races the same promise; liveness cannot\n // reset the clock.\n const firstResponseDeadline = deadlineAfter(firstResponseTimeoutMs)\n\n for (;;) {\n const event = next.value\n let failure: TerminalFailure | null\n let commits = false\n try {\n failure = classifyTerminalFailure(event)\n commits = !failure && committing(event)\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (failure?.outage) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: failure.reason,\n ...(failure.code ? { errorCode: failure.code } : {}),\n },\n empty: false,\n }\n }\n\n if (liveLifecycle && !failure && !commits && isLiveLifecycleEvent(event)) {\n progress.push(event)\n } else {\n buffered.push(event)\n }\n // A terminal NON-outage failure surfaces exactly as it does today.\n if (failure) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: false }\n }\n if (commits) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: isEmptyTerminalReceipt(event) }\n }\n\n // A THROWN failure propagates untouched: `runWithModelFailover` classifies\n // it (outage → next model, anything else → re-thrown to the caller).\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n firstResponseDeadline.promise,\n ])\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (next === TIMED_OUT) {\n firstResponseDeadline.clear()\n // Do not await `return()`: an async generator blocked inside `next()`\n // may not settle its return until that pull completes. Invoking it is\n // the cancellation signal; waiting for it would recreate the hang.\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Model ${model} produced no first answer-bearing event within ${firstResponseTimeoutMs}ms`,\n errorCode: 'provider_first_response_timeout',\n timeoutCode: 'provider_first_response_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n firstResponseDeadline.clear()\n abort()\n // Clean end with nothing committing. Not an outage — but also not an\n // answer, so it is re-runnable on the same model.\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n }\n }\n return { drainOnce }\n}\n","/** Stream framing, event inspection and cancellation around a chat producer. */\nimport type { ChatRouteEvent } from './turn-route-contracts'\nimport { TurnCancellationRequestedError, TurnControlUnavailableError } from '../turn-stream/cancellation'\n\n/** A view queues bytes without making execution wait for a connected reader. */\nexport function createTurnView() {\n let disconnected = false\n let controller!: ReadableStreamDefaultController<Uint8Array>\n const readable = new ReadableStream<Uint8Array>({\n start(value) { controller = value },\n cancel() { disconnected = true },\n })\n return {\n readable,\n get disconnected() { return disconnected },\n write(chunk: Uint8Array): void {\n if (disconnected) return\n try { controller.enqueue(chunk) } catch { disconnected = true }\n },\n close(): void {\n if (disconnected) return\n try { controller.close() } catch { /* A closed view has no more delivery work. */ }\n },\n }\n}\n\n/** One safe pre-execution response for the server-owned host control signal. */\nexport function turnControlResponse(signal: AbortSignal): Response {\n const requested = signal.reason instanceof TurnCancellationRequestedError\n return Response.json({ error: requested ? 'Stop was requested for this turn.' : 'Turn control was lost.',\n code: requested ? 'turn_cancel_requested' : 'turn_control_unavailable' }, { status: requested ? 409 : 503 })\n}\n\n/** The original data of a failure event whose reason a producer withheld from the person. A Symbol key: JSON, and so\n * the wire and the turn buffer, drops it, while the route's own hooks read it through {@link serverFailureData}. */\nexport const WITHHELD_FAILURE: unique symbol = Symbol('withheld failure')\n\n/** A failure event's data as the server records it: the withheld original when a producer kept one, else as streamed. */\nexport function serverFailureData(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n const original = (data as { [WITHHELD_FAILURE]?: unknown } | undefined)?.[WITHHELD_FAILURE]\n return original !== null && typeof original === 'object' ? original as Record<string, unknown> : data\n}\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nexport function failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** The typed reason a terminal `error` / `session.run.failed` event's `data`\n * names, e.g. `sandbox.stream_failed` or an upstream code. */\nexport function failureCodeOf(data: Record<string, unknown> | undefined): string | undefined {\n const code = data?.code\n return typeof code === 'string' && code.length > 0 ? code : undefined\n}\n\n/** A word the user sees: a producer `text` event, or a sandbox text part delta. */\nexport function isVisibleText(event: ChatRouteEvent): boolean {\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'text') return typeof value.text === 'string' ? value.text.trim().length > 0 : true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown } | undefined\n const delta = event.data?.delta\n return part?.type === 'text' && typeof delta === 'string' && delta.trim().length > 0\n}\n\n/** Output rendered by either lane; admission/status/usage events are not model output. */\nexport function isVisibleOutput(event: ChatRouteEvent): boolean {\n if (isVisibleText(event)) return true\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'reasoning') return typeof value.text === 'string' && value.text.trim().length > 0\n if (event.type === 'tool_call' || event.type === 'tool.call' || event.type === 'tool_result' || event.type === 'tool.result' || event.type === 'tool.event') return true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown; text?: unknown } | undefined\n if (part?.type === 'tool') return true\n if (part?.type !== 'reasoning' && part?.type !== 'text') return false\n const text = event.data?.delta ?? part.text\n return typeof text === 'string' && text.trim().length > 0\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nexport async function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nexport async function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nexport function concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n\n/**\n * Stop a producer pull when its request or maintained owner control aborts.\n * `AsyncIterator.return()` alone cannot interrupt a pending `next()` call, so\n * race each pull with the request signal and close the source in `finally`.\n */\nexport async function* abortOnSignal<T>(\n source: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = await nextWithAbort(iterator, signal)\n if (next.done) return\n yield next.value\n }\n } finally {\n await closeIteratorAfterAbort(iterator)\n }\n}\n\nfunction nextWithAbort<T>(\n iterator: AsyncIterator<T>,\n signal: AbortSignal,\n): Promise<IteratorResult<T>> {\n if (signal.aborted) return Promise.reject(cancellationReason(signal))\n return new Promise((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (settled) return\n settled = true\n cleanup()\n reject(cancellationReason(signal))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) {\n onAbort()\n return\n }\n Promise.resolve()\n .then(() => iterator.next())\n .then(\n (result) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(result)\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\n/** Only maintained control errors cross this boundary. An arbitrary abort reason\n * may contain credentials or producer text and retains the existing generic error. */\nfunction cancellationReason(signal: AbortSignal): Error {\n const reason: unknown = signal.reason\n return reason instanceof TurnCancellationRequestedError || reason instanceof TurnControlUnavailableError\n ? reason : new Error('chat turn cancelled')\n}\n\nconst ABORT_CLEANUP_TIMEOUT_MS = 50\n\nasync function closeIteratorAfterAbort<T>(iterator: AsyncIterator<T>): Promise<void> {\n let closing: PromiseLike<unknown> | undefined\n try {\n const result = iterator.return?.()\n if (result) closing = Promise.resolve(result)\n } catch {\n return\n }\n if (!closing) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.resolve(closing).catch(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n}\n","/**\n * What a person reads when a sandbox turn fails: only sentences written here. Harness, provider and Router text is read\n * only to classify the failure, by its code, its HTTP status or a recognized phrase, and the person reads that class's\n * fixed sentence. No part of the reason is shown; the only values in a sentence are times parsed and formatted here.\n * The server keeps the reason, in its log and under a Symbol key the route's own failure hooks read. `personFacing`\n * applies this to every event the sandbox producer yields.\n */\n\nimport { ModelFailoverExhaustedError } from '../model-resolution/failover'\nimport { SandboxRunError } from '../sandbox/sandbox-run-error'\nimport { asRecord, asString, type JsonRecord } from '../stream/index'\nimport { getChatFundingRecovery } from '../web/turn-funding-recovery'\nimport { ModelFailoverTimeoutError } from './model-failover-stream'\nimport { WITHHELD_FAILURE } from './turn-event-stream'\nimport { TURN_USAGE_KEYS } from './sandbox-turn-usage'\n\ntype Log = (message: string, meta?: Record<string, unknown>) => void\n\nconst utcTime = (at: Date) => `${at.toISOString().slice(11, 19)} UTC`\n\nexport const FAILED_TURN_TEXT = 'That answer stopped before it finished. Please send your question again.'\nconst SENTENCES = {\n settlement: 'The answer above is complete.',\n model_key_refused: \"The assistant's model refused its access key, so this message was not answered. \"\n + 'If the assistant has just started, send it again in a minute; if this repeats, tell the team.',\n budget_exhausted: \"This assistant's spending budget is used up. Raise its cap or wait for it to reset, then send again.\",\n balance_low: 'Insufficient credits to cover this request. Add funds, then send again.',\n model_policy: \"That model isn't available here. Choose another model and send again.\",\n grant_model_unsupported: \"This assistant's model can't run here. Ask the team to choose a supported model.\",\n grant_activation_missing: \"This assistant couldn't connect to its model. Tell the team; sending again won't help.\",\n profile_unsupported: \"This assistant's setup can't run here. Ask the team to update it.\",\n provider_retry: 'The model provider is busy, so the request is being retried.',\n}\n\n/** A harness's provider retry wait (OpenCode's raw `retry` status) as one sentence with its next attempt's time. */\nexport function providerRetryNotice(event: { type: string; data?: unknown }): string | undefined {\n const retry = event.type === 'raw' ? asRecord(asRecord(event.data)?.event) : undefined\n if (retry?.type !== 'retry' || !(Number(retry.next) > 0)) return undefined\n return `The model provider is busy; retrying at ${utcTime(new Date(Number(retry.next)))}.`\n}\n\n/** A terminal provider wait (`…, reset at <ISO>`, agent-container provider-retry-wait.ts) as one sentence with its time. */\nexport function providerResetSentence(message: string): string | undefined {\n const at = new Date(message.match(/reset at (\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z)/)?.[1] ?? NaN)\n if (Number.isNaN(at.getTime())) return undefined\n return `The model provider asked us to wait. Try again after ${utcTime(at)} on ${at.toISOString().slice(0, 10)}.`\n}\n\n/** The typed code for a harness whose model refused its key, so a product can tell it from other stream failures. */\nexport const MODEL_KEY_REFUSED_CODE = 'model.key_refused'\n\n/** A harness whose model provider refused its key (\"Invalid API key\", OpenCode's `OPENCODE_ERROR`) as plain words, true\n * both for a newly started box whose harness called the model before its minted key was in place (it recovers within\n * minutes) and for a key that is wrong. The raw error goes to the log, never to the person. */\nexport function modelKeyRefusedSentence(message: string): string | undefined {\n const lower = message.toLowerCase()\n const refused = lower.includes('invalid api key') || (/\\b401\\b/.test(message) && /unauthori[sz]ed|api key/.test(lower))\n return refused ? SENTENCES.model_key_refused : undefined\n}\n\n/** The Router's refusals of a key's budget, and of a balance too low for one request. */\nconst ROUTER_BUDGET = [\"This key's monthly budget is exhausted\", \"This key's lifetime budget is exhausted\",\n 'Monthly budget exceeded (', 'The key or product budget cannot cover']\n\n/** How a failure reads to the person: its class and that class's fixed sentence. */\nexport interface FailureView {\n class: string\n shown: string\n}\n\n/** Refusals by code, each as its fixed sentence: they fail the same way again, so none asks the person to resend. */\nconst REFUSALS = new Map<string, keyof typeof SENTENCES>([\n ['MODEL_REFUSED', 'model_policy'], ['model_policy_denied', 'model_policy'], ['budget_exceeded', 'budget_exhausted'],\n ['grant_model_unsupported', 'grant_model_unsupported'], ['grant_activation_missing', 'grant_activation_missing'],\n ['profile_unsupported', 'profile_unsupported'], [MODEL_KEY_REFUSED_CODE, 'model_key_refused'],\n])\n\n/** Classes a person reads after a lead line, so a client that recognizes the stored failure prefix still finds them. */\nconst LED_CLASSES: ReadonlySet<string> = new Set(['funding', 'balance_low', 'model_policy', 'grant_model_unsupported',\n 'grant_activation_missing', 'profile_unsupported'])\n\n/** Warnings a person may read, each as a sentence written here; any other warning is dropped. */\nconst WARNING_SENTENCES = new Map<string, string>([\n ['empty_visible_output_retry', 'The model returned no visible answer, so it is trying once more.'],\n ['OPENCODE_STEP_TRUNCATED', 'A step of this answer was cut short, so the answer may be incomplete.'],\n ['OPENCODE_PROVIDER_RETRY', SENTENCES.provider_retry],\n ['CODEX_UNEXPECTED_APPROVAL', 'The agent asked for an approval it does not need here, and it was declined.'],\n ['CODEX_UNEXPECTED_QUESTION', 'The agent asked a question it cannot ask here, and it was declined.'],\n ['EXECUTION_INTERRUPTED', 'This answer was interrupted before it finished.'],\n ['FILE_DENIED', 'The agent was refused access to a file.'],\n])\n\n/** A model failover trail: `All N model(s) failed. <model>: <reason> | <model>: <reason>`. */\nconst FAILOVER_TRAIL = /^All \\d+ model\\(s\\) failed\\. /\n\n/** A failover trail read for its last attempt only; any other reason as it is. */\nfunction lastAttempt(reason: string): string {\n if (!FAILOVER_TRAIL.test(reason)) return reason\n const attempts = reason.replace(FAILOVER_TRAIL, '')\n const last = attempts.slice(attempts.lastIndexOf(' | ') + 1).replace(/^\\| /, '')\n const colon = last.indexOf(': ')\n return colon < 0 ? last : last.slice(colon + 2)\n}\n\n/** The class of a failure and its sentence, or `undefined` for the default, withheld class. Linear in the reason. */\nfunction classify(reason: string, code: string | undefined, status: unknown): FailureView | undefined {\n const refusal = REFUSALS.get(code ?? '')\n if (refusal) return { class: refusal, shown: SENTENCES[refusal] }\n const funding = getChatFundingRecovery({ code: code === 'PAYMENT_REQUIRED' ? 'insufficient_credits' : code })\n const last = lastAttempt(reason)\n if (!funding) {\n const wait = providerResetSentence(last)\n if (wait) return { class: 'provider_wait', shown: wait }\n const kind = modelKeyRefusedSentence(last) ? 'model_key_refused'\n : ROUTER_BUDGET.some((phrase) => last.includes(phrase)) ? 'budget_exhausted'\n : last.includes('Available credits cannot cover') ? 'balance_low' : undefined\n if (kind) return { class: kind, shown: SENTENCES[kind] }\n }\n const recovery = funding ?? getChatFundingRecovery({ message: last })\n ?? (Number(status) === 402 ? getChatFundingRecovery({ code: 'insufficient_credits' }) : null)\n if (!recovery) return undefined\n // The recovery UI's own words, so a client that reads the sentence still opens billing.\n const paidAccess = recovery.reason === 'paid_access_required' ? 'Inference requires verified paid access. ' : ''\n return { class: 'funding', shown: `${recovery.title}. ${paidAccess}${recovery.message}` }\n}\n\n/** The turn, thread, session and execution ids a record carries, for the server log. */\nexport function failureIds(source: unknown): Record<string, string> {\n const record = asRecord(source)\n return Object.fromEntries(['turnId', 'threadId', 'sessionId', 'executionId']\n .flatMap((key) => typeof record?.[key] === 'string' && record[key] ? [[key, record[key] as string]] : []))\n}\n\n/** The text a failure adds to the answer: its sentence, after a lead line for the classes that carry one. */\nexport function failureText(view: FailureView, partialAnswer: string): string {\n if (!LED_CLASSES.has(view.class)) return view.shown\n const lead = partialAnswer.trim()\n ? 'The sandbox model stream stopped before a clean completion.'\n : 'The sandbox agent returned an error before producing a visible answer.'\n return `${lead}\\n\\nError: ${view.shown}`\n}\n\n/** Protocol reason values, not arbitrary identifiers or prose. */\nconst REASONS = new Set(['provider_error', 'abort'])\nconst USAGE_KEYS = new Set<string>([...TURN_USAGE_KEYS, 'cacheReadInputTokens', 'cacheCreationInputTokens', 'cost', 'totalCostUsd'])\n\n/** Failure carriers in precedence order, shared by the reason and code extractors. */\nfunction failureSources(event: unknown) {\n const record = asRecord(event)\n const data = asRecord(record?.data)\n const raw = asRecord(data?.event)\n return [data, asRecord(data?.error), asRecord(asRecord(data?.properties)?.error), record, asRecord(record?.error),\n raw, asRecord(raw?.error), asRecord(raw?.item)]\n}\n\n/** The reason stays server-side; a closed protocol reason is a class, not prose. */\nexport function failureReason(event: unknown): string {\n for (const row of failureSources(event)) {\n const reason = asString(row?.message) ?? asString(row?.error) ?? asString(row?.detail) ?? asString(row?.details)\n ?? (REASONS.has(String(row?.reason)) ? undefined : asString(row?.reason)) ?? asString(asRecord(row?.data)?.message)\n if (reason) return reason\n }\n return ''\n}\n\n/** Event types that carry a failure reason; `done` and `status` do too when their status is `failed`. */\nconst FAILURE_TYPES: ReadonlySet<string> = new Set(['error', 'warning', 'session.run.failed', 'session.error'])\n\n/** One code extractor for the wire, raw harness events and the answer text. */\nexport function failureCode(event: unknown): string | undefined {\n return failureSources(event).map((row) => asString(row?.code)).find(Boolean)\n}\n\n/** Allowed fields must also have scalar values: a known key cannot smuggle a nested reason onto the wire. */\nfunction visibleValues(data: JsonRecord): JsonRecord {\n return Object.fromEntries(Object.entries(data).filter(([key, value]) => {\n if (['turnId', 'threadId', 'sessionId', 'executionId', 'code'].includes(key)) return typeof value === 'string' && /^[\\w.:-]+$/.test(value)\n if (key === 'reason') return typeof value === 'string' && REASONS.has(value)\n if (key === 'retryable') return typeof value === 'boolean'\n if (key === 'status' && value === 'failed') return true\n return (['status', 'statusCode', 'retryAt', 'resetAt'].includes(key) || USAGE_KEYS.has(key)) && typeof value === 'number' && Number.isFinite(value)\n }))\n}\n\n/** A failure event as the person reads it: every text field reads `shown`, `details` keeps only its value keys, and the\n * original data, with its reason, rides under `WITHHELD_FAILURE`, which JSON (the wire, the turn buffer) drops. */\nfunction shownFailure(event: JsonRecord, shown: string, reason: string): JsonRecord {\n const data = asRecord(event.data) ?? {}\n const visible = { ...visibleValues(data), ...visibleValues({ code: failureCode(event) }), message: shown }\n const details = visibleValues(asRecord(data.details) ?? {})\n if (Object.keys(details).length) Object.assign(visible, { details })\n for (const key of ['usage', 'tokenUsage']) {\n const usage = Object.fromEntries(Object.entries(asRecord(data[key]) ?? {}).filter(([name, value]) =>\n USAGE_KEYS.has(name) && typeof value === 'number' && Number.isFinite(value)))\n if (Object.keys(usage).length) Object.assign(visible, { [key]: usage })\n }\n const original = typeof data.message === 'string' ? data : { ...data, message: reason }\n return { type: event.type, data: Object.assign(visible, { [WITHHELD_FAILURE]: original }) }\n}\n\n/** One turn's person-facing filter. `view` classifies a failure reason; every reason is logged once, at warn (`log`,\n * else `console.warn`), with its class and ids, and the same reason reads the same wherever it appears. `warning`\n * gives an allowed warning's sentence. `event` is every event the producer yields as it may reach the client.\n * `hasAnswer` says whether the turn already shows answer text. */\nexport function personFacing(options: { log?: Log; failedTurnText: string; hasAnswer?: () => boolean }) {\n const views = new Map<string, FailureView>()\n // The turn's first failure that reads in its own words; a withheld failed `done` or `status` reads it too.\n let named: FailureView | undefined\n const droppedWarnings = new Set<string>()\n const warn = (message: string, meta: Record<string, unknown>) => (options.log ?? console.warn)(message, meta)\n const view = (reason: string, code?: string, status?: unknown, meta: Record<string, unknown> = {}): FailureView => {\n const settled = code?.startsWith('settlement_') ?? false\n const answered = settled && options.hasAnswer?.()\n const key = [reason, code, Number(status) === 402, answered].join('\\n')\n const known = views.get(key)\n if (known) return known\n // A settlement check that fails after a charged answer leaves that answer whole: sending again would charge again.\n const seen = (answered ? { class: 'settlement', shown: SENTENCES.settlement } : undefined)\n ?? classify(reason, code, status)\n ?? { class: settled ? 'settlement' : 'runtime_failure', shown: options.failedTurnText }\n warn('[chat-routes] turn failure withheld from the person', { failureClass: seen.class, code, error: reason, ...meta })\n views.set(key, seen)\n if (seen.shown !== options.failedTurnText) named ??= seen\n return seen\n }\n /** An allowed warning's sentence, or `undefined` for any other warning, which is dropped and logged once. */\n const warning = (code: string | undefined, message: string, meta: Record<string, unknown> = {}): string | undefined => {\n const shown = WARNING_SENTENCES.get(code ?? '')\n if (shown || droppedWarnings.has(`${code}\\n${message}`)) return shown\n droppedWarnings.add(`${code}\\n${message}`)\n warn('[chat-routes] harness warning withheld from the person', { failureClass: 'harness_warning', code, error: message, ...meta })\n return undefined\n }\n /** An event as it may reach the client, or `undefined` for a dropped warning. A failure carrier always reads its class's\n * sentence, even when no reason can be found in it. */\n const event = (event: JsonRecord): JsonRecord | undefined => {\n const data = asRecord(event.data)\n const raw = event.type === 'raw' ? asRecord(data?.event) : undefined\n if (raw) {\n const part = asRecord(raw.part)\n const item = asRecord(raw.item)?.type === 'error' ? asRecord(raw.item) : undefined\n if (raw.type !== 'error' && raw.type !== 'retry' && raw.type !== 'turn.failed' && !('error' in raw) && !item) {\n return part?.type === 'tool' ? { ...event, data: { ...data, event: { ...raw, part: withoutToolList(part) } } } : event\n }\n const reason = failureReason(event)\n const shown = raw.type === 'retry' ? SENTENCES.provider_retry : view(reason, failureCode(event), raw.statusCode ?? raw.status, failureIds(data)).shown\n return { type: 'raw', data: { ...(shownFailure(event, shown, reason).data as JsonRecord),\n event: { type: raw.type === 'retry' ? 'retry' : 'error', ...visibleValues({ code: failureCode(event) }), message: shown } } }\n }\n const failed = (event.type === 'done' || event.type === 'status') && data?.status === 'failed'\n if (!failed && !FAILURE_TYPES.has(String(event.type))) return event\n const reason = failureReason(event)\n if (event.type === 'warning') {\n const shown = warning(failureCode(event), reason, failureIds(data))\n return shown ? shownFailure(event, shown, reason) : undefined\n }\n const status = data?.statusCode ?? (failed ? undefined : data?.status)\n const own = view(reason, failureCode(event), status, failureIds(data))\n // A turn's end reads the sentence its error, answer text and saved message carry, not the generic one.\n return shownFailure(event, (failed && own.shown === options.failedTurnText && named ? named : own).shown, reason)\n }\n return { view, warning, event }\n}\n\n/** A thrown sandbox stream as the operator's failure note, its code and its raw reason. */\nexport function sandboxStreamFailureDiagnostic(error: unknown): { failureNote: string; code: string; reason: string } {\n const streamMessage = (error as { streamMessage?: unknown })?.streamMessage\n const message = typeof streamMessage === 'string'\n ? streamMessage\n : error instanceof Error ? error.message : 'Sandbox stream failed'\n let failureNote = `sandbox-stream: ${message}`\n try {\n const diagnostics = asRecord((error as { diagnostics?: unknown })?.diagnostics)\n if (diagnostics) failureNote += `; ${JSON.stringify(diagnostics)}`\n } catch {\n failureNote += '; [unserializable diagnostics]'\n }\n const ownCode = asString(asRecord(error)?.code)\n const last = error instanceof ModelFailoverExhaustedError ? error.attempts.at(-1) : undefined\n const reason = last?.reason ?? message\n let code = 'sandbox.stream_failed'\n if (error instanceof SandboxRunError) {\n code = error.code\n } else if (error instanceof ModelFailoverTimeoutError) {\n code = error.code\n } else if (error instanceof ModelFailoverExhaustedError) {\n code = last?.errorCode ?? (last && error.attempts.every((attempt) => attempt.reason?.includes(' is not admitted by policy: '))\n ? 'model_policy_denied' : code)\n } else if (ownCode && (REFUSALS.has(ownCode) || getChatFundingRecovery({ code: ownCode })\n || ownCode === 'PAYMENT_REQUIRED' || ownCode.startsWith('settlement_'))) {\n code = ownCode\n }\n if (modelKeyRefusedSentence(reason) && code === 'sandbox.stream_failed') code = MODEL_KEY_REFUSED_CODE\n return { failureNote, code, reason }\n}\n\nconst UNAVAILABLE_TOOL_TEXT = \"That tool isn't available.\"\n\n/** Text without the list of every tool a harness appends to a refused or repeated tool call. */\nfunction withoutToolListTail(text: string): string {\n const at = text.indexOf('Available tools:')\n return at < 0 ? text : text.slice(0, at).trimEnd()\n}\n\n/** A tool part as the person may read it, live and stored: a failed call's `error` and `output` lose the harness's list\n * of every tool, and the harness's `invalid` repair tool, which stands in for a call to a tool the model does not have,\n * reads one sentence. Inputs, metadata and a completed call's output (a document it read) stay whole. */\nexport function withoutToolList(part: JsonRecord): JsonRecord {\n // Bare tool_result events have flat fields until recordPersistedPart normalizes them.\n const nested = asRecord(part.state)\n const state = nested ?? part\n const invalid = part.tool === 'invalid'\n const shown: JsonRecord = { ...state }\n for (const key of ['error', 'output']) {\n if (typeof shown[key] !== 'string' || (key === 'output' && !invalid && state.status !== 'error')) continue\n shown[key] = invalid ? UNAVAILABLE_TOOL_TEXT : withoutToolListTail(shown[key] as string)\n }\n if (invalid) shown.input = { ...asRecord(state.input), error: UNAVAILABLE_TOOL_TEXT }\n return nested ? { ...part, state: shown } : shown\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAmB;AAAA,EAAmB;AAAA,EAAoB;AAAA,EAAW;AACtG;AAGO,SAAS,cAAc,OAAiD;AAC7E,QAAM,WAA0B,CAAC;AACjC,aAAW,OAAO,gBAAiB,KAAI,QAAQ,GAAG,MAAM,OAAW,UAAS,GAAG,IAAI,MAAM,GAAG;AAC5F,SAAO;AACT;AAGO,SAAS,mBAAmB,MAAkB,OAA4B;AAC/E,QAAM,SAAS,SAAS,KAAK,MAAM;AACnC,MAAI,QAAQ;AACV,UAAM,QAAQ,SAAS,OAAO,KAAK;AACnC,UAAM,MAAM,CAAC,SAA6B,UAAuC;AAC/E,YAAM,IAAI,OAAO,KAAK;AACtB,UAAI,CAAC,OAAO,SAAS,CAAC,EAAG,QAAO;AAChC,cAAQ,WAAW,KAAK;AAAA,IAC1B;AACA,UAAM,cAAc,IAAI,MAAM,aAAa,OAAO,KAAK;AACvD,UAAM,eAAe,IAAI,MAAM,cAAc,OAAO,MAAM;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