@tangle-network/agent-app 0.46.36 → 0.46.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +8 -7
  2. package/dist/assets/index.js +18 -0
  3. package/dist/assets/index.js.map +1 -1
  4. package/dist/assets/schema.d.ts +657 -0
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/chat-react/index.js +2 -2
  7. package/dist/chat-routes/index.js +2 -2
  8. package/dist/chat-store/index.js +1 -1
  9. package/dist/{chunk-BDMDL4AB.js → chunk-HJBLT2BW.js} +1 -1
  10. package/dist/chunk-HJBLT2BW.js.map +1 -0
  11. package/dist/{chunk-64EVYEGI.js → chunk-PZOTRGGQ.js} +162 -8
  12. package/dist/chunk-PZOTRGGQ.js.map +1 -0
  13. package/dist/{chunk-7NP744YO.js → chunk-QK4IFP3E.js} +3 -3
  14. package/dist/{chunk-7NP744YO.js.map → chunk-QK4IFP3E.js.map} +1 -1
  15. package/dist/{chunk-EDTWGSQT.js → chunk-SJWIZT7B.js} +6 -2
  16. package/dist/{chunk-EDTWGSQT.js.map → chunk-SJWIZT7B.js.map} +1 -1
  17. package/dist/{chunk-CYSN24KI.js → chunk-U2UAQTFY.js} +2 -2
  18. package/dist/{chunk-4XWVCO7P.js → chunk-Z4TPWP6A.js} +13 -3
  19. package/dist/chunk-Z4TPWP6A.js.map +1 -0
  20. package/dist/{chunk-4SGGSXI7.js → chunk-ZMMIQOFI.js} +6 -5
  21. package/dist/chunk-ZMMIQOFI.js.map +1 -0
  22. package/dist/sandbox/foreground-single-flight.d.ts +62 -0
  23. package/dist/sandbox/index.d.ts +1 -0
  24. package/dist/sandbox/index.js +13 -1
  25. package/dist/sandbox/prewarm-claim-d1.d.ts +15 -8
  26. package/dist/sandbox/prewarm.d.ts +44 -0
  27. package/dist/session-shell/index.js +1 -1
  28. package/dist/signoff/cli.js +1 -1
  29. package/dist/signoff/index.js +1 -1
  30. package/dist/signoff/workflow-pin.d.ts +3 -2
  31. package/dist/stream/index.js +1 -1
  32. package/dist/studio-react/index.js +2 -2
  33. package/dist/trace/index.d.ts +1 -0
  34. package/dist/trace/index.js +240 -0
  35. package/dist/trace/index.js.map +1 -1
  36. package/dist/trace/stage-timing.d.ts +61 -0
  37. package/dist/web-react/index.js +5 -5
  38. package/dist/workspace-react/index.js +1 -1
  39. package/package.json +13 -13
  40. package/dist/chunk-4SGGSXI7.js.map +0 -1
  41. package/dist/chunk-4XWVCO7P.js.map +0 -1
  42. package/dist/chunk-64EVYEGI.js.map +0 -1
  43. package/dist/chunk-BDMDL4AB.js.map +0 -1
  44. /package/dist/{chunk-CYSN24KI.js.map → chunk-U2UAQTFY.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stream/stream-normalizer.ts"],"sourcesContent":["import {\n canTransitionInteractionStatus,\n persistedPartToInteraction,\n type ChatInteractionStatus,\n} from '../interactions/contract'\nimport {\n canTransitionPlanStatus,\n persistedPartToPlan,\n planPartKey,\n planToPersistedPart,\n type ChatPlanStatus,\n} from '../plans/index'\n\n/** Represent a JSON-compatible object with string keys and values of any type */\nexport type JsonRecord = Record<string, unknown>\n\n/** Define an event object carrying a type and optional JSON data payload */\nexport interface StreamEvent {\n type: string\n data?: JsonRecord\n}\n\n/** Resolve an unknown value to a JsonRecord if it is a non-array object or return undefined */\nexport function asRecord(value: unknown): JsonRecord | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as JsonRecord\n : undefined\n}\n\n/** Resolve a non-empty string from a value or return undefined */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/** Resolve a unique tool identifier from various possible properties or generate a fallback ID */\nexport function resolveToolId(part: JsonRecord): string {\n return String(\n part.id ??\n part.callID ??\n part.callId ??\n part.toolUseId ??\n part.toolCallId ??\n part.tool ??\n part.name ??\n `tool-${Date.now()}`,\n )\n}\n\n/** Resolve the tool name from a JSON record using tool, name, or a default value */\nexport function resolveToolName(part: JsonRecord): string {\n return String(part.tool ?? part.name ?? 'tool')\n}\n\n/** Resolve time properties from various keys into a normalized record with numeric start and end fields */\nexport function normalizeTime(value: unknown): JsonRecord | undefined {\n const record = asRecord(value)\n if (!record) return undefined\n\n const start = Number(record.start ?? record.startedAt ?? record.started_at)\n const end = Number(record.end ?? record.completedAt ?? record.completed_at)\n if (!Number.isFinite(start) && !Number.isFinite(end)) return undefined\n\n return {\n start: Number.isFinite(start) ? start : undefined,\n end: Number.isFinite(end) ? end : undefined,\n }\n}\n\n// Sandbox uses `exitCode`; OpenCode's structured shell output uses `exit`.\n// Keep this explicit so stderr alone never turns a successful command into an error.\nconst TOOL_EXIT_KEYS = ['exitCode', 'exit'] as const\n\nfunction toolExitCode(...values: unknown[]): number | undefined {\n for (const value of values) {\n const record = asRecord(value)\n if (!record) continue\n for (const key of TOOL_EXIT_KEYS) {\n const exitCode = record[key]\n if (typeof exitCode === 'number' && Number.isInteger(exitCode)) return exitCode\n }\n }\n return undefined\n}\n\nfunction toolExitError(output: unknown, exitCode: number | undefined): string | undefined {\n if (exitCode === undefined || exitCode === 0) return undefined\n return asString(asRecord(output)?.stderr) ?? `Command exited with code ${exitCode}.`\n}\n\n/** Normalize tool-related events into a standardized message.part.updated format */\nexport function normalizeToolEvent(event: StreamEvent): StreamEvent {\n if (event.type === 'tool_call' || event.type === 'tool.call') {\n const data = event.data ?? {}\n return {\n type: 'message.part.updated',\n data: {\n part: {\n type: 'tool',\n id: data.id ?? data.callId ?? data.callID ?? data.name,\n tool: data.name ?? data.tool ?? 'tool',\n input: data.arguments ?? data.input,\n status: 'running',\n },\n },\n }\n }\n\n if (event.type === 'tool_result' || event.type === 'tool.result') {\n const data = event.data ?? {}\n const state = asRecord(data.state)\n const output = data.output\n const exitCode = toolExitCode(output, data, data.metadata, state, state?.metadata)\n const error = asString(data.error ?? state?.error) ?? toolExitError(output, exitCode)\n const terminalError =\n data.status === 'error' ||\n data.status === 'failed' ||\n state?.status === 'error' ||\n state?.status === 'failed' ||\n Boolean(error) ||\n (exitCode !== undefined && exitCode !== 0)\n return {\n type: 'message.part.updated',\n data: {\n part: {\n type: 'tool',\n id: data.id ?? data.callId ?? data.callID ?? data.name,\n tool: data.name ?? data.tool ?? 'tool',\n output,\n error,\n status: terminalError ? 'error' : 'completed',\n },\n },\n }\n }\n\n return event\n}\n\n/** Normalize a persisted part object by standardizing its structure and fields */\nexport function normalizePersistedPart(rawPart: JsonRecord): JsonRecord | null {\n const type = String(rawPart.type ?? '')\n\n if (type === 'text') {\n const id = asString(rawPart.id) ?? asString(rawPart.partId)\n return {\n type: 'text',\n text: asString(rawPart.text) ?? asString(rawPart.content) ?? '',\n // id: per-segment identity from the harness; absent on legacy parts,\n // which collapse to a single keyed segment. Never invented here.\n ...(id ? { id } : {}),\n }\n }\n\n if (type === 'reasoning') {\n const id = asString(rawPart.id) ?? asString(rawPart.partId)\n return {\n type: 'reasoning',\n text: asString(rawPart.text) ?? asString(rawPart.content) ?? '',\n time: normalizeTime(rawPart.time),\n ...(id ? { id } : {}),\n }\n }\n\n if (type === 'file' || type === 'image') {\n const id = asString(rawPart.id) ?? asString(rawPart.partId)\n return {\n type,\n ...(id ? { id } : {}),\n ...(asString(rawPart.filename) ? { filename: asString(rawPart.filename) } : {}),\n // `name`: the durable attachment display name `promoteAgentFilePart`\n // writes. Coexists with `filename` (legacy raw-harness shape) — kept\n // separate rather than unified so neither producer's shape is lossy.\n ...(asString(rawPart.name) ? { name: asString(rawPart.name) } : {}),\n ...(asString(rawPart.mediaType) ? { mediaType: asString(rawPart.mediaType) } : {}),\n ...(asString(rawPart.url) ? { url: asString(rawPart.url) } : {}),\n ...(asString(rawPart.path) ? { path: asString(rawPart.path) } : {}),\n ...(type === 'file' && asString(rawPart.content) ? { content: asString(rawPart.content) } : {}),\n ...(typeof rawPart.size === 'number' && Number.isFinite(rawPart.size) ? { size: rawPart.size } : {}),\n }\n }\n\n if (type === 'step-start') {\n return { type: 'step-start' }\n }\n\n // The harness's per-step usage receipt. Dropping it here silently loses the\n // turn's token/cost accounting from the persisted transcript.\n if (type === 'step-finish') {\n const tokens = asRecord(rawPart.tokens)\n const cost = Number(rawPart.cost)\n return {\n type: 'step-finish',\n ...(asString(rawPart.reason) ? { reason: asString(rawPart.reason) } : {}),\n ...(tokens ? { tokens } : {}),\n ...(Number.isFinite(cost) ? { cost } : {}),\n }\n }\n\n if (type === 'subtask') {\n const id = asString(rawPart.id) ?? asString(rawPart.partId)\n return {\n type: 'subtask',\n prompt: asString(rawPart.prompt) ?? '',\n description: asString(rawPart.description) ?? '',\n agent: asString(rawPart.agent) ?? '',\n ...(id ? { id } : {}),\n }\n }\n\n if (type === 'interaction') {\n return persistedPartToInteraction(rawPart) ? rawPart : null\n }\n\n if (type === 'plan') {\n const plan = persistedPartToPlan(rawPart)\n return plan ? { ...rawPart, ...planToPersistedPart(plan) } : null\n }\n\n // System-authored notices pass through verbatim; `/chat-store` owns their\n // final typed validation before persistence.\n if (type === 'notice') {\n return rawPart\n }\n\n if (type === 'tool') {\n const state = asRecord(rawPart.state)\n const output = state?.output ?? rawPart.output\n const exitCode = toolExitCode(output, state, state?.metadata, rawPart, rawPart.metadata)\n const error = asString(state?.error ?? rawPart.error) ?? toolExitError(output, exitCode)\n const terminalError =\n state?.status === 'error' ||\n state?.status === 'failed' ||\n rawPart.status === 'error' ||\n rawPart.status === 'failed' ||\n Boolean(error) ||\n (exitCode !== undefined && exitCode !== 0)\n const status =\n terminalError\n ? 'error'\n : state?.status === 'completed' || rawPart.status === 'completed'\n ? 'completed'\n : output !== undefined\n ? 'completed'\n : 'running'\n\n return {\n type: 'tool',\n id: resolveToolId(rawPart),\n tool: resolveToolName(rawPart),\n callID:\n rawPart.callID != null || rawPart.callId != null\n ? String(rawPart.callID ?? rawPart.callId)\n : undefined,\n state: {\n status,\n input: state?.input ?? rawPart.input,\n output,\n error,\n metadata: asRecord(state?.metadata) ?? asRecord(rawPart.metadata),\n time: normalizeTime(state?.time ?? rawPart.time),\n },\n }\n }\n\n return null\n}\n\n/** Stream/transcript part key for a promoted (path-bearing) attachment,\n * keyed on its storage path — re-emitting the same path folds into the same\n * segment instead of duplicating it. */\nexport function attachmentPartKey(path: string): string {\n return `attachment:${path}`\n}\n\n/** Resolve a unique key string for a part based on its type and identifying properties */\nexport function getPartKey(part: JsonRecord): string {\n const type = String(part.type ?? 'unknown')\n if (type === 'tool') {\n return `tool:${resolveToolId(part)}`\n }\n if (type === 'plan') return planPartKey(String(part.planId ?? ''))\n if ((type === 'file' || type === 'image') && asString(part.path)) {\n return attachmentPartKey(String(part.path))\n }\n\n // Keyed by the part's OWN type so distinct kinds never merge into each\n // other. Untyped parts fall back to the text lane (legacy shape).\n const lane = type && type !== 'unknown' ? type : 'text'\n return `${lane}:${String(part.id ?? part.partId ?? part.index ?? 'current')}`\n}\n\n/** Shallow overlay that skips `undefined` incoming values, so a later partial\n * update never erases a field an earlier one captured. */\nfunction overlayDefined(base: JsonRecord, patch: JsonRecord): JsonRecord {\n const out: JsonRecord = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\n/** Merge incoming JSON with existing persisted data, applying delta for text types when provided */\nexport function mergePersistedPart(existing: JsonRecord | undefined, incoming: JsonRecord, delta?: string): JsonRecord {\n const type = String(incoming.type ?? '')\n if (!existing) {\n if (type === 'text' && delta) {\n return { type: 'text', text: delta }\n }\n return incoming\n }\n\n if (type === 'text' && String(existing.type ?? '') === 'text') {\n const existingText = String(existing.text ?? '')\n const incomingText = String(incoming.text ?? '')\n return {\n ...existing,\n ...incoming,\n // An empty snapshot never erases accumulated text (matches reasoning).\n text: delta ? `${existingText}${delta}` : incomingText || existingText,\n }\n }\n\n if (type === 'reasoning' && String(existing.type ?? '') === 'reasoning') {\n const existingText = String(existing.text ?? '')\n const incomingText = String(incoming.text ?? '')\n return {\n ...existing,\n ...incoming,\n text: delta && incomingText === existingText ? `${existingText}${delta}` : incomingText || existingText,\n time: incoming.time ?? existing.time,\n }\n }\n\n if (type === 'tool' && String(existing.type ?? '') === 'tool') {\n const existingState = asRecord(existing.state) ?? {}\n const incomingState = asRecord(incoming.state) ?? {}\n // Overlay only DEFINED incoming fields: a normalized tool part always\n // carries `output`/`error` keys (undefined when not captured), so a plain\n // spread would clobber a completed tool's output with a later empty update.\n const mergedState = overlayDefined(existingState, incomingState)\n // A partial update with no captured status/output/error normalizes to\n // `running`; never let it downgrade a tool that already settled.\n const existingStatus = String(existingState.status ?? '')\n if (\n (existingStatus === 'completed' || existingStatus === 'error') &&\n String(incomingState.status ?? '') === 'running'\n ) {\n mergedState.status = existingStatus\n }\n return {\n ...overlayDefined(existing, incoming),\n state: mergedState,\n }\n }\n\n if (type === 'interaction' && String(existing.type ?? '') === 'interaction') {\n const merged = overlayDefined(existing, incoming)\n const existingStatus = existing.status as ChatInteractionStatus | undefined\n const incomingStatus = incoming.status as ChatInteractionStatus | undefined\n if (\n existingStatus &&\n incomingStatus &&\n existingStatus !== incomingStatus &&\n !canTransitionInteractionStatus(existingStatus, incomingStatus)\n ) {\n merged.status = existingStatus\n }\n if (incoming.answers === undefined && existing.answers !== undefined) {\n merged.answers = existing.answers\n }\n return merged\n }\n\n if (type === 'plan' && String(existing.type ?? '') === 'plan') {\n const existingRevision = Number(existing.revision)\n const incomingRevision = Number(incoming.revision)\n if (Number.isInteger(existingRevision) && Number.isInteger(incomingRevision)) {\n if (incomingRevision < existingRevision) return existing\n if (incomingRevision > existingRevision) return incoming\n }\n const merged = overlayDefined(existing, incoming)\n const existingStatus = existing.status as ChatPlanStatus | undefined\n const incomingStatus = incoming.status as ChatPlanStatus | undefined\n if (\n existingStatus &&\n incomingStatus &&\n existingStatus !== incomingStatus &&\n !canTransitionPlanStatus(existingStatus, incomingStatus)\n ) {\n merged.status = existingStatus\n }\n return merged\n }\n\n return incoming\n}\n\n/** Resolve errors when a tool fails to report a terminal result before the assistant turn ends */\nexport const MISSING_TOOL_TERMINAL_ERROR = 'Tool did not report a terminal result before the assistant turn completed.'\n/** Provide the reason identifier for a missing tool in the terminal environment */\nexport const MISSING_TOOL_TERMINAL_REASON = 'missing-tool-terminal'\n\n/** Closes a tool part left `running` when a stream ended abnormally: settles\n * it as a terminal `error` and stamps `state.metadata.terminalized` so the\n * synthetic settlement is distinguishable from a real tool failure. Parts\n * that already settled (and non-tool parts) pass through untouched. */\nexport function terminalizeDanglingToolPart(part: JsonRecord): JsonRecord {\n if (String(part.type ?? '') !== 'tool') return part\n\n const state = asRecord(part.state) ?? {}\n if (String(state.status ?? part.status ?? '') !== 'running') return part\n\n const metadata = asRecord(state.metadata) ?? {}\n return {\n ...part,\n state: {\n ...state,\n status: 'error',\n error: asString(state.error ?? part.error) ?? MISSING_TOOL_TERMINAL_ERROR,\n metadata: {\n ...metadata,\n terminalized: true,\n terminalReason: MISSING_TOOL_TERMINAL_REASON,\n },\n },\n }\n}\n\n/** Resolve dangling tool parts into terminal forms within the given JSON records array */\nexport function terminalizeDanglingToolParts(parts: JsonRecord[]): JsonRecord[] {\n return parts.map(terminalizeDanglingToolPart)\n}\n\n/** Settles still-pending interaction parts at persist time. The broker\n * guarantees a resolved question either answered (run unblocked, no cancel\n * event) or cancelled/timed out (cancel event already updated the part), so\n * the success path finalizes remaining pendings as `answered` and the\n * failure/terminalize paths as `expired`. */\nexport function finalizePendingInteractionParts(\n parts: JsonRecord[],\n outcome: Extract<ChatInteractionStatus, 'answered' | 'expired'>,\n): JsonRecord[] {\n return parts.map((part) => {\n if (String(part.type ?? '') !== 'interaction') return part\n if (String(part.status ?? '') !== 'pending') return part\n return { ...part, status: outcome }\n })\n}\n\n/** Collapses text-part artifacts of unstable upstream segment identity: the\n * same text arriving under two keys (id-less delta stream, then an\n * id-bearing snapshot) folds into two segments, and interleaved empty\n * segments survive as blank parts. Consecutive identical text parts merge\n * into one; empty text parts drop when any non-empty text part exists. */\nexport function collapseRedundantTextParts(parts: JsonRecord[]): JsonRecord[] {\n const hasNonEmptyText = parts.some(\n (part) => String(part.type ?? '') === 'text' && String(part.text ?? '').trim().length > 0,\n )\n const collapsed: JsonRecord[] = []\n for (const part of parts) {\n if (String(part.type ?? '') !== 'text') {\n collapsed.push(part)\n continue\n }\n const text = String(part.text ?? '')\n if (hasNonEmptyText && text.trim().length === 0) continue\n const previous = collapsed[collapsed.length - 1]\n if (previous && String(previous.type ?? '') === 'text' && String(previous.text ?? '') === text) continue\n collapsed.push(part)\n }\n return collapsed\n}\n\nfunction assembleAssistantParts(\n partOrder: string[],\n partMap: Map<string, JsonRecord>,\n finalText: string,\n): JsonRecord[] {\n const parts = partOrder\n .map((key) => partMap.get(key))\n .filter((part): part is JsonRecord => Boolean(part))\n\n const textParts = parts.filter((part) => String(part.type ?? '') === 'text')\n\n if (textParts.length === 0) {\n if (finalText.trim()) {\n parts.push({ type: 'text', text: finalText })\n }\n return parts\n }\n\n // Id-less text parts form a single logical stream — the final text is\n // authoritative for it.\n if (!textParts.some((part) => asString(part.id))) {\n return parts.map((part) => {\n if (String(part.type ?? '') !== 'text') return part\n return {\n ...part,\n text: finalText || String(part.text ?? ''),\n }\n })\n }\n\n // Per-id text segments: invariant is concat(text parts) === persisted final\n // text, so segment boundaries survive without duplicating the answer into\n // every segment.\n const joined = textParts.map((part) => String(part.text ?? '')).join('')\n if (finalText === joined || finalText.trimEnd() === joined.trimEnd()) {\n return parts\n }\n\n if (finalText.startsWith(joined)) {\n // Final text extends the streamed segments (e.g. a failure diagnostic\n // appended after the stream) — persist the remainder as a trailing\n // id-less segment.\n return [...parts, { type: 'text', text: finalText.slice(joined.length) }]\n }\n\n // Final text replaced the streamed text outright. Keep non-text chronology;\n // collapse text to one authoritative segment at the last text position.\n const lastTextPart = textParts[textParts.length - 1]\n return parts\n .filter((part) => String(part.type ?? '') !== 'text' || part === lastTextPart)\n .map((part) => (part === lastTextPart ? { ...part, text: finalText } : part))\n}\n\n/** Resolve and clean up assistant parts by terminalizing and collapsing redundant segments */\nexport function finalizeAssistantParts(\n partOrder: string[],\n partMap: Map<string, JsonRecord>,\n finalText: string,\n): JsonRecord[] {\n // A stream that ended abnormally can leave tool parts `running` — never\n // persist one; collapsing then removes the duplicate/blank text segments an\n // unstable upstream segment identity produced.\n return collapseRedundantTextParts(terminalizeDanglingToolParts(\n assembleAssistantParts(partOrder, partMap, finalText),\n ))\n}\n\n/** The MID-STREAM twin of {@link finalizeAssistantParts}: the same assembled,\n * collapsed projection MINUS the dangling-tool terminalizer.\n *\n * Incremental persistence snapshots the assistant body while the turn is\n * still running, and mid-stream a tool part sitting at `state.status:\n * 'running'` is the NORMAL in-flight state — not the abnormal end\n * {@link terminalizeDanglingToolPart} exists to settle. Running a live\n * snapshot through `finalizeAssistantParts` would persist every in-flight\n * tool call as a failure (`state.status:'error'`, `metadata.terminalized`),\n * so a reader of the durable row would see phantom tool errors that the final\n * write then silently un-does. Terminalization stays a completion-time\n * decision: the final write is the only writer allowed to settle a tool part.\n *\n * Pending `interaction` parts are likewise left `pending` here (the caller\n * skips {@link finalizePendingInteractionParts}) — an ask is genuinely\n * unanswered until the turn settles. */\nexport function draftAssistantParts(\n partOrder: string[],\n partMap: Map<string, JsonRecord>,\n finalText: string,\n): JsonRecord[] {\n return collapseRedundantTextParts(assembleAssistantParts(partOrder, partMap, finalText))\n}\n\nfunction partStatus(part: JsonRecord | undefined): string {\n const state = asRecord(part?.state)\n return String(state?.status ?? part?.status ?? '')\n}\n\n/** Finalizes, then folds each synthetic tool settlement back into `partMap`\n * and returns just those updates — the shape a streaming loop needs to emit\n * closing `message.part.updated` frames for tools the stream never settled. */\nexport function terminalizeDanglingAssistantToolUpdates(\n partOrder: string[],\n partMap: Map<string, JsonRecord>,\n finalText: string,\n): JsonRecord[] {\n const finalizedParts = finalizeAssistantParts(partOrder, partMap, finalText)\n const updates: JsonRecord[] = []\n\n for (const part of finalizedParts) {\n if (String(part.type ?? '') !== 'tool') continue\n\n const key = getPartKey(part)\n const existing = partMap.get(key)\n if (partStatus(existing) !== 'running' || partStatus(part) === 'running') continue\n\n partMap.set(key, mergePersistedPart(existing, part))\n updates.push(part)\n }\n\n return updates\n}\n\n/** Encode a StreamEvent object into a Uint8Array using the provided TextEncoder */\nexport function encodeEvent(encoder: TextEncoder, event: StreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n"],"mappings":";;;;;;;;;;;;AAuBO,SAAS,SAAS,OAAwC;AAC/D,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAC7D,QACA;AACN;AAGO,SAAS,SAAS,OAAoC;AAC3D,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAGO,SAAS,cAAc,MAA0B;AACtD,SAAO;AAAA,IACL,KAAK,MACH,KAAK,UACL,KAAK,UACL,KAAK,aACL,KAAK,cACL,KAAK,QACL,KAAK,QACL,QAAQ,KAAK,IAAI,CAAC;AAAA,EACtB;AACF;AAGO,SAAS,gBAAgB,MAA0B;AACxD,SAAO,OAAO,KAAK,QAAQ,KAAK,QAAQ,MAAM;AAChD;AAGO,SAAS,cAAc,OAAwC;AACpE,QAAM,SAAS,SAAS,KAAK;AAC7B,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,QAAQ,OAAO,OAAO,SAAS,OAAO,aAAa,OAAO,UAAU;AAC1E,QAAM,MAAM,OAAO,OAAO,OAAO,OAAO,eAAe,OAAO,YAAY;AAC1E,MAAI,CAAC,OAAO,SAAS,KAAK,KAAK,CAAC,OAAO,SAAS,GAAG,EAAG,QAAO;AAE7D,SAAO;AAAA,IACL,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,IACxC,KAAK,OAAO,SAAS,GAAG,IAAI,MAAM;AAAA,EACpC;AACF;AAIA,IAAM,iBAAiB,CAAC,YAAY,MAAM;AAE1C,SAAS,gBAAgB,QAAuC;AAC9D,aAAW,SAAS,QAAQ;AAC1B,UAAM,SAAS,SAAS,KAAK;AAC7B,QAAI,C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AmB,UAAU,IAAI,CAAC;AACnD,YAAQ,KAAK,IAAI;AAAA,EACnB;AAEA,SAAO;AACT;AAGO,SAAS,YAAY,SAAsB,OAAgC;AAChF,SAAO,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,CAAI;AACpD;","names":[]}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Serialize request-time sandbox provisioning across Worker isolates.
3
+ *
4
+ * Background prewarming can lose a race without delaying a request. A real
5
+ * user turn cannot: its losing request must wait for the owner, adopt the box
6
+ * that became ready, or report why the owner did not leave a usable box.
7
+ */
8
+ import type { Harness } from '../harness/index';
9
+ import type { PeekWorkspaceSandboxOutcome } from './index';
10
+ import { type FencedPrewarmClaimStore } from './prewarm';
11
+ export declare const DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS = 180;
12
+ export declare const DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS = 5000;
13
+ export type ReadyRunningSandboxOutcome = Extract<PeekWorkspaceSandboxOutcome, {
14
+ status: 'running';
15
+ }> & {
16
+ box: Extract<PeekWorkspaceSandboxOutcome, {
17
+ status: 'running';
18
+ }>['box'] & {
19
+ filesystemIncarnationReadiness: 'ready';
20
+ };
21
+ };
22
+ export declare class SandboxProvisioningFailedElsewhereError extends Error {
23
+ readonly workspaceId: string;
24
+ readonly state: string;
25
+ readonly code = "sandbox.provisioning_failed_elsewhere";
26
+ constructor(workspaceId: string, state: string);
27
+ }
28
+ export declare class SandboxFilesystemNotReadyError extends Error {
29
+ readonly workspaceId: string;
30
+ readonly readiness: 'transitioning' | 'missing';
31
+ readonly code = "sandbox.filesystem_not_ready";
32
+ readonly retryable = true;
33
+ constructor(workspaceId: string, readiness: 'transitioning' | 'missing');
34
+ }
35
+ export type ForegroundSandboxSingleFlightEvent = {
36
+ type: 'waiting';
37
+ key: string;
38
+ workspaceId: string;
39
+ } | {
40
+ type: 'release-failed';
41
+ key: string;
42
+ workspaceId: string;
43
+ error: string;
44
+ };
45
+ export interface ForegroundSandboxSingleFlightOptions<T> {
46
+ claim: FencedPrewarmClaimStore;
47
+ workspaceId: string;
48
+ harness: Harness;
49
+ provision(): Promise<T>;
50
+ peek(): Promise<PeekWorkspaceSandboxOutcome>;
51
+ adopt(box: ReadyRunningSandboxOutcome): T | Promise<T>;
52
+ onEvent?(event: ForegroundSandboxSingleFlightEvent): void;
53
+ wait?(ms: number): Promise<void>;
54
+ claimTtlSeconds?: number;
55
+ pollIntervalMs?: number;
56
+ }
57
+ /**
58
+ * Run one foreground provision or adopt the ready result from its current
59
+ * owner. An expired retained claim permits takeover. A released claim without
60
+ * a usable box reports the prior attempt instead of starting a retry storm.
61
+ */
62
+ export declare function runForegroundSandboxSingleFlight<T>(options: ForegroundSandboxSingleFlightOptions<T>): Promise<T>;
@@ -782,3 +782,4 @@ export * from './workspace-sandbox-manager';
782
782
  export * from './terminal-connection';
783
783
  export * from './prewarm';
784
784
  export * from './prewarm-claim-d1';
785
+ export * from './foreground-single-flight';
@@ -1,4 +1,6 @@
1
1
  import {
2
+ DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
3
+ DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
2
4
  DEFAULT_PREWARM_CLAIM_TABLE,
3
5
  DEFAULT_PROVISION_TIMEOUT_MS,
4
6
  DEFAULT_SANDBOX_RESOURCES,
@@ -12,7 +14,9 @@ import {
12
14
  PYPI_EGRESS_DOMAINS,
13
15
  SANDBOX_BACKING_CONTAINER_MISSING_CODE,
14
16
  SandboxEgressPolicyMismatchError,
17
+ SandboxFilesystemNotReadyError,
15
18
  SandboxModelResolutionError,
19
+ SandboxProvisioningFailedElsewhereError,
16
20
  SandboxRecoveryFailedError,
17
21
  SandboxRuntimeAuthRefreshError,
18
22
  WORKSPACE_SANDBOX_HOST_EXHAUSTED,
@@ -71,8 +75,10 @@ import {
71
75
  resolveModel,
72
76
  resolveModelSelection,
73
77
  resolveSandboxClientCredentials,
78
+ runForegroundSandboxSingleFlight,
74
79
  runSandboxPrompt,
75
80
  runSandboxToolPathSetup,
81
+ sandboxPrewarmClaimKey,
76
82
  sandboxToolBinDir,
77
83
  sandboxToolPath,
78
84
  sandboxToolRootDir,
@@ -92,7 +98,7 @@ import {
92
98
  workspaceSandboxRecoveryMessage,
93
99
  workspaceSandboxRecoveryRecommendedActions,
94
100
  writeProfileFilesToBox
95
- } from "../chunk-64EVYEGI.js";
101
+ } from "../chunk-PZOTRGGQ.js";
96
102
  import "../chunk-TH7L265V.js";
97
103
  import "../chunk-LWSJK546.js";
98
104
  import "../chunk-P5PIAQVS.js";
@@ -102,6 +108,8 @@ import "../chunk-UGWQLQDS.js";
102
108
  import "../chunk-S5SRJJQG.js";
103
109
  import "../chunk-JML7WKWU.js";
104
110
  export {
111
+ DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
112
+ DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
105
113
  DEFAULT_PREWARM_CLAIM_TABLE,
106
114
  DEFAULT_PROVISION_TIMEOUT_MS,
107
115
  DEFAULT_SANDBOX_RESOURCES,
@@ -115,7 +123,9 @@ export {
115
123
  PYPI_EGRESS_DOMAINS,
116
124
  SANDBOX_BACKING_CONTAINER_MISSING_CODE,
117
125
  SandboxEgressPolicyMismatchError,
126
+ SandboxFilesystemNotReadyError,
118
127
  SandboxModelResolutionError,
128
+ SandboxProvisioningFailedElsewhereError,
119
129
  SandboxRecoveryFailedError,
120
130
  SandboxRuntimeAuthRefreshError,
121
131
  WORKSPACE_SANDBOX_HOST_EXHAUSTED,
@@ -174,8 +184,10 @@ export {
174
184
  resolveModel,
175
185
  resolveModelSelection,
176
186
  resolveSandboxClientCredentials,
187
+ runForegroundSandboxSingleFlight,
177
188
  runSandboxPrompt,
178
189
  runSandboxToolPathSetup,
190
+ sandboxPrewarmClaimKey,
179
191
  sandboxToolBinDir,
180
192
  sandboxToolPath,
181
193
  sandboxToolRootDir,
@@ -1,3 +1,4 @@
1
+ import type { FencedPrewarmClaimStore } from './prewarm';
1
2
  /**
2
3
  * `createD1PrewarmClaimStore` — the cross-isolate half of
3
4
  * `createSandboxPrewarmer`'s single-flight, implemented once.
@@ -27,6 +28,15 @@
27
28
  * reporting `changes: 0` is a SQLite detail, whereas "no row came back" is the
28
29
  * statement telling you directly.
29
30
  *
31
+ * Foreground provisioning uses `acquireLease`/`releaseLease`. The lease's
32
+ * returned `expiresAt` is a fencing value: takeover writes a value strictly
33
+ * greater than the expired value, and release changes only the matching value
34
+ * into a signed tombstone. A later acquire advances the absolute value, so a
35
+ * stale release cannot collide even after a same-clock release and reacquire.
36
+ * `inspect` hides the tombstone as `absent`. This uses the published two-column
37
+ * table without changing the legacy `PrewarmClaimStore` methods or requiring a
38
+ * migration.
39
+ *
30
40
  * ── STRUCTURAL, NOT A DEPENDENCY ───────────────────────────────────────────
31
41
  * The binding is taken as the narrow shape actually used (`prepare().bind()`,
32
42
  * `.first()`, `.run()`), per the package's structural-over-hard-dep rule. No
@@ -60,11 +70,12 @@ export interface D1PrewarmClaimStoreOptions {
60
70
  now?(): number;
61
71
  }
62
72
  export declare const DEFAULT_PREWARM_CLAIM_TABLE = "sandbox_prewarm_claims";
63
- /** Paste into a migration. `expires_at` is epoch MILLISECONDS, matching
64
- * `Date.now()`, so no unit conversion sits between the lease and its clock. */
73
+ /** Paste into a migration. Positive `expires_at` values are epoch MILLISECONDS,
74
+ * matching `Date.now()`. A released fenced claim keeps a negative tombstone so
75
+ * a later lease can advance its fencing value without adding a column. */
65
76
  export declare const PREWARM_CLAIM_TABLE_DDL = "CREATE TABLE IF NOT EXISTS sandbox_prewarm_claims (\n key TEXT PRIMARY KEY,\n expires_at INTEGER NOT NULL\n)";
66
77
  /**
67
- * A `PrewarmClaimStore` backed by one D1 table.
78
+ * A fenced `PrewarmClaimStore` backed by one D1 table.
68
79
  *
69
80
  * ```ts
70
81
  * const prewarmer = createSandboxPrewarmer(shell, {
@@ -73,8 +84,4 @@ export declare const PREWARM_CLAIM_TABLE_DDL = "CREATE TABLE IF NOT EXISTS sandb
73
84
  * })
74
85
  * ```
75
86
  */
76
- export declare function createD1PrewarmClaimStore(db: PrewarmClaimD1Like, options?: D1PrewarmClaimStoreOptions): {
77
- acquire(key: string, ttlSeconds: number): Promise<boolean>;
78
- release(key: string): Promise<void>;
79
- isHeld(key: string): Promise<boolean>;
80
- };
87
+ export declare function createD1PrewarmClaimStore(db: PrewarmClaimD1Like, options?: D1PrewarmClaimStoreOptions): FencedPrewarmClaimStore;
@@ -103,6 +103,47 @@ export interface PrewarmClaimStore {
103
103
  * that started it, and every other one reports `absent`. */
104
104
  isHeld?(key: string): Promise<boolean>;
105
105
  }
106
+ /**
107
+ * The ownership proof for one foreground provisioning attempt.
108
+ *
109
+ * `expiresAt` is both the lease deadline and its fencing value. The D1 store
110
+ * advances it when a takeover succeeds, so an expired owner cannot release a
111
+ * successor's lease. Keep this object and pass it back unchanged to
112
+ * `FencedPrewarmClaimStore.releaseLease`.
113
+ */
114
+ export interface PrewarmClaimLease {
115
+ readonly key: string;
116
+ readonly expiresAt: number;
117
+ }
118
+ /** State needed by a foreground caller that waits for another isolate. */
119
+ export type PrewarmClaimState = {
120
+ status: 'held';
121
+ expiresAt: number;
122
+ } | {
123
+ status: 'expired';
124
+ expiresAt: number;
125
+ } | {
126
+ status: 'absent';
127
+ };
128
+ /** A claim store that can distinguish a completed owner from a crashed owner. */
129
+ export interface InspectablePrewarmClaimStore extends PrewarmClaimStore {
130
+ isHeld(key: string): Promise<boolean>;
131
+ inspect(key: string): Promise<PrewarmClaimState>;
132
+ }
133
+ /**
134
+ * Fenced claim operations for foreground provisioning.
135
+ *
136
+ * This is separate from `PrewarmClaimStore` so the published boolean
137
+ * `acquire` and key-only `release` methods remain source-compatible. A
138
+ * foreground caller must use the lease returned here and release that lease,
139
+ * not the legacy key-only method.
140
+ */
141
+ export interface FencedPrewarmClaimStore extends InspectablePrewarmClaimStore {
142
+ /** Atomically acquire a lease or return null when another live lease wins. */
143
+ acquireLease(key: string, ttlSeconds: number): Promise<PrewarmClaimLease | null>;
144
+ /** Conditionally release only this lease. A stale lease is a no-op. */
145
+ releaseLease(lease: PrewarmClaimLease): Promise<void>;
146
+ }
106
147
  /** What `prewarm()` decided. Every value except `started` means no box was
107
148
  * created and nothing was spent on this call. */
108
149
  export type PrewarmOutcome = 'started' | 'already-running' | 'already-warming' | 'warming-elsewhere' | 'declined-by-policy' | 'cooling-down' | 'absent-and-resume-only';
@@ -190,4 +231,7 @@ export interface SandboxPrewarmer {
190
231
  /** Clear a recorded failure so the next `prewarm` retries immediately. */
191
232
  clearFailure(scope: SandboxPrewarmScope): void;
192
233
  }
234
+ /** Identity of a warm. Harness is part of it because `ensureWorkspaceSandbox`
235
+ * destroys and rebuilds a box whose harness does not match. */
236
+ export declare function sandboxPrewarmClaimKey(scope: Pick<SandboxPrewarmScope, 'workspaceId' | 'harness'>): string;
193
237
  export declare function createSandboxPrewarmer(shell: SandboxRuntimeConfig, options: SandboxPrewarmerOptions): SandboxPrewarmer;
@@ -24,7 +24,7 @@ import {
24
24
  scoreCommandPaletteItem,
25
25
  sessionLabel,
26
26
  writeRailCollapsedCookie
27
- } from "../chunk-EDTWGSQT.js";
27
+ } from "../chunk-SJWIZT7B.js";
28
28
  export {
29
29
  COMMAND_PALETTE_ACTIONS_GROUP,
30
30
  COMMAND_PALETTE_SESSIONS_GROUP,
@@ -3,7 +3,7 @@ import {
3
3
  formatSignoffLine,
4
4
  formatSignoffReport,
5
5
  runSignoff
6
- } from "../chunk-BDMDL4AB.js";
6
+ } from "../chunk-HJBLT2BW.js";
7
7
  import {
8
8
  invokedAsScript
9
9
  } from "../chunk-C3CAYGGQ.js";
@@ -2,7 +2,7 @@ import {
2
2
  formatSignoffReport,
3
3
  loadSignoffConfig,
4
4
  runSignoff
5
- } from "../chunk-BDMDL4AB.js";
5
+ } from "../chunk-HJBLT2BW.js";
6
6
  export {
7
7
  formatSignoffReport,
8
8
  loadSignoffConfig,
@@ -11,12 +11,13 @@
11
11
  * At measurement time, none of tax-agent, legal-agent, or agent-app had an
12
12
  * `.nvmrc`.
13
13
  * All three pinned Node 22 in the merge workflow.
14
- * Agent App now also pins Node 22 in `.nvmrc`.
14
+ * Agent App now pins Node 24.18.0 in `.nvmrc`.
15
15
  *
16
16
  * The workflow fallback reads only `pull_request` checks because those checks
17
17
  * can block a merge.
18
18
  * Agent App uses `.nvmrc` instead of this fallback.
19
- * Its publish workflow uses Node 22 for source checks and Node 24 for npm.
19
+ * Its publish workflow uses Node 24.18.0 for source checks and npm, with a
20
+ * separate clean-runner Node 22 compatibility job.
20
21
  *
21
22
  * Nothing here guesses. An expression (`${{ matrix.node }}`) is not a version,
22
23
  * a `node-version-file` that does not exist is not a pin, and two merge-gate
@@ -25,7 +25,7 @@ import {
25
25
  terminalizeDanglingAssistantToolUpdates,
26
26
  terminalizeDanglingToolPart,
27
27
  terminalizeDanglingToolParts
28
- } from "../chunk-4SGGSXI7.js";
28
+ } from "../chunk-ZMMIQOFI.js";
29
29
  import "../chunk-M3K2HVQD.js";
30
30
  import "../chunk-YJMCRXQQ.js";
31
31
  import {
@@ -38,7 +38,7 @@ import {
38
38
  } from "../chunk-TY2DALJG.js";
39
39
  import {
40
40
  useInfiniteScroll
41
- } from "../chunk-4XWVCO7P.js";
41
+ } from "../chunk-Z4TPWP6A.js";
42
42
  import {
43
43
  CheckGlyph,
44
44
  ChevronDown,
@@ -49,7 +49,7 @@ import {
49
49
  ProviderLogo,
50
50
  usePopover
51
51
  } from "../chunk-PYDMEYWA.js";
52
- import "../chunk-EDTWGSQT.js";
52
+ import "../chunk-SJWIZT7B.js";
53
53
 
54
54
  // src/studio-react/use-studio-generations.ts
55
55
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -16,6 +16,7 @@
16
16
  export * from './mission-trace';
17
17
  export * from './flow-types';
18
18
  export * from './mission-flow';
19
+ export * from './stage-timing';
19
20
  import type { FlowTrace } from './flow-types';
20
21
  /** Represent a timed event with a timestamp and associated event data */
21
22
  export interface TimedEvent {
@@ -46,6 +46,242 @@ function randomHex(byteLength) {
46
46
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
47
47
  }
48
48
 
49
+ // src/trace/stage-timing.ts
50
+ var STAGE_TIMING_EVENT = "stage_timing";
51
+ var STAGE_TIMING_VERSION = 1;
52
+ var MAX_STAGE_LENGTH = 80;
53
+ var MAX_IDENTIFIER_LENGTH = 128;
54
+ var MAX_DETAIL_KEYS = 8;
55
+ var MAX_DETAIL_KEY_LENGTH = 64;
56
+ var MAX_DETAIL_STRING_LENGTH = 64;
57
+ var SENSITIVE_KEY = /(?:api|auth|access|refresh|session|private|secret|password|credential|cookie|bearer|token|ssn|ein|email|phone)[_-]?(?:key|token|secret)?/iu;
58
+ var CREDENTIAL_VALUE = /\b(?:bearer|basic|digest|token)\s+\S+|\bapi[-_ ]?key\s*[:=]\s*\S+/iu;
59
+ function boundedIdentifier(value) {
60
+ if (typeof value !== "string") return void 0;
61
+ const trimmed = value.trim();
62
+ return trimmed ? trimmed.slice(0, MAX_IDENTIFIER_LENGTH) : void 0;
63
+ }
64
+ function safeProperty(value, key) {
65
+ try {
66
+ return Reflect.get(value, key);
67
+ } catch {
68
+ return void 0;
69
+ }
70
+ }
71
+ function isObject(value) {
72
+ return value !== null && typeof value === "object";
73
+ }
74
+ function sanitizeDetail(detail) {
75
+ try {
76
+ if (!isObject(detail) || Array.isArray(detail)) return void 0;
77
+ const entries = [];
78
+ for (const [rawKey, value] of Object.entries(detail)) {
79
+ if (entries.length >= MAX_DETAIL_KEYS) break;
80
+ const normalizedKey = rawKey.trim();
81
+ if (!normalizedKey || SENSITIVE_KEY.test(normalizedKey) || value === void 0) {
82
+ continue;
83
+ }
84
+ const key = normalizedKey.slice(0, MAX_DETAIL_KEY_LENGTH);
85
+ if (typeof value === "string") {
86
+ if (CREDENTIAL_VALUE.test(value)) continue;
87
+ entries.push([key, value.slice(0, MAX_DETAIL_STRING_LENGTH)]);
88
+ } else if (typeof value === "number") {
89
+ entries.push([key, Number.isFinite(value) ? value : null]);
90
+ } else if (typeof value === "boolean" || value === null) {
91
+ entries.push([key, value]);
92
+ }
93
+ }
94
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
95
+ } catch {
96
+ return void 0;
97
+ }
98
+ }
99
+ function isStageTimingKind(value) {
100
+ return value === "leaf" || value === "span";
101
+ }
102
+ function isStageTimingOutcome(value) {
103
+ return value === "ok" || value === "error" || value === "timeout" || value === "skipped";
104
+ }
105
+ function buildStageTimingRecord(context, stage, startedAt, durationMs, input = {}) {
106
+ try {
107
+ const name = typeof stage === "string" ? stage.trim() : "";
108
+ if (!name || !Number.isFinite(startedAt) || startedAt < 0 || !Number.isFinite(durationMs) || durationMs < 0 || !isObject(context) || !isObject(input)) {
109
+ return null;
110
+ }
111
+ const rawKind = safeProperty(input, "kind");
112
+ const rawOutcome = safeProperty(input, "outcome");
113
+ const kind = rawKind === void 0 ? "leaf" : rawKind;
114
+ const outcome = rawOutcome === void 0 ? "ok" : rawOutcome;
115
+ if (!isStageTimingKind(kind) || !isStageTimingOutcome(outcome)) return null;
116
+ const runId = boundedIdentifier(safeProperty(context, "runId"));
117
+ if (!runId) return null;
118
+ const record = {
119
+ evt: STAGE_TIMING_EVENT,
120
+ v: STAGE_TIMING_VERSION,
121
+ stage: name.slice(0, MAX_STAGE_LENGTH),
122
+ kind,
123
+ startedAt: Math.round(startedAt),
124
+ durationMs: Math.round(durationMs),
125
+ outcome,
126
+ runId
127
+ };
128
+ for (const key of [
129
+ "workspaceId",
130
+ "threadId",
131
+ "sandboxId",
132
+ "model",
133
+ "harness",
134
+ "path"
135
+ ]) {
136
+ const value = boundedIdentifier(safeProperty(context, key));
137
+ if (value) record[key] = value;
138
+ }
139
+ const attempt = safeProperty(input, "attempt");
140
+ if (typeof attempt === "number" && Number.isSafeInteger(attempt) && attempt >= 0) {
141
+ record.attempt = attempt;
142
+ }
143
+ const detail = sanitizeDetail(safeProperty(input, "detail"));
144
+ if (detail) record.detail = detail;
145
+ return record;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ function safePrimitiveText(value) {
151
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint" && typeof value !== "symbol") {
152
+ return "";
153
+ }
154
+ try {
155
+ return String(value);
156
+ } catch {
157
+ return "";
158
+ }
159
+ }
160
+ function outcomeForError(error) {
161
+ try {
162
+ const objectLike = isObject(error) || typeof error === "function";
163
+ const code = objectLike ? safePrimitiveText(safeProperty(error, "code")) : "";
164
+ const message = objectLike ? safePrimitiveText(safeProperty(error, "message")) : safePrimitiveText(error);
165
+ return /timeout|timed ?out|deadline/iu.test(`${code} ${message}`) ? "timeout" : "error";
166
+ } catch {
167
+ return "error";
168
+ }
169
+ }
170
+ function safeClock(now) {
171
+ try {
172
+ const value = now();
173
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
174
+ } catch {
175
+ return void 0;
176
+ }
177
+ }
178
+ function safeObject(value) {
179
+ try {
180
+ if (!isObject(value) || Array.isArray(value)) return {};
181
+ return { ...value };
182
+ } catch {
183
+ return {};
184
+ }
185
+ }
186
+ function mergeInputs(base, extra) {
187
+ const baseObject = safeObject(base);
188
+ const extraObject = safeObject(extra);
189
+ const detail = {
190
+ ...safeObject(baseObject.detail),
191
+ ...safeObject(extraObject.detail)
192
+ };
193
+ return {
194
+ ...baseObject,
195
+ ...extraObject,
196
+ detail
197
+ };
198
+ }
199
+ function withOutcome(extra, outcome) {
200
+ return { ...safeObject(extra), outcome };
201
+ }
202
+ function createStageTiming(options) {
203
+ const now = options.now ?? (() => Date.now());
204
+ const generatedRunId = () => {
205
+ try {
206
+ const value = (options.createRunId ?? (() => crypto.randomUUID()))();
207
+ return boundedIdentifier(value) ?? crypto.randomUUID();
208
+ } catch {
209
+ try {
210
+ return crypto.randomUUID();
211
+ } catch {
212
+ return "run-unknown";
213
+ }
214
+ }
215
+ };
216
+ const context = {
217
+ ...options.context,
218
+ runId: boundedIdentifier(options.context?.runId) ?? generatedRunId()
219
+ };
220
+ const emit = (stage, startedAt, durationMs, input = {}) => {
221
+ try {
222
+ const record = buildStageTimingRecord(context, stage, startedAt, durationMs, input);
223
+ if (!record) return;
224
+ const result = options.emit(record);
225
+ if (result && typeof result.then === "function") {
226
+ void Promise.resolve(result).catch(() => void 0);
227
+ }
228
+ } catch {
229
+ }
230
+ };
231
+ const start = (stage, input = {}) => {
232
+ const observedStart = safeClock(now);
233
+ const startedAt = observedStart ?? 0;
234
+ let emitted = false;
235
+ const finish = (extra = {}) => {
236
+ if (emitted) return;
237
+ emitted = true;
238
+ if (observedStart === void 0) return;
239
+ const observedEnd = safeClock(now);
240
+ if (observedEnd === void 0) return;
241
+ try {
242
+ emit(stage, observedStart, observedEnd - observedStart, mergeInputs(input, extra));
243
+ } catch {
244
+ }
245
+ };
246
+ return {
247
+ startedAt,
248
+ done: finish,
249
+ fail(error, extra = {}) {
250
+ let outcome = "error";
251
+ try {
252
+ outcome = outcomeForError(error);
253
+ } catch {
254
+ }
255
+ finish(withOutcome(extra, outcome));
256
+ }
257
+ };
258
+ };
259
+ return {
260
+ context,
261
+ setContext(input) {
262
+ try {
263
+ Object.assign(context, input);
264
+ } catch {
265
+ }
266
+ },
267
+ recordDuration(stage, startedAt, durationMs, input = {}) {
268
+ emit(stage, startedAt, durationMs, input);
269
+ },
270
+ start,
271
+ async measure(stage, input, operation) {
272
+ const handle = start(stage, input);
273
+ try {
274
+ const value = await operation();
275
+ handle.done();
276
+ return value;
277
+ } catch (error) {
278
+ handle.fail(error);
279
+ throw error;
280
+ }
281
+ }
282
+ };
283
+ }
284
+
49
285
  // src/trace/index.ts
50
286
  function timedEventsFromLines(lines) {
51
287
  const out = [];
@@ -184,10 +420,14 @@ function renderHistogram(values, opts) {
184
420
  return lines.join("\n");
185
421
  }
186
422
  export {
423
+ STAGE_TIMING_EVENT,
424
+ STAGE_TIMING_VERSION,
187
425
  buildFlowTrace,
426
+ buildStageTimingRecord,
188
427
  childSpanContext,
189
428
  composeMissionFlowTrace,
190
429
  createMissionTraceContext,
430
+ createStageTiming,
191
431
  delegationActivityToFlowSpans,
192
432
  loopTraceEventsToFlowSpans,
193
433
  renderHistogram,