@tangle-network/agent-app 4.0.1 → 4.0.3
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.
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +2 -1
- package/dist/agent-profiles/index.js +1 -1
- package/dist/chat-routes/index.js +12 -17
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/visible-text.d.ts +7 -0
- package/dist/{chunk-EI27JMS6.js → chunk-565M7QOK.js} +1 -1
- package/dist/chunk-565M7QOK.js.map +1 -0
- package/dist/{chunk-LBMFQLBS.js → chunk-DKEIQRKT.js} +4 -2
- package/dist/chunk-DKEIQRKT.js.map +1 -0
- package/dist/{chunk-XOHE6SKU.js → chunk-EK2Y55K4.js} +2 -137
- package/dist/chunk-EK2Y55K4.js.map +1 -0
- package/dist/{chunk-AFMLLZWU.js → chunk-GWATTXFR.js} +3 -3
- package/dist/{chunk-AFMLLZWU.js.map → chunk-GWATTXFR.js.map} +1 -1
- package/dist/{chunk-QVGDVY5U.js → chunk-I4MPG5T6.js} +2 -2
- package/dist/chunk-IJ6B5ZPU.js +141 -0
- package/dist/chunk-IJ6B5ZPU.js.map +1 -0
- package/dist/{chunk-HES3IABJ.js → chunk-JKYCXQFI.js} +2 -2
- package/dist/{chunk-U2PTQCQ3.js → chunk-NKANJSKB.js} +2 -2
- package/dist/{chunk-5DAEU3CP.js → chunk-SJKQUTGU.js} +11 -6
- package/dist/chunk-SJKQUTGU.js.map +1 -0
- package/dist/{chunk-JSWBJBPM.js → chunk-W5YQZEE4.js} +15 -10
- package/dist/chunk-W5YQZEE4.js.map +1 -0
- package/dist/{chunk-PISTUUEZ.js → chunk-XCUT2I52.js} +25 -12
- package/dist/{chunk-PISTUUEZ.js.map → chunk-XCUT2I52.js.map} +1 -1
- package/dist/{chunk-BRQ2SC6V.js → chunk-XKVJQVOT.js} +2 -1
- package/dist/chunk-XKVJQVOT.js.map +1 -0
- package/dist/conformance/cli.js +2 -2
- package/dist/conformance/index.js +2 -2
- package/dist/launch-invariants/cli.js +4 -3
- package/dist/launch-invariants/cli.js.map +1 -1
- package/dist/launch-invariants/index.js +3 -2
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/testing.js +4 -3
- package/dist/operator/contract.d.ts +6 -0
- package/dist/operator/index.js +6 -1
- package/dist/operator/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +5 -3
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +15 -0
- package/dist/runtime/router-turn.js +3 -1
- package/dist/turn-health/index.js +5 -3
- package/dist/turn-health/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5DAEU3CP.js.map +0 -1
- package/dist/chunk-BRQ2SC6V.js.map +0 -1
- package/dist/chunk-EI27JMS6.js.map +0 -1
- package/dist/chunk-JSWBJBPM.js.map +0 -1
- package/dist/chunk-LBMFQLBS.js.map +0 -1
- package/dist/chunk-XOHE6SKU.js.map +0 -1
- /package/dist/{chunk-QVGDVY5U.js.map → chunk-I4MPG5T6.js.map} +0 -0
- /package/dist/{chunk-HES3IABJ.js.map → chunk-JKYCXQFI.js.map} +0 -0
- /package/dist/{chunk-U2PTQCQ3.js.map → chunk-NKANJSKB.js.map} +0 -0
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
ProtectedModelSettlementError,
|
|
3
3
|
createRouterProtectedModelPort,
|
|
4
4
|
runProtectedRouterTurn
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-GWATTXFR.js";
|
|
6
6
|
import {
|
|
7
7
|
DURABLE_HOP_BUDGET_MS,
|
|
8
8
|
asksForLanguage,
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
createOpenAICompatStreamTurn,
|
|
14
14
|
createOpenAIResponsesTurn,
|
|
15
15
|
isOpenAIResponsesModel,
|
|
16
|
+
narratesBefore,
|
|
16
17
|
perTurnPrefixBytes,
|
|
17
18
|
placeRouterTurn,
|
|
18
19
|
replyLanguageInstruction,
|
|
@@ -26,7 +27,7 @@ import {
|
|
|
26
27
|
turnKnowledgeInstructions,
|
|
27
28
|
workspaceKnowledgeForTurn,
|
|
28
29
|
workspaceTurnCheckpoints
|
|
29
|
-
} from "../chunk-
|
|
30
|
+
} from "../chunk-XCUT2I52.js";
|
|
30
31
|
import {
|
|
31
32
|
DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
|
|
32
33
|
DEFAULT_TANGLE_ROUTER_BASE_URL,
|
|
@@ -193,6 +194,7 @@ export {
|
|
|
193
194
|
isTangleBillingEnforcementDisabled,
|
|
194
195
|
isTangleExecutionKeyError,
|
|
195
196
|
mergeSurfaceOverlay,
|
|
197
|
+
narratesBefore,
|
|
196
198
|
normalizeModelId,
|
|
197
199
|
perTurnPrefixBytes,
|
|
198
200
|
placeRouterTurn,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;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AAM,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG,GAAG;AACxD,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;AAC5F,UAAI,OAAO,cAAc,QAAQ;AAC/B,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,oCAAoC,KAAK,UAAW,OAAmC,SAAS,CAAC,GAAG;AAAA,MACnJ;AACA,UAAI;AACJ,UAAI;AACF,iBAAS,IAAI,IAAI,OAAO,GAAG;AAAA,MAC7B,QAAQ;AACN,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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<string, unknown>;
|
|
34
|
+
/**
|
|
35
|
+
* `'lookup'`: the tool fetches what the answer needs, so text a round writes before calling it narrates
|
|
36
|
+
* the work ("Let me check your vault") and is not the answer. A tool that declares nothing (a save, a send,
|
|
37
|
+
* a bridged tool) keeps the text before it as the answer.
|
|
38
|
+
*/
|
|
39
|
+
effect?: 'lookup';
|
|
34
40
|
run(args: Record<string, unknown>, context: RouterTurnToolContext): Promise<unknown>;
|
|
35
41
|
}
|
|
42
|
+
/** Whether text a round writes before calling `tool` narrates the work instead of answering. */
|
|
43
|
+
export declare function narratesBefore(tool: Pick<RouterTurnTool, 'effect'> | undefined): boolean;
|
|
36
44
|
/** What a running tool gets besides its arguments. */
|
|
37
45
|
export interface RouterTurnToolContext {
|
|
38
46
|
/** This call's identity, shared by streamed parts, tool history and a native child execution. */
|
|
@@ -130,6 +138,13 @@ export interface RouterTurnFailure {
|
|
|
130
138
|
export interface RouterTurnOutcome {
|
|
131
139
|
/** Every text segment the model wrote, joined by blank lines. */
|
|
132
140
|
text: string;
|
|
141
|
+
/**
|
|
142
|
+
* The turn's answer: `text` without its narration, the text a round wrote before calling a tool marked
|
|
143
|
+
* `effect: 'lookup'`. Text before any other tool stays. When everything written was narration, the answer
|
|
144
|
+
* is `text`, so narration that is the turn's only text is still shown. It covers this hop only:
|
|
145
|
+
* `continueFrom.text` from earlier hops is in `text`, never in `answer`.
|
|
146
|
+
*/
|
|
147
|
+
answer: string;
|
|
133
148
|
/** The model the router reports having served, when it said. */
|
|
134
149
|
servedModel: string | null;
|
|
135
150
|
toolCalls: Array<{
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
budgetTurnKnowledge,
|
|
5
5
|
composeRouterTurnPrompt,
|
|
6
6
|
composeRouterTurnPromptSections,
|
|
7
|
+
narratesBefore,
|
|
7
8
|
perTurnPrefixBytes,
|
|
8
9
|
placeRouterTurn,
|
|
9
10
|
replyLanguageInstruction,
|
|
@@ -13,7 +14,7 @@ import {
|
|
|
13
14
|
turnKnowledgeInstructions,
|
|
14
15
|
workspaceKnowledgeForTurn,
|
|
15
16
|
workspaceTurnCheckpoints
|
|
16
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-XCUT2I52.js";
|
|
17
18
|
import "../chunk-D6UJEOZQ.js";
|
|
18
19
|
import "../chunk-YYA2CVOY.js";
|
|
19
20
|
import "../chunk-KSLTD4FI.js";
|
|
@@ -23,6 +24,7 @@ export {
|
|
|
23
24
|
budgetTurnKnowledge,
|
|
24
25
|
composeRouterTurnPrompt,
|
|
25
26
|
composeRouterTurnPromptSections,
|
|
27
|
+
narratesBefore,
|
|
26
28
|
perTurnPrefixBytes,
|
|
27
29
|
placeRouterTurn,
|
|
28
30
|
replyLanguageInstruction,
|
|
@@ -3,7 +3,6 @@ import {
|
|
|
3
3
|
sizedBatches
|
|
4
4
|
} from "../chunk-UULUBF5J.js";
|
|
5
5
|
import {
|
|
6
|
-
classifyTurnOutcome,
|
|
7
6
|
createConsoleAlertSink,
|
|
8
7
|
createGuardedAlertSink,
|
|
9
8
|
createMemoryThrottleStore,
|
|
@@ -11,9 +10,12 @@ import {
|
|
|
11
10
|
createSlackBotAlertSink,
|
|
12
11
|
createThrottledAlertSink,
|
|
13
12
|
createWebhookAlertSink,
|
|
14
|
-
describeReason,
|
|
15
13
|
turnAlert
|
|
16
|
-
} from "../chunk-
|
|
14
|
+
} from "../chunk-IJ6B5ZPU.js";
|
|
15
|
+
import {
|
|
16
|
+
classifyTurnOutcome,
|
|
17
|
+
describeReason
|
|
18
|
+
} from "../chunk-EK2Y55K4.js";
|
|
17
19
|
import "../chunk-JRCZHDRG.js";
|
|
18
20
|
|
|
19
21
|
// src/turn-health/lifecycle.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n /** `/chat-routes` sets this when a `contextGate` short-circuited the turn and\n * the producer never ran. */\n gated?: boolean\n}\n\n/** Structural mirror of the lifecycle error payload. */\nexport interface TurnHealthErrorInfo {\n error: unknown\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\n\n/** What {@link createTurnHealthLifecycle} returns — assignable to\n * `createChatTurnRoutes`' `lifecycle` option. */\nexport interface TurnHealthLifecycle {\n onTurnComplete(info: TurnHealthCompleteInfo): Promise<void>\n onTurnError(info: TurnHealthErrorInfo): Promise<void>\n}\n\nexport interface TurnHealthLifecycleOptions {\n /** Names the product in every alert. */\n product: string\n sink: AlertSink\n /** Called for every verdict, healthy or not — the hook for a counter or a\n * metrics push. Alerts are for humans; this is for graphs. */\n onVerdict?(verdict: {\n product: string\n healthy: boolean\n kinds: string[]\n durationMs: number\n }): void\n /** Page when a turn was answered by a gate instead of the model.\n *\n * Default `false`, and the default is the honest one: gating is a legitimate\n * design and a product that gates its intake would otherwise page on every\n * healthy turn. Whether the rate is pathological is domain knowledge, so it\n * stays a product decision — the verdict is ALWAYS reported through\n * {@link TurnHealthLifecycleOptions.onVerdict} so a counter can watch the\n * rate even when nobody is paged. */\n alertOnGatedTurn?: boolean\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n return String(error)\n}\n\n/**\n * Build the lifecycle hooks that page on a turn which succeeded at nothing.\n *\n * The live lane sees `finalText` and usage but not the persisted parts, so it\n * catches the blank-completion and hard-failure shapes immediately. The\n * parts-dependent shapes (a tool call whose arguments never parsed, a tool\n * call that left no effect) are caught by {@link sweepSilentFailures}, which\n * reads what was actually written to the store — the honest place to ask\n * whether an effect persisted.\n */\nexport function createTurnHealthLifecycle(\n options: TurnHealthLifecycleOptions,\n): TurnHealthLifecycle {\n // Guarded: a paging failure must never take down a customer's turn.\n const sink = createGuardedAlertSink(options.sink)\n\n return {\n async onTurnComplete(info) {\n const verdict = classifyTurnOutcome({\n finalText: info.finalText,\n outputTokens: info.usage?.outputTokens ?? null,\n durationMs: info.durationMs,\n ...(info.gated ? { gated: true } : {}),\n })\n options.onVerdict?.({\n product: options.product,\n healthy: verdict.healthy,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n if (verdict.healthy || verdict.severity === null) return\n // Counted above, paged only on request — see `alertOnGatedTurn`.\n if (!options.alertOnGatedTurn && verdict.reasons.every((r) => r.kind === 'answered_without_model')) {\n return\n }\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: verdict.severity,\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n\n async onTurnError(info) {\n const verdict = classifyTurnOutcome({\n failed: true,\n failureReason: errorText(info.error),\n durationMs: info.durationMs,\n })\n options.onVerdict?.({\n product: options.product,\n healthy: false,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: 'critical',\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n }\n}\n","/**\n * The SWEEP half: ask the store what it has been quietly accumulating.\n *\n * A live per-turn hook cannot see the failure that matters most, because the\n * worst outage produced NO turns at all to hook: gtm-agent took 9–21 user\n * messages a day for sixteen straight days and wrote zero real assistant\n * replies. Nothing crashed on a schedule; the product simply stopped\n * answering. The only thing that could have noticed is something that\n * periodically counts what arrived against what was answered.\n *\n * That is this. It runs on a cron, reads the shared `/chat-store` schema, and\n * pages when the ratio breaks.\n *\n * The queries live HERE and not in each product because all four products\n * (gtm, tax, legal, workcomp) persist to the same `message`/`thread` tables —\n * four copies of this cron is exactly the duplication the repo's engine/shell\n * rule exists to prevent.\n */\n\nimport { classifyTurnOutcome, describeReason, type TurnHealthReason } from './classify.js'\nimport type { AlertSink, TurnHealthAlert } from './sink.js'\nimport { SIZED_READ_BYTES, sizedBatches } from '../launch-invariants/sized-reads.js'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n /** The newest of these messages was followed by a row that showed the person\n * something (a failure notice or error prose), so they know it failed. False\n * or absent: nothing came back at all. */\n notified?: boolean\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. Left undefined by a source that\n * lists rows by {@link partsSize} and serves parts through\n * {@link TurnHealthSource.readParts}. */\n parts: unknown\n /** Stored length of `parts` (SQLite `length()`), set when the row was listed\n * without them. The sweep batches {@link TurnHealthSource.readParts} by it. */\n partsSize?: number | null\n outputTokens?: number | null\n model?: string | null\n createdAt: number\n}\n\n/** What the sweep needs from a store. A product on a non-standard schema\n * implements these two reads; everything else is shared. */\nexport interface TurnHealthSource {\n findUnansweredThreads(input: {\n minAgeMs: number\n /** Ignore user messages older than this. See {@link SweepOptions.maxAgeMs}. */\n maxAgeMs: number\n now: number\n }): Promise<UnansweredThread[]>\n listRecentAssistantTurns(input: { sinceMs: number; now: number; limit: number }): Promise<\n PersistedTurnRow[]\n >\n /**\n * The stored `parts` of these rows, by id, for a source that lists rows\n * without them. The sweep asks for at most {@link TURN_HEALTH_PARTS_BATCH_SIZE}\n * of parts at a time and judges each batch before it reads the next, so memory\n * holds one batch rather than the whole window.\n *\n * On 2026-10-10 gtm-agent's 500 newest assistant rows carried 122 MB of\n * parts (the largest 2.8 MB). Read in one query they exceeded the Worker's\n * 128 MB, which stopped the hourly cron and every sweep queued after this one.\n */\n readParts?(ids: readonly string[]): Promise<Map<string, unknown>>\n}\n\n/**\n * The part fields classifyTurnOutcome reads, as SQL over one `json_each` row.\n * Each string field is taken only when its JSON type is text, so a non-string\n * value reads exactly as the classifier would see it in the full part.\n */\n/** `expr` evaluated only on an object part: json_type and json_extract raise on a bare string element. */\nconst onObject = (expr: string) => `CASE WHEN p.type = 'object' THEN ${expr} END`\n/** The value at `path` when it is a JSON string, else NULL. */\nconst textAt = (path: string, take = `json_extract(p.value, '${path}')`) => onObject(`CASE WHEN json_type(p.value, '${path}') = 'text' THEN ${take} END`)\nconst PART_PROJECTION = [\n `p.type AS partKind`,\n `${textAt('$.type')} AS type`,\n `coalesce(${onObject(`CASE WHEN json_type(p.value, '$.text') = 'text' AND length(trim(json_extract(p.value, '$.text'), char(32, 9, 10, 13))) > 0 THEN 1 ELSE 0 END`)}, 0) AS hasText`,\n `${textAt('$.tool')} AS tool`,\n `${onObject(`json_type(p.value, '$.state')`)} AS stateKind`,\n `${textAt('$.state.status')} AS status`,\n `${textAt('$.state.error', `substr(json_extract(p.value, '$.state.error'), 1, 200)`)} AS stateError`,\n `${onObject(`json_type(p.value, '$.state.input')`)} AS inputKind`,\n `${textAt('$.state.input.error', `substr(json_extract(p.value, '$.state.input.error'), 1, 200)`)} AS inputError`,\n `${textAt('$.state.input.tool')} AS inputTool`,\n `${textAt('$.state.input', `json_valid(json_extract(p.value, '$.state.input'))`)} AS inputValid`,\n `${textAt('$.state.input', `substr(json_extract(p.value, '$.state.input'), 1, 120)`)} AS inputSample`,\n].join(',\\n ')\n\ninterface ProjectedPart {\n partKind: string | null\n type: string | null\n hasText: number\n tool: string | null\n stateKind: string | null\n status: string | null\n stateError: string | null\n inputKind: string | null\n inputError: string | null\n inputTool: string | null\n inputValid: number | null\n inputSample: string | null\n}\n\n/** A part rebuilt from its projection, judged by classifyTurnOutcome as the stored part would be. */\nfunction slimPart(row: ProjectedPart): unknown {\n // classifyTurnOutcome treats an array part as a record with no type (an opaque part) and skips any other non-object.\n if (row.partKind === 'array') return []\n if (row.partKind !== 'object') return null\n const part: Record<string, unknown> = {}\n if (row.type !== null) part.type = row.type\n if (row.hasText) part.text = 'x'\n if (row.tool !== null) part.tool = row.tool\n if (row.stateKind === 'object') {\n const state: Record<string, unknown> = {}\n if (row.status !== null) state.status = row.status\n if (row.stateError !== null) state.error = row.stateError\n if (row.inputKind === 'object') {\n const input: Record<string, unknown> = {}\n if (row.inputError !== null) input.error = row.inputError\n if (row.inputTool !== null) input.tool = row.inputTool\n state.input = input\n } else if (row.inputKind === 'text') {\n // A parseable string reads as parseable; an unparseable one keeps its sample and a NUL after it, so its prefix\n // can never parse by accident.\n state.input = row.inputValid ? '{}' : `${row.inputSample ?? ''}\\u0000`\n } else if (row.inputKind !== null) {\n state.input = null\n }\n part.state = state\n }\n return part\n}\n\n/** Most stored parts the sweep reads in one batch; a larger row is read alone. */\nexport const TURN_HEALTH_PARTS_BATCH_SIZE = SIZED_READ_BYTES\n\n/** Consecutive rows whose listed parts size fits one read. */\nfunction partsBatches(rows: readonly PersistedTurnRow[]): PersistedTurnRow[][] {\n return sizedBatches(rows.map((row) => ({ key: row, size: row.partsSize })), { bytes: TURN_HEALTH_PARTS_BATCH_SIZE })\n}\n\n/** The listed rows with their parts, read one batch at a time when the source listed them without. */\nasync function* withParts(rows: readonly PersistedTurnRow[], source: TurnHealthSource): AsyncGenerator<PersistedTurnRow> {\n for (const batch of partsBatches(rows)) {\n const unread = batch.filter((row) => row.parts === undefined && (row.partsSize ?? 0) > 0).map((row) => row.id)\n // A read failure propagates, like the listing's, so the caller retries the sweep.\n const read = unread.length > 0 && source.readParts ? await source.readParts(unread) : null\n for (const row of batch) yield read?.has(row.id) ? { ...row, parts: read.get(row.id) } : row\n }\n}\n\nexport interface SweepOptions {\n product: string\n source: TurnHealthSource\n sink: AlertSink\n /** A user message must go unanswered this long before it counts. Guards\n * against alerting on a turn that is simply still streaming. Default 15 min. */\n minAgeMs?: number\n /**\n * A user message OLDER than this is abandoned, not unanswered — it stops\n * counting. Default 7 days.\n *\n * Without this bound the sweep is worse than useless. gtm-agent's table\n * holds 384 unanswered messages whose oldest is 1,676 h (70 days) old;\n * paging hourly on a backlog nobody will ever reply to is exactly how an\n * alert channel gets muted, and a muted channel is the state this module\n * exists to escape. The alert has to mean \"something broke recently\".\n */\n maxAgeMs?: number\n /** How far back to judge settled turns. Default 24 h. */\n lookbackMs?: number\n /** Cap on rows judged per sweep. Default 500. */\n limit?: number\n /** Fraction of recent turns allowed to be silently broken before paging.\n * Default 0.05 — the measured blank-completion rate on the tax tool surface\n * was 12.2%, so 5% separates a real regression from noise. */\n emptyRateThreshold?: number\n /** Absolute floor: never page on a rate computed from fewer turns than this. */\n minTurnsForRate?: number\n /** Declare that this product's deliverable comes from TOOL calls, which\n * switches on the dead-tool-surface detector.\n *\n * Opt-in because only the product knows: a copilot that answers from context\n * is perfectly healthy with zero tool calls, while an agent whose entire job\n * is to file, draft, or submit something is broken the moment its tool\n * surface goes quiet — and broken INVISIBLY, because every turn still\n * returns fluent prose and HTTP 200.\n *\n * This is the fourth failure shape, and the only one no per-turn rule can\n * see.\n *\n * The verdict is drawn ONLY over turns whose parts were present and\n * readable. An earlier revision counted rows that stored no parts, and the\n * production example this comment used to cite was that bug rather than a\n * finding: tax-agent's 97 parts-less rows all predate its parts persistence\n * (they stop at 2026-07-17T02:20Z, the encrypted rows start 02:58Z), while\n * the same database's `turn_events` table holds 243 `tool_call` frames over\n * 15 turns. The tool surface was never dead; the rows were empty. */\n expectsToolCalls?: boolean\n /** Turns needed before a dead tool surface is called. Default 10. */\n minTurnsForToolSurface?: number\n /**\n * Make an at-rest parts encoding readable, so this sweep can judge a product\n * that does not store parts in the clear.\n *\n * Without it, a product that encrypts `parts` (tax-agent wraps the whole\n * array in one `__encrypted_parts__` part) is permanently UNMEASURABLE by the\n * tool-surface rule: every row is opaque, so the honest verdict is \"cannot\n * certify\" forever. This seam is how such a product gets a real verdict\n * instead of permanent blindness — the sweep stays domain-free and the\n * product supplies the decoder.\n *\n * Return the decoded parts value (it is parsed exactly like a stored one).\n * Returning `null`/`undefined` or THROWING leaves the row's stored value in\n * place, so a decoder that fails reports the row as opaque. It must never\n * report success as an empty array: that manufactures the exact absent-parts\n * blindness this module now refuses to draw conclusions from.\n */\n decodeParts?: (raw: unknown, row: PersistedTurnRow) => Promise<unknown> | unknown\n /**\n * Which threads that got no reply at all should page (a `critical` alert);\n * the rest are reported as a `warning`. A product passes its own rule, such\n * as only its customers' and operators' threads, so internal and evaluation\n * traffic stops paging. Default: threads silent for 24 hours or more.\n */\n pageSilentThreads?: (threads: UnansweredThread[]) => Promise<UnansweredThread[]> | UnansweredThread[]\n /**\n * Where a product already reports threads that ended on a failure the person\n * saw, such as its reliability report. When set, those threads are counted\n * but not alerted here. Unset, they are a `warning`, so a product whose every\n * reply is an error message still shows up.\n */\n failureNoticesReportedBy?: string\n now?: number\n}\n\nconst defaultPageSilentThreads = (threads: UnansweredThread[]) => threads.filter((thread) => thread.oldestAgeMs >= 24 * HOUR_MS)\n\n/** Apply the optional decoder, falling back to the stored value on any failure\n * so a broken decoder degrades to blindness (reported) rather than to a fake\n * empty parts array (silent). */\nasync function decodeRowParts(\n decode: SweepOptions['decodeParts'],\n row: PersistedTurnRow,\n): Promise<unknown> {\n if (!decode) return row.parts\n try {\n const decoded = await decode(row.parts, row)\n return decoded ?? row.parts\n } catch {\n return row.parts\n }\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n /** Threads whose user messages have no real answer: {@link silentThreads}\n * plus {@link notifiedThreads}. */\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n /** Threads where nothing came back after the newest message. */\n silentThreads: number\n /** Of {@link silentThreads}, the ones `pageSilentThreads` selected. */\n pagedSilentThreads: number\n /** Threads that ended on a failure the person saw. */\n notifiedThreads: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n /** Tool calls the harness rejected while settling them as `completed`. */\n rejectedToolCalls: number\n /** Turns carrying at least one tool part. */\n turnsWithToolCalls: number\n /** Total tool parts across the window. */\n toolCalls: number\n /** Turns the classifier could not interpret at all (encrypted at rest, or a\n * part vocabulary this module does not know). These are EXCLUDED from\n * `turnsJudged`-based rates — a rate computed over rows nobody could read is\n * a fabricated number. */\n unreadableTurns: number\n /** Turns whose PARTS could not be interpreted. A superset of\n * {@link unreadableTurns} (a row can have readable text and opaque parts).\n * No tool verdict is drawn over these. */\n opaquePartsTurns: number\n /** Turns that persisted NO parts at all. Distinct from\n * {@link opaquePartsTurns}: nothing failed to parse, there was simply\n * nothing there. Also excluded from every tool verdict. */\n noPartsTurns: number\n /** Turns a tool verdict may actually be drawn from — parts present AND\n * interpretable. The denominator behind `dead_tool_surface`. */\n toolReadableTurns: number\n alerts: TurnHealthAlert[]\n}\n\nfunction parseParts(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw\n if (typeof raw !== 'string' || raw.trim().length === 0) return []\n try {\n const parsed = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed : []\n } catch {\n // A parts column that is not JSON is itself a corruption worth seeing, but\n // it is not this detector's job — treat as no parts rather than throwing.\n return []\n }\n}\n\nconst HOUR_MS = 3_600_000\n\n/**\n * Assistant-row openers agent-app writes ITSELF when a sandbox turn fails.\n *\n * Kept byte-identical to the strings `createSandboxChatProducer` composes\n * (`src/chat-routes/sandbox-producer.ts`). They are shell vocabulary, not\n * product domain, so recognising them is this package's job — a product on\n * the shared producer gets a correct sweep with no configuration.\n *\n * `tests/turn-health/turn-health.test.ts` pins these against the producer, so\n * changing the producer's wording without changing this list fails CI rather\n * than silently making dead threads look answered.\n */\n/** D1's maximum LIKE pattern length, including the trailing `%`. Measured, not\n * documented: 50 succeeds, 51 raises `SQLITE_ERROR: LIKE or GLOB pattern too\n * complex`. */\nexport const D1_MAX_LIKE_PATTERN_LENGTH = 50\n\nexport const SHELL_ERROR_REPLY_PREFIXES: readonly string[] = [\n 'The sandbox model stream stopped before a clean completion.',\n 'The sandbox agent returned an error before producing a visible answer.',\n \"The assistant's model refused its access key, so this message was not answered.\",\n]\n\n/**\n * Run one sweep and deliver whatever it finds.\n *\n * Errors from the sink are NOT swallowed here (unlike the live lane): a sweep\n * that could not deliver has accomplished nothing, and its cron invocation\n * should go red rather than report a clean run.\n */\nexport async function sweepSilentFailures(options: SweepOptions): Promise<SweepResult> {\n const now = options.now ?? Date.now()\n const minAgeMs = options.minAgeMs ?? 15 * 60_000\n const maxAgeMs = options.maxAgeMs ?? 7 * 24 * HOUR_MS\n const lookbackMs = options.lookbackMs ?? 24 * HOUR_MS\n const limit = options.limit ?? 500\n const emptyRateThreshold = options.emptyRateThreshold ?? 0.05\n const minTurnsForRate = options.minTurnsForRate ?? 10\n const minTurnsForToolSurface = options.minTurnsForToolSurface ?? 10\n // Half the window opaque means the sweep is guessing. Fixed rather than\n // configurable: a product must not be able to tune its own blindness report\n // into silence.\n const blindThreshold = 0.5\n\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, maxAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n const silent = unanswered.filter((t) => !t.notified)\n const notified = unanswered.filter((t) => t.notified)\n const paged = new Set(\n (await (options.pageSilentThreads ?? defaultPageSilentThreads)(silent)).map((t) => t.threadId),\n )\n const describeThread = (t: UnansweredThread) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(t.oldestAgeMs / HOUR_MS).toFixed(1)}h`\n\n if (silent.length > 0) {\n const silentMessages = silent.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldest = silent.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n alerts.push({\n product: options.product,\n severity: paged.size > 0 ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${silentMessages} user message(s) unanswered across ${silent.length} thread(s), with no reply at all`,\n details: [\n `oldest unanswered message: ${(oldest / HOUR_MS).toFixed(1)}h; ${paged.size} of these thread(s) page`,\n // The threads that page come first, so the alert names what to open.\n ...[...silent.filter((t) => paged.has(t.threadId)), ...silent.filter((t) => !paged.has(t.threadId))]\n .slice(0, 5)\n .map((t) => `${describeThread(t)}${paged.has(t.threadId) ? ' (pages)' : ''}`),\n ],\n data: { silentThreads: silent.length, pagedSilentThreads: paged.size, pendingUserMessages: silentMessages, oldestUnansweredMs: oldest },\n at: now,\n })\n }\n if (notified.length > 0 && !options.failureNoticesReportedBy) {\n const notifiedMessages = notified.reduce((sum, t) => sum + t.pendingMessages, 0)\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:failed_threads`,\n title: `${options.product}: ${notifiedMessages} user message(s) across ${notified.length} thread(s) ended on a failure the person saw`,\n details: notified.slice(0, 5).map(describeThread),\n data: { notifiedThreads: notified.length, pendingUserMessages: notifiedMessages },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let rejectedToolCalls = 0\n let unhealthyTurns = 0\n let turnsWithToolCalls = 0\n let toolCalls = 0\n let unreadableTurns = 0\n // Turns whose PARTS were interpretable — the only rows a tool verdict may be\n // drawn from. Distinct from `unreadableTurns`, which is the harder blindness\n // (nothing judgeable at all).\n let toolReadableTurns = 0\n let opaquePartsTurns = 0\n // Rows that persisted NO parts at all. Not opaque (nothing failed to parse)\n // and not evidence either — counted separately so the coverage line can say\n // which of the two blindnesses applies.\n let noPartsTurns = 0\n const opaqueTypes = new Set<string>()\n const malformedSamples: TurnHealthReason[] = []\n const rejectedSamples: TurnHealthReason[] = []\n\n for await (const row of withParts(turns, options.source)) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(await decodeRowParts(options.decodeParts, row)),\n outputTokens: row.outputTokens ?? null,\n })\n toolCalls += verdict.toolCalls\n if (verdict.toolCalls > 0) turnsWithToolCalls += 1\n // A tool verdict needs evidence that was READ. `partsReadable` alone is\n // satisfied vacuously by a row that persisted no parts, which is how a\n // product with 243 real tool calls was paged as having a dead tool surface.\n if (verdict.partsReadable && verdict.interpretedParts > 0) toolReadableTurns += 1\n else if (verdict.partsReadable) noPartsTurns += 1\n else {\n opaquePartsTurns += 1\n for (const t of verdict.opaquePartTypes) opaqueTypes.add(t)\n }\n if (verdict.unreadable) {\n unreadableTurns += 1\n continue\n }\n if (verdict.healthy) continue\n unhealthyTurns += 1\n for (const reason of verdict.reasons) {\n if (reason.kind === 'empty_completion') emptyCompletions += 1\n if (reason.kind === 'malformed_tool_call') {\n malformedToolCalls += 1\n if (malformedSamples.length < 3) malformedSamples.push(reason)\n }\n if (reason.kind === 'tool_call_no_effect') toolCallsWithoutEffect += 1\n if (reason.kind === 'tool_call_rejected') {\n rejectedToolCalls += 1\n if (rejectedSamples.length < 3) rejectedSamples.push(reason)\n }\n }\n }\n\n // Turns this sweep could actually judge. Every rate below divides by THIS,\n // never by the raw row count.\n const readableTurns = turns.length - unreadableTurns\n\n // A malformed tool call is never acceptable at any rate — it means a\n // deliverable was requested and silently discarded. Page on the first one.\n if (malformedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:malformed_tool_call`,\n title: `${options.product}: ${malformedToolCalls} tool call(s) had unparseable arguments — deliverables silently dropped`,\n details: malformedSamples.map(describeReason),\n data: { malformedToolCalls, turnsJudged: turns.length },\n at: now,\n })\n }\n\n // A rejected call means a deliverable was requested and thrown away while the\n // turn reported success. Never acceptable at any rate.\n if (rejectedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:tool_call_rejected`,\n title: `${options.product}: ${rejectedToolCalls} tool call(s) were REJECTED but settled as completed — deliverables silently dropped`,\n details: rejectedSamples.map(describeReason),\n data: { rejectedToolCalls, turnsJudged: readableTurns },\n at: now,\n })\n }\n\n if (readableTurns >= minTurnsForRate) {\n const rate = emptyCompletions / readableTurns\n if (rate > emptyRateThreshold) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:empty_completion_rate`,\n title: `${options.product}: ${(rate * 100).toFixed(1)}% of turns completed with no output`,\n details: [\n `${emptyCompletions} of ${readableTurns} readable settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: readableTurns, rate },\n at: now,\n })\n }\n }\n\n // ── the fourth shape: a tool surface that has gone quiet ───────────────\n //\n // Nothing errors, every turn answers fluently, and the product stops DOING\n // anything. Only visible across a window, which is why it needs its own pass\n // rather than a rule inside the per-turn classifier.\n // Judged ONLY over turns whose parts could be interpreted, and the count of\n // rows that could not is stated in the alert — a verdict that names its own\n // coverage can be trusted; one that hides it cannot.\n if (options.expectsToolCalls && toolReadableTurns >= minTurnsForToolSurface && toolCalls === 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:dead_tool_surface`,\n title: `${options.product}: ZERO tool calls across ${toolReadableTurns} turns — the tool surface is dead`,\n details: [\n `${toolReadableTurns} assistant turns with readable parts in the lookback, none of which called a tool`,\n 'the product declares its deliverable comes from tool calls, so it has answered without doing anything',\n ...(opaquePartsTurns > 0\n ? [`${opaquePartsTurns} further turn(s) had unreadable parts and were not judged`]\n : []),\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} further turn(s) persisted no parts at all and were not judged`]\n : []),\n ],\n data: {\n turnsJudged: toolReadableTurns,\n toolCalls: 0,\n turnsWithToolCalls: 0,\n turnsNotJudged: opaquePartsTurns + noPartsTurns,\n opaquePartsTurns,\n noPartsTurns,\n },\n at: now,\n })\n }\n\n // A product that ASKED for a tool-surface verdict and did not get one must be\n // told that, or the absence of a page reads as a pass. This is the honest\n // form of the alert above: same question, and the answer is \"I could not\n // see\", which is a real finding about the product's observability rather than\n // a fabricated finding about its behaviour.\n if (\n options.expectsToolCalls &&\n toolReadableTurns < minTurnsForToolSurface &&\n opaquePartsTurns + noPartsTurns > 0\n ) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:tool_surface_unmeasurable`,\n title: `${options.product}: tool surface could not be certified — only ${toolReadableTurns} of ${turns.length} turns carried readable parts`,\n details: [\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} turn(s) persisted no parts at all — nothing to read a tool call from`]\n : []),\n ...(opaquePartsTurns > 0\n ? [\n `${opaquePartsTurns} turn(s) stored parts this sweep cannot interpret (${\n [...opaqueTypes].join(', ') || 'unnamed'\n }) — supply \\`decodeParts\\` to make them readable`,\n ]\n : []),\n 'this is NOT a dead tool surface finding; it is the absence of evidence either way',\n ],\n data: {\n toolReadableTurns,\n noPartsTurns,\n opaquePartsTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n // ── the detector reporting on ITSELF ───────────────────────────────────\n //\n // The one verdict this module must never give is \"healthy\" derived from rows\n // it could not read. If most of the window was opaque, that fact is the\n // alert — silence here would be the module committing the exact failure it\n // was built to catch.\n if (opaquePartsTurns > 0 && opaquePartsTurns >= turns.length * blindThreshold) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:detector_blind`,\n title: `${options.product}: ${opaquePartsTurns} of ${turns.length} turns have unreadable parts — this sweep cannot certify them`,\n details: [\n `uninterpretable part types: ${[...opaqueTypes].join(', ') || '(none named)'}`,\n 'these rows are excluded from every verdict above; treat them as UNMEASURED, not healthy',\n ],\n data: {\n opaquePartsTurns,\n unreadableTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n silentThreads: silent.length,\n pagedSilentThreads: paged.size,\n notifiedThreads: notified.length,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n rejectedToolCalls,\n turnsWithToolCalls,\n toolCalls,\n unreadableTurns,\n opaquePartsTurns,\n noPartsTurns,\n toolReadableTurns,\n alerts,\n }\n}\n\n// ── D1 source for the shared chat-store schema ────────────────────────────\n\n/** Minimal structural D1 contract (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForHealth {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\n/**\n * The sweep source for products on the canonical `/chat-store` tables.\n *\n * \"Answered\" deliberately means an assistant row with NON-EMPTY content. A\n * blank assistant row is what a broken turn writes, so counting it as an\n * answer would let the exact failure being hunted mark itself resolved. That\n * single predicate is the difference between this catching the gtm outage and\n * sleeping through it — during those sixteen days the table was NOT empty.\n *\n * The query deliberately does NOT join the thread table. Products do not all\n * keep one: tax-agent's `thread` table holds zero rows because it groups by\n * its own `tax_sessions`, and an inner join against it silently reported \"0\n * unanswered threads, healthy\" while 18 real messages sat unanswered. A\n * detector that reports healthy because its join found nothing is the same\n * bug class it was built to catch.\n */\nexport function createD1TurnHealthSource(\n db: D1LikeForHealth,\n options: {\n messageTable?: string\n threadTable?: string\n /**\n * Content prefixes that mark an assistant row as an ERROR SURFACE rather\n * than an answer. A row matching one of these stops counting as a reply,\n * so the thread keeps reporting as unanswered.\n *\n * This exists because the obvious rule — \"an assistant row with non-empty\n * content is an answer\" — is wrong in the exact case that matters. On\n * 2026-07-27 gtm-agent's newest assistant row read:\n *\n * \"The sandbox model stream stopped before a clean completion.\n * Error: All 2 model(s) failed. gpt-5-mini: TANGLE_HUB_URL is required …\"\n *\n * 246 characters of well-formed prose that answers nothing. Counting it\n * marks a dead product healthy — the same failure-returning-success shape\n * this module exists to catch, recursing into the detector itself.\n *\n * There is no schema-level way to recognise it: `output_tokens IS NULL`\n * looked promising until legal-agent showed 22 of 25 GENUINE replies with\n * null usage — it would have reported a working product broken.\n *\n * Defaults to {@link SHELL_ERROR_REPLY_PREFIXES}, the openers agent-app\n * ITSELF writes in `createSandboxChatProducer`. Those are not domain —\n * this package composed them, so this package is what must recognise\n * them, and every product on the shared producer is correct with no\n * configuration. Pass your own list to ADD product-specific error prose;\n * pass `[]` to disable the rule.\n *\n * Prefixes are bound as query parameters, never interpolated.\n */\n errorReplyPrefixes?: readonly string[]\n /**\n * Read each row's whole `parts` instead of the fields the classifier reads.\n * Only a product whose `decodeParts` needs the stored bytes (an encrypted\n * parts envelope) sets this; the default reads a small projection.\n */\n fullParts?: boolean\n } = {},\n): TurnHealthSource {\n // Table names are identifiers and cannot be bound as parameters. They come\n // from deploy-time product config, never from a request, and are validated\n // here so this can never become an injection point.\n const message = safeIdentifier(options.messageTable ?? 'message')\n const thread = safeIdentifier(options.threadTable ?? 'thread')\n // D1 rejects a LIKE pattern longer than 50 characters with\n // `SQLITE_ERROR: LIKE or GLOB pattern too complex`, and the pattern is the\n // prefix PLUS the trailing `%`. Measured against production D1 on\n // 2026-07-27: a 49-char prefix (50-char pattern) succeeds, 50 fails.\n //\n // Both shipped defaults are longer than that (55 and 70 characters), so\n // before this clamp `findUnansweredThreads` threw on every product database\n // — the detector could not run at all against the only store the fleet uses.\n //\n // Truncating is safe in the one direction that matters: a shorter prefix\n // matches MORE rows as non-answers, so a thread is reported unanswered\n // rather than silently marked healthy. The first 49 characters of each\n // default are still unambiguous.\n const errorPrefixes = [...(options.errorReplyPrefixes ?? SHELL_ERROR_REPLY_PREFIXES)].map((p) =>\n p.slice(0, D1_MAX_LIKE_PATTERN_LENGTH - 1),\n )\n\n return {\n async findUnansweredThreads({ minAgeMs, maxAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const floorSeconds = Math.floor((now - maxAgeMs) / 1000)\n // Each prefix becomes one bound `NOT LIKE ?||'%'` term. Parameters, not\n // interpolation — a product-supplied string never reaches the SQL text.\n const errorClause = errorPrefixes\n .map((_, i) => ` AND a.content NOT LIKE ?${i + 3} || '%'`)\n .join('')\n // A row after the newest pending message that showed something (error\n // prose, or a notice part) means the person saw the failure. A blank row\n // with no notice showed nothing, so its thread stays silent.\n const { results } = await db\n .prepare(\n `WITH pending AS (\n SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt,\n MAX(m.created_at) AS newestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at >= ?2\n AND m.created_at > COALESCE(\n (SELECT MAX(a.created_at)\n FROM ${message} a\n WHERE a.thread_id = m.thread_id\n AND a.role = 'assistant'\n AND length(trim(a.content)) > 0${errorClause}), 0)\n GROUP BY m.thread_id\n )\n SELECT p.threadId, p.pendingMessages, p.oldestCreatedAt,\n EXISTS (\n SELECT 1 FROM ${message} a\n WHERE a.thread_id = p.threadId AND a.role = 'assistant' AND a.created_at >= p.newestCreatedAt\n AND (length(trim(coalesce(a.content, ''))) > 0 OR EXISTS (\n SELECT 1 FROM json_each(CASE WHEN json_valid(a.parts) THEN CASE WHEN json_type(a.parts) = 'array' THEN a.parts ELSE '[]' END ELSE '[]' END) n\n WHERE CASE WHEN n.type = 'object' THEN json_extract(n.value, '$.type') END = 'notice'))\n ) AS notified\n FROM pending p\n ORDER BY p.oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number; notified: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n notified: Number(row.notified) === 1,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, length(parts) AS partsSize,\n output_tokens AS outputTokens, model, created_at AS createdAt\n FROM ${message}\n WHERE role = 'assistant' AND created_at >= ?1\n ORDER BY created_at DESC\n LIMIT ?2`,\n )\n .bind(sinceSeconds, limit)\n .all<Record<string, unknown>>()\n\n return results.map((row) => ({\n id: String(row.id),\n threadId: String(row.threadId),\n content: typeof row.content === 'string' ? row.content : '',\n parts: undefined,\n partsSize: row.partsSize === null ? null : Number(row.partsSize),\n outputTokens: row.outputTokens === null ? null : Number(row.outputTokens),\n model: (row.model as string | null) ?? null,\n createdAt: Number(row.createdAt) * 1000,\n }))\n },\n\n async readParts(ids) {\n if (ids.length === 0) return new Map()\n const placeholders = ids.map((_, i) => `?${i + 1}`).join(', ')\n if (options.fullParts) {\n const { results } = await db\n .prepare(`SELECT id, parts FROM ${message} WHERE id IN (${placeholders})`)\n .bind(...ids)\n .all<{ id: string; parts: unknown }>()\n return new Map(results.map((row) => [String(row.id), row.parts]))\n }\n // One row per part with only what classifyTurnOutcome reads, so a day of\n // tool output never leaves the database: the full read\n // returned 141.9 MB per run for 500 turns.\n const { results } = await db\n .prepare(`SELECT m.id AS id, CAST(p.key AS INTEGER) AS idx, ${PART_PROJECTION}\n FROM ${message} m, json_each(CASE WHEN json_valid(m.parts) THEN CASE WHEN json_type(m.parts) = 'array' THEN m.parts ELSE '[]' END ELSE '[]' END) p\n WHERE m.id IN (${placeholders})\n ORDER BY m.id, idx`)\n .bind(...ids)\n .all<ProjectedPart & { id: string }>()\n const parts = new Map<string, unknown[]>(ids.map((id) => [id, []]))\n for (const row of results) parts.get(String(row.id))?.push(slimPart(row))\n return parts\n },\n }\n\n function safeIdentifier(name: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe table identifier: ${name}`)\n }\n return name\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqEA,SAAS,UAAU,OAAwB;AACzC,MAAI,iBAAiB,MAAO,QAAO,MAAM;AACzC,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,SAAO,OAAO,KAAK;AACrB;AAYO,SAAS,0BACd,SACqB;AAErB,QAAM,OAAO,uBAAuB,QAAQ,IAAI;AAEhD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,YAAM,UAAU,oBAAoB;AAAA,QAClC,WAAW,KAAK;AAAA,QAChB,cAAc,KAAK,OAAO,gBAAgB;AAAA,QAC1C,YAAY,KAAK;AAAA,QACjB,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,IAAI,CAAC;AAAA,MACtC,CAAC;AACD,cAAQ,YAAY;AAAA,QAClB,SAAS,QAAQ;AAAA,QACjB,SAAS,QAAQ;AAAA,QACjB,OAAO,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,QACxC,YAAY,KAAK;AAAA,MACnB,CAAC;AACD,UAAI,QAAQ,WAAW,QAAQ,aAAa,KAAM;AAElD,UAAI,CAAC,QAAQ,oBAAoB,QAAQ,QAAQ,MAAM,CAAC,MAAM,EAAE,SAAS,wBAAwB,GAAG;AAClG;AAAA,MACF;AACA,YAAM,KAAK;AAAA,QACT,UAAU;AAAA,UACR,SAAS,QAAQ;AAAA,UACjB,UAAU,QAAQ;AAAA,UAClB,SAAS,QAAQ;AAAA,UACjB,GAAI,KAAK,WAAW,EA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GAAG,MAAM,IAAI,IAAI,CAAC,EAAE,EAAE,KAAK,IAAI;AAC7D,UAAI,QAAQ,WAAW;AACrB,cAAM,EAAE,SAAAA,SAAQ,IAAI,MAAM,GACvB,QAAQ,yBAAyB,OAAO,iBAAiB,YAAY,GAAG,EACxE,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,eAAO,IAAI,IAAIA,SAAQ,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,EAAE,GAAG,IAAI,KAAK,CAAC,CAAC;AAAA,MAClE;AAIA,YAAM,EAAE,QAAQ,IAAI,MAAM,GACvB,QAAQ,qDAAqD,eAAe;AAAA,oBACjE,OAAO;AAAA,6BACE,YAAY;AAAA,+BACV,EACtB,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,YAAM,QAAQ,IAAI,IAAuB,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClE,iBAAW,OAAO,QAAS,OAAM,IAAI,OAAO,IAAI,EAAE,CAAC,GAAG,KAAK,SAAS,GAAG,CAAC;AACxE,aAAO;AAAA,IACT;AAAA,EACF;AAEA,WAAS,eAAe,MAAsB;AAC5C,QAAI,CAAC,2BAA2B,KAAK,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACF;","names":["results"]}
|
|
1
|
+
{"version":3,"sources":["../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n /** `/chat-routes` sets this when a `contextGate` short-circuited the turn and\n * the producer never ran. */\n gated?: boolean\n}\n\n/** Structural mirror of the lifecycle error payload. */\nexport interface TurnHealthErrorInfo {\n error: unknown\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\n\n/** What {@link createTurnHealthLifecycle} returns — assignable to\n * `createChatTurnRoutes`' `lifecycle` option. */\nexport interface TurnHealthLifecycle {\n onTurnComplete(info: TurnHealthCompleteInfo): Promise<void>\n onTurnError(info: TurnHealthErrorInfo): Promise<void>\n}\n\nexport interface TurnHealthLifecycleOptions {\n /** Names the product in every alert. */\n product: string\n sink: AlertSink\n /** Called for every verdict, healthy or not — the hook for a counter or a\n * metrics push. Alerts are for humans; this is for graphs. */\n onVerdict?(verdict: {\n product: string\n healthy: boolean\n kinds: string[]\n durationMs: number\n }): void\n /** Page when a turn was answered by a gate instead of the model.\n *\n * Default `false`, and the default is the honest one: gating is a legitimate\n * design and a product that gates its intake would otherwise page on every\n * healthy turn. Whether the rate is pathological is domain knowledge, so it\n * stays a product decision — the verdict is ALWAYS reported through\n * {@link TurnHealthLifecycleOptions.onVerdict} so a counter can watch the\n * rate even when nobody is paged. */\n alertOnGatedTurn?: boolean\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n return String(error)\n}\n\n/**\n * Build the lifecycle hooks that page on a turn which succeeded at nothing.\n *\n * The live lane sees `finalText` and usage but not the persisted parts, so it\n * catches the blank-completion and hard-failure shapes immediately. The\n * parts-dependent shapes (a tool call whose arguments never parsed, a tool\n * call that left no effect) are caught by {@link sweepSilentFailures}, which\n * reads what was actually written to the store — the honest place to ask\n * whether an effect persisted.\n */\nexport function createTurnHealthLifecycle(\n options: TurnHealthLifecycleOptions,\n): TurnHealthLifecycle {\n // Guarded: a paging failure must never take down a customer's turn.\n const sink = createGuardedAlertSink(options.sink)\n\n return {\n async onTurnComplete(info) {\n const verdict = classifyTurnOutcome({\n finalText: info.finalText,\n outputTokens: info.usage?.outputTokens ?? null,\n durationMs: info.durationMs,\n ...(info.gated ? { gated: true } : {}),\n })\n options.onVerdict?.({\n product: options.product,\n healthy: verdict.healthy,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n if (verdict.healthy || verdict.severity === null) return\n // Counted above, paged only on request — see `alertOnGatedTurn`.\n if (!options.alertOnGatedTurn && verdict.reasons.every((r) => r.kind === 'answered_without_model')) {\n return\n }\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: verdict.severity,\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n\n async onTurnError(info) {\n const verdict = classifyTurnOutcome({\n failed: true,\n failureReason: errorText(info.error),\n durationMs: info.durationMs,\n })\n options.onVerdict?.({\n product: options.product,\n healthy: false,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: 'critical',\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n }\n}\n","/**\n * The SWEEP half: ask the store what it has been quietly accumulating.\n *\n * A live per-turn hook cannot see the failure that matters most, because the\n * worst outage produced NO turns at all to hook: gtm-agent took 9–21 user\n * messages a day for sixteen straight days and wrote zero real assistant\n * replies. Nothing crashed on a schedule; the product simply stopped\n * answering. The only thing that could have noticed is something that\n * periodically counts what arrived against what was answered.\n *\n * That is this. It runs on a cron, reads the shared `/chat-store` schema, and\n * pages when the ratio breaks.\n *\n * The queries live HERE and not in each product because all four products\n * (gtm, tax, legal, workcomp) persist to the same `message`/`thread` tables —\n * four copies of this cron is exactly the duplication the repo's engine/shell\n * rule exists to prevent.\n */\n\nimport { classifyTurnOutcome, describeReason, type TurnHealthReason } from './classify.js'\nimport type { AlertSink, TurnHealthAlert } from './sink.js'\nimport { SIZED_READ_BYTES, sizedBatches } from '../launch-invariants/sized-reads.js'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n /** The newest of these messages was followed by a row that showed the person\n * something (a failure notice or error prose), so they know it failed. False\n * or absent: nothing came back at all. */\n notified?: boolean\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. Left undefined by a source that\n * lists rows by {@link partsSize} and serves parts through\n * {@link TurnHealthSource.readParts}. */\n parts: unknown\n /** Stored length of `parts` (SQLite `length()`), set when the row was listed\n * without them. The sweep batches {@link TurnHealthSource.readParts} by it. */\n partsSize?: number | null\n outputTokens?: number | null\n model?: string | null\n createdAt: number\n}\n\n/** What the sweep needs from a store. A product on a non-standard schema\n * implements these two reads; everything else is shared. */\nexport interface TurnHealthSource {\n findUnansweredThreads(input: {\n minAgeMs: number\n /** Ignore user messages older than this. See {@link SweepOptions.maxAgeMs}. */\n maxAgeMs: number\n now: number\n }): Promise<UnansweredThread[]>\n listRecentAssistantTurns(input: { sinceMs: number; now: number; limit: number }): Promise<\n PersistedTurnRow[]\n >\n /**\n * The stored `parts` of these rows, by id, for a source that lists rows\n * without them. The sweep asks for at most {@link TURN_HEALTH_PARTS_BATCH_SIZE}\n * of parts at a time and judges each batch before it reads the next, so memory\n * holds one batch rather than the whole window.\n *\n * On 2026-10-10 gtm-agent's 500 newest assistant rows carried 122 MB of\n * parts (the largest 2.8 MB). Read in one query they exceeded the Worker's\n * 128 MB, which stopped the hourly cron and every sweep queued after this one.\n */\n readParts?(ids: readonly string[]): Promise<Map<string, unknown>>\n}\n\n/**\n * The part fields classifyTurnOutcome reads, as SQL over one `json_each` row.\n * Each string field is taken only when its JSON type is text, so a non-string\n * value reads exactly as the classifier would see it in the full part.\n */\n/** `expr` evaluated only on an object part: json_type and json_extract raise on a bare string element. */\nconst onObject = (expr: string) => `CASE WHEN p.type = 'object' THEN ${expr} END`\n/** The value at `path` when it is a JSON string, else NULL. */\nconst textAt = (path: string, take = `json_extract(p.value, '${path}')`) => onObject(`CASE WHEN json_type(p.value, '${path}') = 'text' THEN ${take} END`)\nconst PART_PROJECTION = [\n `p.type AS partKind`,\n `${textAt('$.type')} AS type`,\n `coalesce(${onObject(`CASE WHEN json_type(p.value, '$.text') = 'text' AND length(trim(json_extract(p.value, '$.text'), char(32, 9, 10, 13))) > 0 THEN 1 ELSE 0 END`)}, 0) AS hasText`,\n `${textAt('$.tool')} AS tool`,\n `${onObject(`json_type(p.value, '$.state')`)} AS stateKind`,\n `${textAt('$.state.status')} AS status`,\n `${textAt('$.state.error', `substr(json_extract(p.value, '$.state.error'), 1, 200)`)} AS stateError`,\n `${onObject(`json_type(p.value, '$.state.input')`)} AS inputKind`,\n `${textAt('$.state.input.error', `substr(json_extract(p.value, '$.state.input.error'), 1, 200)`)} AS inputError`,\n `${textAt('$.state.input.tool')} AS inputTool`,\n `${textAt('$.state.input', `json_valid(json_extract(p.value, '$.state.input'))`)} AS inputValid`,\n `${textAt('$.state.input', `substr(json_extract(p.value, '$.state.input'), 1, 120)`)} AS inputSample`,\n].join(',\\n ')\n\ninterface ProjectedPart {\n partKind: string | null\n type: string | null\n hasText: number\n tool: string | null\n stateKind: string | null\n status: string | null\n stateError: string | null\n inputKind: string | null\n inputError: string | null\n inputTool: string | null\n inputValid: number | null\n inputSample: string | null\n}\n\n/** A part rebuilt from its projection, judged by classifyTurnOutcome as the stored part would be. */\nfunction slimPart(row: ProjectedPart): unknown {\n // classifyTurnOutcome treats an array part as a record with no type (an opaque part) and skips any other non-object.\n if (row.partKind === 'array') return []\n if (row.partKind !== 'object') return null\n const part: Record<string, unknown> = {}\n if (row.type !== null) part.type = row.type\n if (row.hasText) part.text = 'x'\n if (row.tool !== null) part.tool = row.tool\n if (row.stateKind === 'object') {\n const state: Record<string, unknown> = {}\n if (row.status !== null) state.status = row.status\n if (row.stateError !== null) state.error = row.stateError\n if (row.inputKind === 'object') {\n const input: Record<string, unknown> = {}\n if (row.inputError !== null) input.error = row.inputError\n if (row.inputTool !== null) input.tool = row.inputTool\n state.input = input\n } else if (row.inputKind === 'text') {\n // A parseable string reads as parseable; an unparseable one keeps its sample and a NUL after it, so its prefix\n // can never parse by accident.\n state.input = row.inputValid ? '{}' : `${row.inputSample ?? ''}\\u0000`\n } else if (row.inputKind !== null) {\n state.input = null\n }\n part.state = state\n }\n return part\n}\n\n/** Most stored parts the sweep reads in one batch; a larger row is read alone. */\nexport const TURN_HEALTH_PARTS_BATCH_SIZE = SIZED_READ_BYTES\n\n/** Consecutive rows whose listed parts size fits one read. */\nfunction partsBatches(rows: readonly PersistedTurnRow[]): PersistedTurnRow[][] {\n return sizedBatches(rows.map((row) => ({ key: row, size: row.partsSize })), { bytes: TURN_HEALTH_PARTS_BATCH_SIZE })\n}\n\n/** The listed rows with their parts, read one batch at a time when the source listed them without. */\nasync function* withParts(rows: readonly PersistedTurnRow[], source: TurnHealthSource): AsyncGenerator<PersistedTurnRow> {\n for (const batch of partsBatches(rows)) {\n const unread = batch.filter((row) => row.parts === undefined && (row.partsSize ?? 0) > 0).map((row) => row.id)\n // A read failure propagates, like the listing's, so the caller retries the sweep.\n const read = unread.length > 0 && source.readParts ? await source.readParts(unread) : null\n for (const row of batch) yield read?.has(row.id) ? { ...row, parts: read.get(row.id) } : row\n }\n}\n\nexport interface SweepOptions {\n product: string\n source: TurnHealthSource\n sink: AlertSink\n /** A user message must go unanswered this long before it counts. Guards\n * against alerting on a turn that is simply still streaming. Default 15 min. */\n minAgeMs?: number\n /**\n * A user message OLDER than this is abandoned, not unanswered — it stops\n * counting. Default 7 days.\n *\n * Without this bound the sweep is worse than useless. gtm-agent's table\n * holds 384 unanswered messages whose oldest is 1,676 h (70 days) old;\n * paging hourly on a backlog nobody will ever reply to is exactly how an\n * alert channel gets muted, and a muted channel is the state this module\n * exists to escape. The alert has to mean \"something broke recently\".\n */\n maxAgeMs?: number\n /** How far back to judge settled turns. Default 24 h. */\n lookbackMs?: number\n /** Cap on rows judged per sweep. Default 500. */\n limit?: number\n /** Fraction of recent turns allowed to be silently broken before paging.\n * Default 0.05 — the measured blank-completion rate on the tax tool surface\n * was 12.2%, so 5% separates a real regression from noise. */\n emptyRateThreshold?: number\n /** Absolute floor: never page on a rate computed from fewer turns than this. */\n minTurnsForRate?: number\n /** Declare that this product's deliverable comes from TOOL calls, which\n * switches on the dead-tool-surface detector.\n *\n * Opt-in because only the product knows: a copilot that answers from context\n * is perfectly healthy with zero tool calls, while an agent whose entire job\n * is to file, draft, or submit something is broken the moment its tool\n * surface goes quiet — and broken INVISIBLY, because every turn still\n * returns fluent prose and HTTP 200.\n *\n * This is the fourth failure shape, and the only one no per-turn rule can\n * see.\n *\n * The verdict is drawn ONLY over turns whose parts were present and\n * readable. An earlier revision counted rows that stored no parts, and the\n * production example this comment used to cite was that bug rather than a\n * finding: tax-agent's 97 parts-less rows all predate its parts persistence\n * (they stop at 2026-07-17T02:20Z, the encrypted rows start 02:58Z), while\n * the same database's `turn_events` table holds 243 `tool_call` frames over\n * 15 turns. The tool surface was never dead; the rows were empty. */\n expectsToolCalls?: boolean\n /** Turns needed before a dead tool surface is called. Default 10. */\n minTurnsForToolSurface?: number\n /**\n * Make an at-rest parts encoding readable, so this sweep can judge a product\n * that does not store parts in the clear.\n *\n * Without it, a product that encrypts `parts` (tax-agent wraps the whole\n * array in one `__encrypted_parts__` part) is permanently UNMEASURABLE by the\n * tool-surface rule: every row is opaque, so the honest verdict is \"cannot\n * certify\" forever. This seam is how such a product gets a real verdict\n * instead of permanent blindness — the sweep stays domain-free and the\n * product supplies the decoder.\n *\n * Return the decoded parts value (it is parsed exactly like a stored one).\n * Returning `null`/`undefined` or THROWING leaves the row's stored value in\n * place, so a decoder that fails reports the row as opaque. It must never\n * report success as an empty array: that manufactures the exact absent-parts\n * blindness this module now refuses to draw conclusions from.\n */\n decodeParts?: (raw: unknown, row: PersistedTurnRow) => Promise<unknown> | unknown\n /**\n * Which threads that got no reply at all should page (a `critical` alert);\n * the rest are reported as a `warning`. A product passes its own rule, such\n * as only its customers' and operators' threads, so internal and evaluation\n * traffic stops paging. Default: threads silent for 24 hours or more.\n */\n pageSilentThreads?: (threads: UnansweredThread[]) => Promise<UnansweredThread[]> | UnansweredThread[]\n /**\n * Where a product already reports threads that ended on a failure the person\n * saw, such as its reliability report. When set, those threads are counted\n * but not alerted here. Unset, they are a `warning`, so a product whose every\n * reply is an error message still shows up.\n */\n failureNoticesReportedBy?: string\n now?: number\n}\n\nconst defaultPageSilentThreads = (threads: UnansweredThread[]) => threads.filter((thread) => thread.oldestAgeMs >= 24 * HOUR_MS)\n\n/** Apply the optional decoder, falling back to the stored value on any failure\n * so a broken decoder degrades to blindness (reported) rather than to a fake\n * empty parts array (silent). */\nasync function decodeRowParts(\n decode: SweepOptions['decodeParts'],\n row: PersistedTurnRow,\n): Promise<unknown> {\n if (!decode) return row.parts\n try {\n const decoded = await decode(row.parts, row)\n return decoded ?? row.parts\n } catch {\n return row.parts\n }\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n /** Threads whose user messages have no real answer: {@link silentThreads}\n * plus {@link notifiedThreads}. */\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n /** Threads where nothing came back after the newest message. */\n silentThreads: number\n /** Of {@link silentThreads}, the ones `pageSilentThreads` selected. */\n pagedSilentThreads: number\n /** Threads that ended on a failure the person saw. */\n notifiedThreads: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n /** Tool calls the harness rejected while settling them as `completed`. */\n rejectedToolCalls: number\n /** Turns carrying at least one tool part. */\n turnsWithToolCalls: number\n /** Total tool parts across the window. */\n toolCalls: number\n /** Turns the classifier could not interpret at all (encrypted at rest, or a\n * part vocabulary this module does not know). These are EXCLUDED from\n * `turnsJudged`-based rates — a rate computed over rows nobody could read is\n * a fabricated number. */\n unreadableTurns: number\n /** Turns whose PARTS could not be interpreted. A superset of\n * {@link unreadableTurns} (a row can have readable text and opaque parts).\n * No tool verdict is drawn over these. */\n opaquePartsTurns: number\n /** Turns that persisted NO parts at all. Distinct from\n * {@link opaquePartsTurns}: nothing failed to parse, there was simply\n * nothing there. Also excluded from every tool verdict. */\n noPartsTurns: number\n /** Turns a tool verdict may actually be drawn from — parts present AND\n * interpretable. The denominator behind `dead_tool_surface`. */\n toolReadableTurns: number\n alerts: TurnHealthAlert[]\n}\n\nfunction parseParts(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw\n if (typeof raw !== 'string' || raw.trim().length === 0) return []\n try {\n const parsed = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed : []\n } catch {\n // A parts column that is not JSON is itself a corruption worth seeing, but\n // it is not this detector's job — treat as no parts rather than throwing.\n return []\n }\n}\n\nconst HOUR_MS = 3_600_000\n\n/**\n * Assistant-row openers agent-app writes ITSELF when a sandbox turn fails.\n *\n * Kept byte-identical to the strings `createSandboxChatProducer` composes\n * (`src/chat-routes/sandbox-producer.ts`). They are shell vocabulary, not\n * product domain, so recognising them is this package's job — a product on\n * the shared producer gets a correct sweep with no configuration.\n *\n * `tests/turn-health/turn-health.test.ts` pins these against the producer, so\n * changing the producer's wording without changing this list fails CI rather\n * than silently making dead threads look answered.\n */\n/** D1's maximum LIKE pattern length, including the trailing `%`. Measured, not\n * documented: 50 succeeds, 51 raises `SQLITE_ERROR: LIKE or GLOB pattern too\n * complex`. */\nexport const D1_MAX_LIKE_PATTERN_LENGTH = 50\n\nexport const SHELL_ERROR_REPLY_PREFIXES: readonly string[] = [\n 'The sandbox model stream stopped before a clean completion.',\n 'The sandbox agent returned an error before producing a visible answer.',\n \"The assistant's model refused its access key, so this message was not answered.\",\n]\n\n/**\n * Run one sweep and deliver whatever it finds.\n *\n * Errors from the sink are NOT swallowed here (unlike the live lane): a sweep\n * that could not deliver has accomplished nothing, and its cron invocation\n * should go red rather than report a clean run.\n */\nexport async function sweepSilentFailures(options: SweepOptions): Promise<SweepResult> {\n const now = options.now ?? Date.now()\n const minAgeMs = options.minAgeMs ?? 15 * 60_000\n const maxAgeMs = options.maxAgeMs ?? 7 * 24 * HOUR_MS\n const lookbackMs = options.lookbackMs ?? 24 * HOUR_MS\n const limit = options.limit ?? 500\n const emptyRateThreshold = options.emptyRateThreshold ?? 0.05\n const minTurnsForRate = options.minTurnsForRate ?? 10\n const minTurnsForToolSurface = options.minTurnsForToolSurface ?? 10\n // Half the window opaque means the sweep is guessing. Fixed rather than\n // configurable: a product must not be able to tune its own blindness report\n // into silence.\n const blindThreshold = 0.5\n\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, maxAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n const silent = unanswered.filter((t) => !t.notified)\n const notified = unanswered.filter((t) => t.notified)\n const paged = new Set(\n (await (options.pageSilentThreads ?? defaultPageSilentThreads)(silent)).map((t) => t.threadId),\n )\n const describeThread = (t: UnansweredThread) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(t.oldestAgeMs / HOUR_MS).toFixed(1)}h`\n\n if (silent.length > 0) {\n const silentMessages = silent.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldest = silent.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n alerts.push({\n product: options.product,\n severity: paged.size > 0 ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${silentMessages} user message(s) unanswered across ${silent.length} thread(s), with no reply at all`,\n details: [\n `oldest unanswered message: ${(oldest / HOUR_MS).toFixed(1)}h; ${paged.size} of these thread(s) page`,\n // The threads that page come first, so the alert names what to open.\n ...[...silent.filter((t) => paged.has(t.threadId)), ...silent.filter((t) => !paged.has(t.threadId))]\n .slice(0, 5)\n .map((t) => `${describeThread(t)}${paged.has(t.threadId) ? ' (pages)' : ''}`),\n ],\n data: { silentThreads: silent.length, pagedSilentThreads: paged.size, pendingUserMessages: silentMessages, oldestUnansweredMs: oldest },\n at: now,\n })\n }\n if (notified.length > 0 && !options.failureNoticesReportedBy) {\n const notifiedMessages = notified.reduce((sum, t) => sum + t.pendingMessages, 0)\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:failed_threads`,\n title: `${options.product}: ${notifiedMessages} user message(s) across ${notified.length} thread(s) ended on a failure the person saw`,\n details: notified.slice(0, 5).map(describeThread),\n data: { notifiedThreads: notified.length, pendingUserMessages: notifiedMessages },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let rejectedToolCalls = 0\n let unhealthyTurns = 0\n let turnsWithToolCalls = 0\n let toolCalls = 0\n let unreadableTurns = 0\n // Turns whose PARTS were interpretable — the only rows a tool verdict may be\n // drawn from. Distinct from `unreadableTurns`, which is the harder blindness\n // (nothing judgeable at all).\n let toolReadableTurns = 0\n let opaquePartsTurns = 0\n // Rows that persisted NO parts at all. Not opaque (nothing failed to parse)\n // and not evidence either — counted separately so the coverage line can say\n // which of the two blindnesses applies.\n let noPartsTurns = 0\n const opaqueTypes = new Set<string>()\n const malformedSamples: TurnHealthReason[] = []\n const rejectedSamples: TurnHealthReason[] = []\n\n for await (const row of withParts(turns, options.source)) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(await decodeRowParts(options.decodeParts, row)),\n outputTokens: row.outputTokens ?? null,\n })\n toolCalls += verdict.toolCalls\n if (verdict.toolCalls > 0) turnsWithToolCalls += 1\n // A tool verdict needs evidence that was READ. `partsReadable` alone is\n // satisfied vacuously by a row that persisted no parts, which is how a\n // product with 243 real tool calls was paged as having a dead tool surface.\n if (verdict.partsReadable && verdict.interpretedParts > 0) toolReadableTurns += 1\n else if (verdict.partsReadable) noPartsTurns += 1\n else {\n opaquePartsTurns += 1\n for (const t of verdict.opaquePartTypes) opaqueTypes.add(t)\n }\n if (verdict.unreadable) {\n unreadableTurns += 1\n continue\n }\n if (verdict.healthy) continue\n unhealthyTurns += 1\n for (const reason of verdict.reasons) {\n if (reason.kind === 'empty_completion') emptyCompletions += 1\n if (reason.kind === 'malformed_tool_call') {\n malformedToolCalls += 1\n if (malformedSamples.length < 3) malformedSamples.push(reason)\n }\n if (reason.kind === 'tool_call_no_effect') toolCallsWithoutEffect += 1\n if (reason.kind === 'tool_call_rejected') {\n rejectedToolCalls += 1\n if (rejectedSamples.length < 3) rejectedSamples.push(reason)\n }\n }\n }\n\n // Turns this sweep could actually judge. Every rate below divides by THIS,\n // never by the raw row count.\n const readableTurns = turns.length - unreadableTurns\n\n // A malformed tool call is never acceptable at any rate — it means a\n // deliverable was requested and silently discarded. Page on the first one.\n if (malformedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:malformed_tool_call`,\n title: `${options.product}: ${malformedToolCalls} tool call(s) had unparseable arguments — deliverables silently dropped`,\n details: malformedSamples.map(describeReason),\n data: { malformedToolCalls, turnsJudged: turns.length },\n at: now,\n })\n }\n\n // A rejected call means a deliverable was requested and thrown away while the\n // turn reported success. Never acceptable at any rate.\n if (rejectedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:tool_call_rejected`,\n title: `${options.product}: ${rejectedToolCalls} tool call(s) were REJECTED but settled as completed — deliverables silently dropped`,\n details: rejectedSamples.map(describeReason),\n data: { rejectedToolCalls, turnsJudged: readableTurns },\n at: now,\n })\n }\n\n if (readableTurns >= minTurnsForRate) {\n const rate = emptyCompletions / readableTurns\n if (rate > emptyRateThreshold) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:empty_completion_rate`,\n title: `${options.product}: ${(rate * 100).toFixed(1)}% of turns completed with no output`,\n details: [\n `${emptyCompletions} of ${readableTurns} readable settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: readableTurns, rate },\n at: now,\n })\n }\n }\n\n // ── the fourth shape: a tool surface that has gone quiet ───────────────\n //\n // Nothing errors, every turn answers fluently, and the product stops DOING\n // anything. Only visible across a window, which is why it needs its own pass\n // rather than a rule inside the per-turn classifier.\n // Judged ONLY over turns whose parts could be interpreted, and the count of\n // rows that could not is stated in the alert — a verdict that names its own\n // coverage can be trusted; one that hides it cannot.\n if (options.expectsToolCalls && toolReadableTurns >= minTurnsForToolSurface && toolCalls === 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:dead_tool_surface`,\n title: `${options.product}: ZERO tool calls across ${toolReadableTurns} turns — the tool surface is dead`,\n details: [\n `${toolReadableTurns} assistant turns with readable parts in the lookback, none of which called a tool`,\n 'the product declares its deliverable comes from tool calls, so it has answered without doing anything',\n ...(opaquePartsTurns > 0\n ? [`${opaquePartsTurns} further turn(s) had unreadable parts and were not judged`]\n : []),\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} further turn(s) persisted no parts at all and were not judged`]\n : []),\n ],\n data: {\n turnsJudged: toolReadableTurns,\n toolCalls: 0,\n turnsWithToolCalls: 0,\n turnsNotJudged: opaquePartsTurns + noPartsTurns,\n opaquePartsTurns,\n noPartsTurns,\n },\n at: now,\n })\n }\n\n // A product that ASKED for a tool-surface verdict and did not get one must be\n // told that, or the absence of a page reads as a pass. This is the honest\n // form of the alert above: same question, and the answer is \"I could not\n // see\", which is a real finding about the product's observability rather than\n // a fabricated finding about its behaviour.\n if (\n options.expectsToolCalls &&\n toolReadableTurns < minTurnsForToolSurface &&\n opaquePartsTurns + noPartsTurns > 0\n ) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:tool_surface_unmeasurable`,\n title: `${options.product}: tool surface could not be certified — only ${toolReadableTurns} of ${turns.length} turns carried readable parts`,\n details: [\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} turn(s) persisted no parts at all — nothing to read a tool call from`]\n : []),\n ...(opaquePartsTurns > 0\n ? [\n `${opaquePartsTurns} turn(s) stored parts this sweep cannot interpret (${\n [...opaqueTypes].join(', ') || 'unnamed'\n }) — supply \\`decodeParts\\` to make them readable`,\n ]\n : []),\n 'this is NOT a dead tool surface finding; it is the absence of evidence either way',\n ],\n data: {\n toolReadableTurns,\n noPartsTurns,\n opaquePartsTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n // ── the detector reporting on ITSELF ───────────────────────────────────\n //\n // The one verdict this module must never give is \"healthy\" derived from rows\n // it could not read. If most of the window was opaque, that fact is the\n // alert — silence here would be the module committing the exact failure it\n // was built to catch.\n if (opaquePartsTurns > 0 && opaquePartsTurns >= turns.length * blindThreshold) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:detector_blind`,\n title: `${options.product}: ${opaquePartsTurns} of ${turns.length} turns have unreadable parts — this sweep cannot certify them`,\n details: [\n `uninterpretable part types: ${[...opaqueTypes].join(', ') || '(none named)'}`,\n 'these rows are excluded from every verdict above; treat them as UNMEASURED, not healthy',\n ],\n data: {\n opaquePartsTurns,\n unreadableTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n silentThreads: silent.length,\n pagedSilentThreads: paged.size,\n notifiedThreads: notified.length,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n rejectedToolCalls,\n turnsWithToolCalls,\n toolCalls,\n unreadableTurns,\n opaquePartsTurns,\n noPartsTurns,\n toolReadableTurns,\n alerts,\n }\n}\n\n// ── D1 source for the shared chat-store schema ────────────────────────────\n\n/** Minimal structural D1 contract (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForHealth {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\n/**\n * The sweep source for products on the canonical `/chat-store` tables.\n *\n * \"Answered\" deliberately means an assistant row with NON-EMPTY content. A\n * blank assistant row is what a broken turn writes, so counting it as an\n * answer would let the exact failure being hunted mark itself resolved. That\n * single predicate is the difference between this catching the gtm outage and\n * sleeping through it — during those sixteen days the table was NOT empty.\n *\n * The query deliberately does NOT join the thread table. Products do not all\n * keep one: tax-agent's `thread` table holds zero rows because it groups by\n * its own `tax_sessions`, and an inner join against it silently reported \"0\n * unanswered threads, healthy\" while 18 real messages sat unanswered. A\n * detector that reports healthy because its join found nothing is the same\n * bug class it was built to catch.\n */\nexport function createD1TurnHealthSource(\n db: D1LikeForHealth,\n options: {\n messageTable?: string\n threadTable?: string\n /**\n * Content prefixes that mark an assistant row as an ERROR SURFACE rather\n * than an answer. A row matching one of these stops counting as a reply,\n * so the thread keeps reporting as unanswered.\n *\n * This exists because the obvious rule — \"an assistant row with non-empty\n * content is an answer\" — is wrong in the exact case that matters. On\n * 2026-07-27 gtm-agent's newest assistant row read:\n *\n * \"The sandbox model stream stopped before a clean completion.\n * Error: All 2 model(s) failed. gpt-5-mini: TANGLE_HUB_URL is required …\"\n *\n * 246 characters of well-formed prose that answers nothing. Counting it\n * marks a dead product healthy — the same failure-returning-success shape\n * this module exists to catch, recursing into the detector itself.\n *\n * There is no schema-level way to recognise it: `output_tokens IS NULL`\n * looked promising until legal-agent showed 22 of 25 GENUINE replies with\n * null usage — it would have reported a working product broken.\n *\n * Defaults to {@link SHELL_ERROR_REPLY_PREFIXES}, the openers agent-app\n * ITSELF writes in `createSandboxChatProducer`. Those are not domain —\n * this package composed them, so this package is what must recognise\n * them, and every product on the shared producer is correct with no\n * configuration. Pass your own list to ADD product-specific error prose;\n * pass `[]` to disable the rule.\n *\n * Prefixes are bound as query parameters, never interpolated.\n */\n errorReplyPrefixes?: readonly string[]\n /**\n * Read each row's whole `parts` instead of the fields the classifier reads.\n * Only a product whose `decodeParts` needs the stored bytes (an encrypted\n * parts envelope) sets this; the default reads a small projection.\n */\n fullParts?: boolean\n } = {},\n): TurnHealthSource {\n // Table names are identifiers and cannot be bound as parameters. They come\n // from deploy-time product config, never from a request, and are validated\n // here so this can never become an injection point.\n const message = safeIdentifier(options.messageTable ?? 'message')\n const thread = safeIdentifier(options.threadTable ?? 'thread')\n // D1 rejects a LIKE pattern longer than 50 characters with\n // `SQLITE_ERROR: LIKE or GLOB pattern too complex`, and the pattern is the\n // prefix PLUS the trailing `%`. Measured against production D1 on\n // 2026-07-27: a 49-char prefix (50-char pattern) succeeds, 50 fails.\n //\n // Both shipped defaults are longer than that (55 and 70 characters), so\n // before this clamp `findUnansweredThreads` threw on every product database\n // — the detector could not run at all against the only store the fleet uses.\n //\n // Truncating is safe in the one direction that matters: a shorter prefix\n // matches MORE rows as non-answers, so a thread is reported unanswered\n // rather than silently marked healthy. The first 49 characters of each\n // default are still unambiguous.\n const errorPrefixes = [...(options.errorReplyPrefixes ?? SHELL_ERROR_REPLY_PREFIXES)].map((p) =>\n p.slice(0, D1_MAX_LIKE_PATTERN_LENGTH - 1),\n )\n\n return {\n async findUnansweredThreads({ minAgeMs, maxAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const floorSeconds = Math.floor((now - maxAgeMs) / 1000)\n // Each prefix becomes one bound `NOT LIKE ?||'%'` term. Parameters, not\n // interpolation — a product-supplied string never reaches the SQL text.\n const errorClause = errorPrefixes\n .map((_, i) => ` AND a.content NOT LIKE ?${i + 3} || '%'`)\n .join('')\n // A row after the newest pending message that showed something (error\n // prose, or a notice part) means the person saw the failure. A blank row\n // with no notice showed nothing, so its thread stays silent.\n const { results } = await db\n .prepare(\n `WITH pending AS (\n SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt,\n MAX(m.created_at) AS newestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at >= ?2\n AND m.created_at > COALESCE(\n (SELECT MAX(a.created_at)\n FROM ${message} a\n WHERE a.thread_id = m.thread_id\n AND a.role = 'assistant'\n AND length(trim(a.content)) > 0${errorClause}), 0)\n GROUP BY m.thread_id\n )\n SELECT p.threadId, p.pendingMessages, p.oldestCreatedAt,\n EXISTS (\n SELECT 1 FROM ${message} a\n WHERE a.thread_id = p.threadId AND a.role = 'assistant' AND a.created_at >= p.newestCreatedAt\n AND (length(trim(coalesce(a.content, ''))) > 0 OR EXISTS (\n SELECT 1 FROM json_each(CASE WHEN json_valid(a.parts) THEN CASE WHEN json_type(a.parts) = 'array' THEN a.parts ELSE '[]' END ELSE '[]' END) n\n WHERE CASE WHEN n.type = 'object' THEN json_extract(n.value, '$.type') END = 'notice'))\n ) AS notified\n FROM pending p\n ORDER BY p.oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number; notified: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n notified: Number(row.notified) === 1,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, length(parts) AS partsSize,\n output_tokens AS outputTokens, model, created_at AS createdAt\n FROM ${message}\n WHERE role = 'assistant' AND created_at >= ?1\n ORDER BY created_at DESC\n LIMIT ?2`,\n )\n .bind(sinceSeconds, limit)\n .all<Record<string, unknown>>()\n\n return results.map((row) => ({\n id: String(row.id),\n threadId: String(row.threadId),\n content: typeof row.content === 'string' ? row.content : '',\n parts: undefined,\n partsSize: row.partsSize === null ? null : Number(row.partsSize),\n outputTokens: row.outputTokens === null ? null : Number(row.outputTokens),\n model: (row.model as string | null) ?? null,\n createdAt: Number(row.createdAt) * 1000,\n }))\n },\n\n async readParts(ids) {\n if (ids.length === 0) return new Map()\n const placeholders = ids.map((_, i) => `?${i + 1}`).join(', ')\n if (options.fullParts) {\n const { results } = await db\n .prepare(`SELECT id, parts FROM ${message} WHERE id IN (${placeholders})`)\n .bind(...ids)\n .all<{ id: string; parts: unknown }>()\n return new Map(results.map((row) => [String(row.id), row.parts]))\n }\n // One row per part with only what classifyTurnOutcome reads, so a day of\n // tool output never leaves the database: the full read\n // returned 141.9 MB per run for 500 turns.\n const { results } = await db\n .prepare(`SELECT m.id AS id, CAST(p.key AS INTEGER) AS idx, ${PART_PROJECTION}\n FROM ${message} m, json_each(CASE WHEN json_valid(m.parts) THEN CASE WHEN json_type(m.parts) = 'array' THEN m.parts ELSE '[]' END ELSE '[]' END) p\n WHERE m.id IN (${placeholders})\n ORDER BY m.id, idx`)\n .bind(...ids)\n .all<ProjectedPart & { id: string }>()\n const parts = new Map<string, unknown[]>(ids.map((id) => [id, []]))\n for (const row of results) parts.get(String(row.id))?.push(slimPart(row))\n return parts\n },\n }\n\n function safeIdentifier(name: string): string {\n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vC,eAAO,IAAI,IAAIA,SAAQ,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,EAAE,GAAG,IAAI,KAAK,CAAC,CAAC;AAAA,MAClE;AAIA,YAAM,EAAE,QAAQ,IAAI,MAAM,GACvB,QAAQ,qDAAqD,eAAe;AAAA,oBACjE,OAAO;AAAA,6BACE,YAAY;AAAA,+BACV,EACtB,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,YAAM,QAAQ,IAAI,IAAuB,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClE,iBAAW,OAAO,QAAS,OAAM,IAAI,OAAO,IAAI,EAAE,CAAC,GAAG,KAAK,SAAS,GAAG,CAAC;AACxE,aAAO;AAAA,IACT;AAAA,EACF;AAEA,WAAS,eAAe,MAAsB;AAC5C,QAAI,CAAC,2BAA2B,KAAK,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACF;","names":["results"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/draft-persistence.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 * 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'\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 (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\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\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. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the 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 || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= 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: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\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\n ? await Promise.all(\n capped.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : 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 ? safeStringify(values.parts).length : 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\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\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;AAC1D,UAAM,kBAAkB,IAAI,MAAM,iBAAiB,OAAO,SAAS;AACnE,QAAI,OAAO;AACT,YAAM,kBAAkB,IAAI,MAAM,iBAAiB,MAAM,IAAI;AAC7D,YAAM,mBAAmB,IAAI,MAAM,kBAAkB,MAAM,KAAK;AAAA,IAClE;AAAA,EACF;AACA,QAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,MAAI,OAAO,SAAS,IAAI,EAAG,OAAM,kBAAkB,MAAM,kBAAkB,KAAK;AAClF;;;ACkIA,IAAM,sBAA2C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAC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