@tangle-network/agent-app 0.63.17 → 0.63.19

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 (128) hide show
  1. package/dist/agent-profiles/d1.js +2 -2
  2. package/dist/agent-profiles/index.js +2 -2
  3. package/dist/agent-profiles/switch.d.ts +1 -1
  4. package/dist/agent-profiles/switch.js +1 -1
  5. package/dist/app-auth/index.js.map +1 -1
  6. package/dist/chat-routes/hybrid-producer.d.ts +1 -1
  7. package/dist/chat-routes/index.js +11 -11
  8. package/dist/chat-routes/model-failover-stream.d.ts +1 -1
  9. package/dist/chat-routes/turn-prefetch.d.ts +1 -1
  10. package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
  11. package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
  12. package/dist/chunk-3CI35I4X.js.map +1 -0
  13. package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
  14. package/dist/chunk-3Q3UEWKK.js.map +1 -0
  15. package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
  16. package/dist/chunk-5WSSH3X5.js.map +1 -0
  17. package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
  18. package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
  19. package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
  20. package/dist/chunk-K3A2YAIX.js.map +1 -0
  21. package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
  22. package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
  23. package/dist/chunk-LMIP4OVR.js.map +1 -0
  24. package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
  25. package/dist/chunk-N5RWYR5N.js.map +1 -0
  26. package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
  27. package/dist/chunk-OSMMEMDH.js.map +1 -0
  28. package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
  29. package/dist/chunk-OYFA7BAK.js.map +1 -0
  30. package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
  31. package/dist/chunk-OZDMIYES.js.map +1 -0
  32. package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
  33. package/dist/chunk-QUT3T2IN.js.map +1 -0
  34. package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
  35. package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
  36. package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
  37. package/dist/chunk-UULUBF5J.js.map +1 -0
  38. package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
  39. package/dist/chunk-VEPII3YP.js.map +1 -0
  40. package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
  41. package/dist/chunk-W6G2HF6M.js.map +1 -0
  42. package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
  43. package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
  44. package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
  45. package/dist/chunk-XGFGSZS5.js.map +1 -0
  46. package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
  47. package/dist/chunk-YRWUJKW5.js.map +1 -0
  48. package/dist/journeys/artifacts.d.ts +1 -0
  49. package/dist/journeys/cli.js +1 -1
  50. package/dist/journeys/index.js +55 -18
  51. package/dist/journeys/index.js.map +1 -1
  52. package/dist/journeys/journey.d.ts +1 -0
  53. package/dist/journeys/score.d.ts +1 -1
  54. package/dist/journeys/scoreboard.d.ts +1 -2
  55. package/dist/journeys/send.d.ts +1 -2
  56. package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
  57. package/dist/launch-invariants/catalog.d.ts +3 -3
  58. package/dist/launch-invariants/cli.js +3 -3
  59. package/dist/launch-invariants/index.d.ts +1 -1
  60. package/dist/launch-invariants/index.js +3 -3
  61. package/dist/launch-invariants/index.js.map +1 -1
  62. package/dist/launch-invariants/limit-alarms.d.ts +1 -1
  63. package/dist/launch-invariants/pasted-code.d.ts +1 -1
  64. package/dist/launch-invariants/schedule.d.ts +1 -1
  65. package/dist/launch-invariants/settlement.d.ts +2 -2
  66. package/dist/launch-invariants/sized-reads.d.ts +1 -1
  67. package/dist/launch-invariants/testing.js +3 -3
  68. package/dist/model-resolution/index.js +1 -1
  69. package/dist/platform/billable-turn-admission.d.ts +1 -1
  70. package/dist/platform/delegated-keys.d.ts +2 -2
  71. package/dist/platform/delegated-turn-keys.d.ts +1 -1
  72. package/dist/platform/index.js.map +1 -1
  73. package/dist/preflight/cli.js +1 -1
  74. package/dist/preflight/index.d.ts +1 -1
  75. package/dist/preflight/index.js +1 -1
  76. package/dist/preset-cloudflare/index.js +6 -6
  77. package/dist/public-consultation/index.js +9 -9
  78. package/dist/rollout/cli.js +1 -1
  79. package/dist/rollout/d1.js +1 -1
  80. package/dist/rollout/index.d.ts +1 -1
  81. package/dist/rollout/index.js +1 -1
  82. package/dist/runtime/index.js +3 -3
  83. package/dist/runtime/router-turn.d.ts +3 -3
  84. package/dist/runtime/router-turn.js +2 -2
  85. package/dist/runtime/turn-knowledge.d.ts +1 -1
  86. package/dist/sandbox/index.js +5 -5
  87. package/dist/sandbox/model.d.ts +1 -1
  88. package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
  89. package/dist/sandbox/prewarm.d.ts +2 -2
  90. package/dist/sandbox/reuse-state.d.ts +1 -1
  91. package/dist/sandbox/terminal-connection.d.ts +4 -4
  92. package/dist/sandbox/warm-lease.d.ts +2 -2
  93. package/dist/sandbox/warm-receipts.d.ts +1 -1
  94. package/dist/signoff/app-defaults.d.ts +1 -1
  95. package/dist/signoff/cli.js +2 -2
  96. package/dist/signoff/index.js +2 -2
  97. package/dist/signoff/surface-ladder.d.ts +2 -2
  98. package/dist/signoff/workspace-surface.d.ts +1 -1
  99. package/dist/stream/index.js +2 -2
  100. package/dist/stream/turn-buffer.d.ts +1 -1
  101. package/dist/turn-health/index.js +1 -1
  102. package/dist/turn-health/index.js.map +1 -1
  103. package/dist/turn-stream/adapters.d.ts +1 -1
  104. package/dist/turn-stream/core.d.ts +1 -1
  105. package/dist/turn-stream/index.js +2 -2
  106. package/dist/turn-trace/index.js +1 -1
  107. package/dist/turn-trace/otel.d.ts +1 -1
  108. package/dist/workspace-export/index.js.map +1 -1
  109. package/package.json +1 -1
  110. package/dist/chunk-5FAKBTCK.js.map +0 -1
  111. package/dist/chunk-5UQJ7F3P.js.map +0 -1
  112. package/dist/chunk-6GX3UHQW.js.map +0 -1
  113. package/dist/chunk-7EDNPQHW.js.map +0 -1
  114. package/dist/chunk-7VTGB4DM.js.map +0 -1
  115. package/dist/chunk-A3BJDXPX.js.map +0 -1
  116. package/dist/chunk-AVBNS64P.js.map +0 -1
  117. package/dist/chunk-E3AOUTIR.js.map +0 -1
  118. package/dist/chunk-EKXG4JSN.js.map +0 -1
  119. package/dist/chunk-I6BZVIRH.js.map +0 -1
  120. package/dist/chunk-ISP6ZH3G.js.map +0 -1
  121. package/dist/chunk-LRYY3OX7.js.map +0 -1
  122. package/dist/chunk-MT6ZTQGD.js.map +0 -1
  123. package/dist/chunk-VDYEVCQQ.js.map +0 -1
  124. package/dist/chunk-ZLX4BA27.js.map +0 -1
  125. /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
  126. /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
  127. /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
  128. /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
@@ -692,4 +692,4 @@ export {
692
692
  broadcastThreadCreated,
693
693
  createTurnStreamUpgradeHandler
694
694
  };
695
- //# sourceMappingURL=chunk-MT6ZTQGD.js.map
695
+ //# sourceMappingURL=chunk-N5RWYR5N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/turn-stream/core.ts","../src/turn-stream/cancellation.ts","../src/chat-routes/stale-turn-lock.ts","../src/turn-stream/adapters.ts"],"sourcesContent":["/**\n * Channel tokens, lock records, workspace signals, and durable event keys.\n * Interactive turn replay belongs to the sandbox session gateway.\n * An optional turn-event backend stores durable rows and a running-turn index.\n * This core uses WebCrypto and plain data without a Cloudflare runtime import.\n */\n\nimport { base64UrlEncodeText, constantTimeEqual, hmacSha256Base64Url } from '../crypto/web-token'\n\n// ── events ──────────────────────────────────────────────────────────────────\n\n/** One event on a turn-stream channel. Workspace-signal events\n * (`thread.created`, `thread.activity`, product events) carry no `seq` —\n * ordering is delivery order on the DO's single-threaded event loop. */\nexport interface TurnStreamEvent {\n type: string\n data?: unknown\n timestamp: number\n seq?: never\n}\n\n// ── channel-bound capability tokens (issue #746) ─────────────────────────────\n//\n// The DO's endpoints are not publicly routed, but \"safe because nothing\n// forwards to it\" is convention, not enforcement: one accidental\n// `stub.fetch(publicRequest)` and every channel's lock, turn events, and\n// signals are cross-tenant writable. Every request the DO serves must now\n// carry a short-lived HMAC capability token minted for THIS DO's channel\n// name — a valid token for one channel is refused by every other, and a\n// token without the secret cannot exist. Worker code mints with the same\n// secret via the adapters (`authSecret`) and the WS upgrade forwarder;\n// nothing else needs to know the format.\n\n/** Default capability lifetime. Tokens are minted per worker request and\n * verified immediately; a WS token gates only the upgrade handshake — an\n * accepted socket lives until it closes. */\nexport const TURN_STREAM_TOKEN_TTL_MS = 60_000\n\n/** Request header the adapters attach (and the DO accepts). The worker also\n * attaches it when forwarding an authorized browser WebSocket handshake. */\nexport const TURN_STREAM_TOKEN_HEADER = 'x-turn-stream-token'\n\n/** Server control authority is separate from the channel capabilities used by existing viewer forwarders. */\nexport interface TurnStreamTokenClaims {\n purpose: 'turn-control' | 'turn-cancel' | 'turn-recovery'\n identity: TurnLockReleaseInput & { turnStreamId: string }\n}\n\nfunction encodeTurnStreamClaims(claims: TurnStreamTokenClaims): string {\n const { identity, purpose } = claims\n if (!['turn-control', 'turn-cancel', 'turn-recovery'].includes(purpose)\n || !identity || !['thread', 'workspace'].includes(identity.scope)\n || [identity.workspaceId, identity.threadId, identity.executionId, identity.lockId, identity.turnStreamId]\n .some(value => typeof value !== 'string' || !value.trim())) throw new Error('Invalid turn-stream control claims')\n return base64UrlEncodeText(JSON.stringify([purpose, identity.workspaceId, identity.threadId, identity.scope,\n identity.executionId, identity.lockId, identity.turnStreamId]))\n}\n\n/** Legacy v1 channel capabilities remain unchanged. Optional v2 claims bind\n * server-only purpose and exact owner identity inside the same signed payload. */\nexport async function mintTurnStreamToken(\n channelName: string,\n secret: string,\n now: () => number = Date.now,\n ttlMs: number = TURN_STREAM_TOKEN_TTL_MS,\n claims?: TurnStreamTokenClaims,\n): Promise<string> {\n if (!secret || secret.length < 32) throw new Error('turn-stream token secret must be at least 32 characters')\n const expiresAt = now() + ttlMs\n const payload = `${claims ? 'v2' : 'v1'}.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}${claims ? `.${encodeTurnStreamClaims(claims)}` : ''}`\n return `${payload}.${await hmacSha256Base64Url(payload, secret)}`\n}\n\n/** Verify a token for `channelName`: constant-time MAC compare with the\n * exact channel name embedded in the signed payload, plus freshness. A\n * token minted for any other channel — or a tampered expiry — is false. */\nexport async function verifyTurnStreamToken(\n channelName: string,\n token: string,\n secret: string,\n now: () => number = Date.now,\n claims?: TurnStreamTokenClaims,\n): Promise<boolean> {\n if (!secret || secret.length < 32) return false\n const parts = token.split('.')\n const version = parts[0]\n if (!(version === 'v1' && parts.length === 4 || version === 'v2' && parts.length === 5)) return false\n const name = parts[1]!\n const expires36 = parts[2]!\n const mac = parts.at(-1)!\n if (claims) {\n try { if (version !== 'v2' || parts[3] !== encodeTurnStreamClaims(claims)) return false }\n catch { return false }\n }\n if (name !== base64UrlEncodeText(channelName)) return false\n if (!/^[0-9a-z]+$/.test(expires36)) return false\n const expiresAt = parseInt(expires36, 36)\n if (!Number.isSafeInteger(expiresAt) || expiresAt <= now()) return false\n const expected = await hmacSha256Base64Url(parts.slice(0, -1).join('.'), secret)\n return constantTimeEqual(mac, expected)\n}\n\n// ── channel keys ────────────────────────────────────────────────────────────\n//\n// One DO instance per channel key. Four families:\n// thread `${workspaceId}:${threadId}` — thread viewer signals.\n// workspace `${workspaceId}` — sidebar activity + thread.created\n// + every turn lock: the workspace-scope lock and each\n// thread-scope lock, under separate storage keys.\n// turn `turn:${turnId}` — durable turn-event rows + status\n// (the TurnEventStore contract; replay survives DO eviction).\n// scope `scope:${scopeId}` — running-turn index for a thread,\n// backing `TurnEventStore.listRunning`.\n\n/** Define the scope level for acquiring a turn lock within thread or workspace contexts */\nexport type TurnLockScope = 'thread' | 'workspace'\n\n/** Channel for a thread's viewer signals. */\nexport function threadChannelKey(workspaceId: string, threadId: string): string {\n return `${workspaceId}:${threadId}`\n}\n\n/** Channel for workspace signals and the workspace-scoped lock. */\nexport function workspaceChannelKey(workspaceId: string): string {\n return workspaceId\n}\n\n/** The channel a lock lives on: the workspace channel, for both scopes.\n * Workspace-scope locks serialize every thread in the workspace (one shared\n * sandbox) and thread-scope locks serialize one thread (router lane); they\n * stay independent because each has its own storage key\n * ({@link turnLockStorageKey}). A thread lock on its own channel created a\n * new Durable Object on every thread's first turn, 0.8-1.9 s inside Creative's\n * admission on staging against an object that already exists. */\nexport function turnLockChannelKey(workspaceId: string, _threadId: string, _scope: TurnLockScope): string {\n return workspaceChannelKey(workspaceId)\n}\n\n/** The storage key a lock lives under inside its channel's instance: the\n * workspace-scope lock under `TURN_STREAM_STORAGE_KEYS.lock`, each thread's\n * lock under `TURN_STREAM_STORAGE_KEYS.threadLockPrefix` + its thread id. */\nexport function turnLockStorageKey(scope: TurnLockScope, threadId: string): string {\n return scope === 'workspace' ? TURN_STREAM_STORAGE_KEYS.lock : `${TURN_STREAM_STORAGE_KEYS.threadLockPrefix}${threadId}`\n}\n\n/** Channel for the optional Durable Object turn-event backend. */\nexport function turnStorageChannelKey(turnId: string): string {\n return `turn:${turnId}`\n}\n\n/** Running-turn index for the optional Durable Object turn-event backend. */\nexport function scopeIndexChannelKey(scopeId: string): string {\n return `scope:${scopeId}`\n}\n\n/** Recent thread-created markers kept for late-connecting sidebars. */\nexport const MAX_RECENT_CREATED = 50\n\n/** A responding marker older than this is treated as stale, so a dropped\n * `end` broadcast can't leave a permanently-stuck \"responding\" dot. */\nexport const ACTIVITY_TTL_MS = 15 * 60 * 1000\n\n/** Remove responding markers older than ttlMs; return their thread IDs. */\nexport function pruneStaleThreads(active: Map<string, number>, now: number, ttlMs: number): string[] {\n const removed: string[] = []\n for (const [threadId, startedAt] of active) {\n if (now - startedAt > ttlMs) {\n active.delete(threadId)\n removed.push(threadId)\n }\n }\n return removed\n}\n\n// ── chat-turn lock record + fences ──────────────────────────────────────────\n\n/** Fallback lifetime for an unreleased lock. Use stale-lock reconciliation to\n * recover earlier when execution state proves that its holder stopped. */\nexport const TURN_LOCK_TTL_MS = 30 * 60 * 1000\n\n/** The stored single-flight lock. Field-compatible with the reference\n * consumer's `ChatTurnLock` so adoption is a swap, not a migration. */\nexport interface DurableTurnLock {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n startedAt: number\n expiresAt: number\n turnId?: string\n /** The turn released this lock, but a product-owned post-turn task (e.g.\n * file persistence reading the box) is still running, so the release is\n * parked on the lock until the task settles. Written only through the DO's\n * defer seam — the base package never sets it on its own. */\n releasePending?: boolean\n /** Optional Router control, owned by this exact lock generation. Stop never releases the lock. */\n cancellation?: { turnStreamId: string; requestedAt?: number }\n}\n\n/** Define input parameters required to acquire a turn-based lock in a workspace thread */\nexport interface TurnLockAcquireInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n turnId?: string\n cancellation?: { turnStreamId: string }\n}\n\n/** Resolve the result of attempting to acquire a turn lock indicating success or active lock status */\nexport type TurnLockAcquireResult =\n | { acquired: true; lock: DurableTurnLock }\n | { acquired: false; active: DurableTurnLock }\n\n/** Define input parameters required to release a turn lock in a specific workspace thread */\nexport interface TurnLockReleaseInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n lockId: string\n}\n\n/** Fenced out-of-band release (stop button, stale-lock reconciliation). The\n * fences make it refuse a SUCCESSOR lock: `interruptedAt` must not precede\n * the lock's own start, and when either side names a turn, both must name\n * the same one. */\nexport interface TurnLockInterruptedReleaseInput {\n workspaceId: string\n threadId: string\n /** Try only this scope; omit to try workspace then thread. */\n scope?: TurnLockScope\n interruptedAt: number\n turnId?: string\n /** Only after the existing stale policy positively proves this exact Router owner and its children abandoned. */\n recovery?: TurnLockReleaseInput & { turnStreamId: string }\n}\n\n/** `stored` is what the DO read from storage; expired locks are dead. */\nexport function activeTurnLock(stored: DurableTurnLock | undefined, now: number): DurableTurnLock | null {\n if (!stored) return null\n // Locks written before the scope field existed default to thread scope.\n const lock = stored.scope ? stored : { ...stored, scope: 'thread' as const }\n return lock.expiresAt > now ? lock : null\n}\n\n/** Create a durable turn lock object with timing and scope based on input parameters */\nexport function createTurnLock(input: TurnLockAcquireInput, now: number, ttlMs = TURN_LOCK_TTL_MS): DurableTurnLock {\n return {\n workspaceId: input.workspaceId,\n threadId: input.threadId,\n scope: input.scope,\n executionId: input.executionId,\n lockId: input.lockId,\n startedAt: now,\n expiresAt: now + ttlMs,\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.cancellation ? { cancellation: { turnStreamId: input.cancellation.turnStreamId } } : {}),\n }\n}\n\n/** A cooperative release matches the execution and, when supplied, lock ID. */\nexport function turnLockMatchesRelease(\n active: DurableTurnLock,\n input: { executionId: string; lockId?: string },\n): boolean {\n if (active.executionId !== input.executionId) return false\n if (input.lockId && active.lockId !== input.lockId) return false\n return true\n}\n\n/**\n * The interrupted/stale release fence. `interruptedAt` is the instant the\n * releasing evidence was observed (the stop click, the stale-lock probe) —\n * a lock STARTED after that instant is a successor the evidence says nothing\n * about, so it survives. When the lock recorded a client turnId, the release\n * must name the same turn; a lock without one refuses a turn-specific\n * release (it cannot prove it is that turn).\n */\nexport function interruptedReleaseApplies(\n active: DurableTurnLock,\n input: { threadId: string; interruptedAt: number; turnId?: string },\n): boolean {\n if (active.threadId !== input.threadId) return false\n if (active.startedAt > input.interruptedAt) return false\n if (active.turnId) {\n if (active.turnId !== input.turnId) return false\n } else if (input.turnId) {\n return false\n }\n return true\n}\n\n// ── wire contract (adapter ↔ DO endpoint paths) ─────────────────────────────\n//\n// Kept byte-identical to the reference consumer's DO where an endpoint\n// existed there, so a product deletes its fork by re-pointing a binding, not\n// by re-speaking a protocol.\n\n/** Provide constant paths for managing chat turn streams and locks */\nexport const TURN_STREAM_PATHS = {\n broadcast: '/broadcast',\n lockAcquire: '/chat-turn-lock/acquire',\n /** Read the active lock without changing it; also brings the object up before a turn needs it. */\n lockPeek: '/chat-turn-lock/peek',\n lockRelease: '/chat-turn-lock/release',\n lockReleaseInterrupted: '/chat-turn-lock/release-interrupted',\n turnEventsAppend: '/turn-events/append',\n turnEventsRead: '/turn-events/read',\n turnStatusSet: '/turn-status/set',\n turnStatusGet: '/turn-status/get',\n scopeStatusSet: '/turn-scope/set',\n scopeRunningList: '/turn-scope/running',\n} as const\n\n/** Storage keys inside a DO instance. Exported for subclass coexistence —\n * a product extending the DO must not collide with these. */\nexport const TURN_STREAM_STORAGE_KEYS = {\n lock: 'chatTurnLock',\n threadLockPrefix: 'chatTurnLock:thread:',\n activeThreads: 'activeThreads',\n turnStatus: 'turnStatus',\n turnScope: 'turnScopeIndex',\n turnEventPrefix: 'turnEvent:',\n} as const\n\n/** Zero-padded seq so DO storage `list({ prefix })` returns rows in replay\n * order without a sort. 10 digits holds any realistic turn. */\nexport function turnEventStorageKey(seq: number): string {\n return `${TURN_STREAM_STORAGE_KEYS.turnEventPrefix}${String(seq).padStart(10, '0')}`\n}\n","import type { TurnStreamAuth, TurnStreamNamespaceLike } from './adapters'\nimport { TURN_STREAM_PATHS, TURN_STREAM_TOKEN_HEADER, mintTurnStreamToken, turnLockChannelKey } from './core'\nimport type { TurnCancellationIdentity } from './cancellation-do'\nexport type { TurnCancellationIdentity } from './cancellation-do'\n\n/** Per-owner observation only. Closing it never changes or releases the durable lock. */\nexport interface TurnCancellationConnection {\n signal: AbortSignal\n close(): void\n}\n\ninterface ControlSocket extends EventTarget {\n accept(): void\n send(value: string): void\n close(code?: number, reason?: string): void\n}\n\nexport class TurnCancellationRequestedError extends Error {\n readonly code = 'turn_cancel_requested'\n constructor() { super('Cancellation was requested for this turn'); this.name = 'TurnCancellationRequestedError' }\n}\n\nexport class TurnControlUnavailableError extends Error {\n readonly code = 'turn_control_unavailable'\n constructor(message = 'The durable turn control connection was lost') { super(message); this.name = 'TurnControlUnavailableError' }\n}\n\nasync function cancellationRequest(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth, upgrade: boolean,\n) {\n const key = turnLockChannelKey(identity.workspaceId, identity.threadId, identity.scope)\n const url = new URL(`https://turn-stream.internal${upgrade ? '/' : TURN_STREAM_PATHS.lockReleaseInterrupted}`)\n const headers = new Headers({ [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(key, auth.secret, undefined, undefined,\n { purpose: upgrade ? 'turn-control' : 'turn-cancel', identity }) })\n if (upgrade) {\n for (const [name, value] of Object.entries(identity)) url.searchParams.set(name, value)\n url.searchParams.set('sessionId', identity.threadId)\n url.searchParams.set('cancellation', '1')\n headers.set('Upgrade', 'websocket')\n } else headers.set('Content-Type', 'application/json')\n return namespace.get(namespace.idFromName(key)).fetch(url.href, { method: upgrade ? 'GET' : 'POST', headers,\n ...(upgrade ? {} : { body: JSON.stringify({ ...identity, cancel: true }) }) })\n}\n\n/** The product authorizes Stop first. This exact fenced request records intent; it never claims work stopped. */\nexport async function requestDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth,\n): Promise<{ requested: boolean; reason?: 'stale-owner' }> {\n const response = await cancellationRequest(namespace, identity, auth, false)\n if (!response.ok) throw new Error(`Turn cancellation failed (HTTP ${response.status})`)\n return response.json()\n}\n\n/** One server-owned connection on the existing authenticated DO transport, with retained cancellation replay. */\nexport async function connectDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity,\n auth: TurnStreamAuth,\n): Promise<TurnCancellationConnection> {\n const response = await cancellationRequest(namespace, identity, auth, true) as Response & { webSocket?: ControlSocket }\n if (response.status !== 101 || !response.webSocket) throw new TurnControlUnavailableError(`Turn control connection failed (HTTP ${response.status})`)\n const socket = response.webSocket\n const controller = new AbortController()\n let closing = false\n let ready = false\n let resolveReady!: () => void\n let rejectReady!: (error: Error) => void\n const connected = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject })\n const fail = () => {\n if (closing) return\n const error = new TurnControlUnavailableError()\n if (!ready) rejectReady(error)\n controller.abort(error)\n }\n const close = () => { closing = true; clearTimeout(timer); try { socket.close(1000, 'Owner observation ended') } catch { /* Already closed. */ } }\n const timer = setTimeout(() => { if (!ready) { fail(); close() } }, 10_000)\n socket.addEventListener('message', event => {\n let message: { type?: string; cancellationRequested?: boolean }\n try { message = JSON.parse(String((event as MessageEvent).data)) } catch { fail(); close(); return }\n if (message.type === 'turn.control.released') {\n // A normal owner closes before its own cooperative release. Any release\n // still observed here removes this producer's authority to continue I/O.\n fail()\n close(); return\n }\n if (message.type === 'turn.control.ownership-lost') { fail(); close(); return }\n if (message.type !== 'turn.control' || typeof message.cancellationRequested !== 'boolean') { fail(); close(); return }\n if (message.cancellationRequested) controller.abort(new TurnCancellationRequestedError())\n ready = true\n clearTimeout(timer)\n resolveReady()\n })\n socket.addEventListener('close', fail)\n socket.addEventListener('error', fail)\n try { socket.accept(); socket.send(JSON.stringify({ type: 'sync' })); await connected }\n catch (error) { close(); throw error }\n return { signal: controller.signal, close }\n}\n","import type { TurnCancellationIdentity } from '../turn-stream/cancellation'\n\n/**\n * Recovery policy for a `ChatTurnLock` whose holder died.\n *\n * `createChatTurnRoutes` takes the lock as a seam (`acquire`/`release`) and a\n * lock is a single-flight guard: while it is held, a second turn on the same\n * scope is refused. Products give it a TTL measured in tens of minutes, so a\n * turn that dies without releasing wedges chat for that whole window. Every\n * app on the seam inherits that wedge, which is why the way OUT of it is\n * policy this package owns rather than something each app rediscovers.\n *\n * The policy takes PROBES, not clients: it imports no sandbox SDK, opens no\n * connection, and knows nothing about how a product finds its box or talks to\n * a sidecar. That is what makes the rules testable and what keeps the concrete\n * probes — which box key, which session id, which sidecar endpoint — in the\n * product.\n *\n * A supplied exact Router owner probe replaces the native rules: live and\n * unknown hold; positive outer + child abandonment observes the same terminal\n * grace and exact release fence. A native session cannot attest to a Router owner.\n *\n * The native rules, in precedence order:\n *\n * 1. The session probe answered and the execution is TERMINAL ⇒ release, once\n * the lock is past a short grace period. The authority on \"is this turn\n * still running\" is whatever is actually running it; a terminal verdict is\n * proof the lock outlived its turn — but only if the verdict is about THIS\n * turn, which is what the grace buys (see\n * {@link DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS}).\n * 2. The session probe answered and the execution is LIVE ⇒ hold, always.\n * Nothing below may override this. The lock is doing exactly its job.\n * 3. The probes could not reach that authority at all — the sandbox could not\n * be listed, is gone, is not running, or its session probe failed ⇒ fall\n * back on the physical argument: an execution runs INSIDE the box, so a box\n * that is not there is running nothing, and the lock is releasable. Without\n * this fallback the recovery would depend on the very subsystem whose\n * failure produced the stale lock.\n *\n * Rule 3 is gated on a grace period because it is an inference, not an\n * observation — see {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS}.\n */\n\n/** Where the box is, as far as the caller can see. `state` on `not-running`\n * is the platform's own status string, carried through for the log. */\nexport type StaleTurnLockSandboxProbeResult =\n | { status: 'running' }\n | { status: 'absent' }\n | { status: 'not-running'; state?: string }\n\n/** What the thing running the turn says about it. `terminal: false` means an\n * execution is LIVE — the strongest signal in the policy. `diagnostics` rides\n * through to the result and the logs unread. */\nexport type StaleTurnLockSessionProbeResult =\n | { reachable: true; terminal: boolean; diagnostics?: Record<string, unknown> }\n | { reachable: false; reason?: string }\n\n/** A positive abandoned verdict covers the exact outer producer and every registered child/effect owner. */\nexport interface StaleTurnLockOwnerProbeResult {\n identity: TurnCancellationIdentity\n status: 'live' | 'abandoned' | 'unknown'\n diagnostics?: Record<string, unknown>\n}\n\n/**\n * Minimum age a lock must reach before the \"sandbox unreachable ⇒ nothing can\n * be running\" fallback may force-release it.\n *\n * The lock is acquired BEFORE the box is ensured, so during a cold workspace's\n * first turn there is a real window in which the lock is held and no box exists\n * yet — indistinguishable, from a peek, from a box that vanished. The grace\n * period has to outlast that window (create + bootstrap + whatever the product\n * hydrates) or a concurrent request steals the lock from a turn that is merely\n * still provisioning. Five minutes clears observed cold starts with room to\n * spare while cutting the worst case from a TTL-length wedge down to five\n * minutes. Raising it makes recovery slower; lowering it risks stealing a lock\n * mid-provision.\n */\nexport const DEFAULT_STALE_TURN_LOCK_GRACE_MS = 5 * 60 * 1000\n\n/**\n * Minimum age a lock must reach before a TERMINAL session verdict may release\n * it.\n *\n * The session probe is keyed on the THREAD, not on the execution the lock\n * holds: a sidecar that has nothing running reports `terminal` with\n * `activeExecutionId: null`, so there is no id to match the lock against. The\n * lock, meanwhile, is acquired BEFORE the box is ensured and before the\n * execution registers with the sidecar. Between those two moments a second\n * request that reconciles the lock asks the sidecar about a turn it has not\n * heard of yet and gets back the PREVIOUS turn's terminal state — proof about\n * the wrong execution. Releasing on that verdict hands the second request a\n * lock the first one is still using, which is two concurrent turns on a scope\n * whose single-flight guard just voted for itself.\n *\n * One minute covers the acquire → box-ensure → sidecar-registration window on\n * a warm box (the cold-box case is Rule 3's, and has its own, much longer\n * grace). Deliberately NOT\n * {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS}: this branch has a positive\n * observation behind it, so it should recover fast, and stretching it to five\n * minutes would leave a genuinely dead turn wedged for the whole window that\n * the session probe exists to shortcut. Raising it delays recovery from a\n * crashed turn; lowering it narrows the registration window it protects.\n */\nexport const DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS = 60 * 1000\n\n/** Resolve options for probing and releasing stale TURN locks based on lock start time and sandbox state */\nexport interface ReconcileStaleTurnLockOptions {\n /** When the held lock was acquired (epoch ms). The grace period is measured\n * from here, so it must be the LOCK's start, not the turn's. */\n lockStartedAt: number\n /** Router ownership replaces native-only inference. Missing/uncertain outer or child evidence must stay unknown. */\n owner?: {\n identity: TurnCancellationIdentity\n probe(identity: TurnCancellationIdentity): Promise<StaleTurnLockOwnerProbeResult>\n }\n /** Is the box there and running? Never provisions — a peek, not an ensure.\n * A throw is treated as unreachable, same as `absent`. */\n probeSandbox(): Promise<StaleTurnLockSandboxProbeResult>\n /** Ask the running box whether the execution is still live. Only called when\n * `probeSandbox` reported `running`. A throw is treated as unreachable. */\n probeSession(): Promise<StaleTurnLockSessionProbeResult>\n /** Release the lock, fenced by the instant the releasing evidence was\n * observed. `fence.observedAt` is snapshotted BEFORE the probe that\n * justified the release, so a store that can compare it against the held\n * lock's start refuses to delete a SUCCESSOR lock acquired while the probe\n * was in flight. A store that cannot make that comparison may ignore the\n * fence, but must not substitute its own `Date.now()` — that timestamp is\n * by construction newer than any successor and makes the check vacuous.\n *\n * Returns whether the release actually landed — `false` when the lock was\n * already gone (someone else got there first), which is reported, never\n * treated as a release. */\n release(fence: { observedAt: number }): boolean | Promise<boolean>\n /** Override {@link DEFAULT_STALE_TURN_LOCK_GRACE_MS} (Rule 3's fallback). */\n graceMs?: number\n /** Override {@link DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS} (Rule 1's release). */\n terminalGraceMs?: number\n /** Identity fields merged into every log line (workspace, thread, execution\n * id — whatever makes the entry findable in the product's logs). */\n context?: Record<string, unknown>\n /** Defaults to `console.warn`. Both the withheld and the force-released\n * branches log; a force-release is never silent. */\n log?(message: string, meta: Record<string, unknown>): void\n /** Injectable clock, for tests. */\n now?(): number\n}\n\n/** Describe the outcome of reconciling a stale turn lock including release status and diagnostics */\nexport interface ReconcileStaleTurnLockResult {\n released: boolean\n /** Why the policy decided what it did — the probe's own diagnostics on the\n * reachable path, the unreachable reason and lock age on the fallback. */\n diagnostics: Record<string, unknown>\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Decide whether a held lock is stale and, if so, release it.\n *\n * Never provisions and never mutates anything but the lock: a reconciliation\n * attempt on a cold workspace leaves it cold.\n */\nexport async function reconcileStaleTurnLock(\n options: ReconcileStaleTurnLockOptions,\n): Promise<ReconcileStaleTurnLockResult> {\n if (options.owner) return reconcileTurnOwner(options)\n let sandbox: StaleTurnLockSandboxProbeResult\n try {\n sandbox = await options.probeSandbox()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SANDBOX_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (sandbox.status !== 'running') {\n return forceReleaseUnreachable(options, {\n unreachableReason: sandbox.status === 'absent' ? 'SANDBOX_ABSENT' : 'SANDBOX_NOT_RUNNING',\n ...(sandbox.status === 'not-running' && sandbox.state !== undefined\n ? { sandboxState: sandbox.state }\n : {}),\n })\n }\n\n // Snapshot the clock BEFORE the probe and use that one instant for BOTH the\n // grace decision and the release fence: the release is only valid against the\n // lock as it was when the state was observed, not after an arbitrarily slow\n // round trip. Re-reading the clock after the probe would let a slow round\n // trip age the lock past the grace on paper, and would hand the store a fence\n // newer than a successor lock acquired meanwhile.\n const observedAt = (options.now ?? Date.now)()\n let session: StaleTurnLockSessionProbeResult\n try {\n session = await options.probeSession()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SESSION_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (!session.reachable) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SESSION_UNREACHABLE',\n ...(session.reason !== undefined ? { sessionProbeError: session.reason } : {}),\n })\n }\n\n const diagnostics: Record<string, unknown> = {\n sandboxReachable: true,\n sessionTerminal: session.terminal,\n ...(session.diagnostics ?? {}),\n }\n // The authority answered and says the execution is live: the lock is doing\n // its job. Nothing below this point may override that.\n if (!session.terminal) return { released: false, diagnostics }\n\n // Terminal, but about WHICH execution? The probe is thread-keyed, so a lock\n // younger than the registration window may be reading the previous turn's\n // verdict — hold until it is old enough that the verdict has to be its own.\n const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n if (lockAgeMs < terminalGraceMs) {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const withheld = {\n ...diagnostics,\n lockAgeMs,\n terminalReleaseGraceMs: terminalGraceMs,\n terminalReleaseWithheld: 'LOCK_WITHIN_TERMINAL_GRACE_PERIOD',\n }\n log('[chat-routes] stale turn lock held: terminal verdict but lock is younger than the registration window', {\n ...(options.context ?? {}),\n ...withheld,\n })\n return { released: false, diagnostics: withheld }\n }\n\n const released = await options.release({ observedAt })\n return {\n released,\n diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, released, observedAt },\n }\n}\n\nasync function reconcileTurnOwner(options: ReconcileStaleTurnLockOptions): Promise<ReconcileStaleTurnLockResult> {\n const owner = options.owner!\n // The observation fence is captured before the authority read, as on the native path.\n const observedAt = (options.now ?? Date.now)()\n let evidence: StaleTurnLockOwnerProbeResult\n try { evidence = await owner.probe(owner.identity) }\n catch (error) { return { released: false, diagnostics: { ownerStatus: 'unknown', ownerProbeError: messageOf(error) } } }\n const keys = ['workspaceId', 'threadId', 'scope', 'executionId', 'lockId', 'turnStreamId'] as const\n if (!evidence?.identity || keys.some(key => evidence.identity[key] !== owner.identity[key])) {\n return { released: false, diagnostics: { ownerStatus: 'unknown', releaseWithheld: 'OWNER_IDENTITY_MISMATCH' } }\n }\n const status = evidence.status === 'abandoned' || evidence.status === 'live' ? evidence.status : 'unknown'\n const diagnostics = { ...(evidence.diagnostics ?? {}), ownerStatus: status }\n if (status !== 'abandoned') return { released: false, diagnostics }\n const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n if (lockAgeMs < terminalGraceMs) return { released: false, diagnostics: {\n ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, releaseWithheld: 'LOCK_WITHIN_TERMINAL_GRACE_PERIOD',\n } }\n const released = await options.release({ observedAt })\n return { released, diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, observedAt, released } }\n}\n\n/**\n * The fallback: the session authority could not attest to the execution's\n * state because the box is gone, stopped, or unreachable. Release the lock\n * once it is old enough that it cannot belong to a turn still provisioning its\n * box — and say so either way, with the reason, the lock's age, and the grace\n * period it was measured against.\n *\n * One clock read (`at`) serves as the age gate AND the release fence here too,\n * for the same reason the terminal branch uses `observedAt` for both.\n */\nasync function forceReleaseUnreachable(\n options: ReconcileStaleTurnLockOptions,\n reason: Record<string, unknown> & { unreachableReason: string },\n): Promise<ReconcileStaleTurnLockResult> {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const graceMs = options.graceMs ?? DEFAULT_STALE_TURN_LOCK_GRACE_MS\n const at = (options.now ?? Date.now)()\n const lockAgeMs = at - options.lockStartedAt\n const diagnostics: Record<string, unknown> = {\n ...reason,\n sandboxReachable: false,\n lockAgeMs,\n forceReleaseGraceMs: graceMs,\n }\n\n if (lockAgeMs < graceMs) {\n log('[chat-routes] stale turn lock held: sandbox unreachable but lock is inside the grace period', {\n ...(options.context ?? {}),\n ...diagnostics,\n })\n return { released: false, diagnostics: { ...diagnostics, forceReleaseWithheld: 'LOCK_WITHIN_GRACE_PERIOD' } }\n }\n\n const released = await options.release({ observedAt: at })\n log('[chat-routes] force-released stale turn lock: sandbox unreachable, no turn can be executing', {\n ...(options.context ?? {}),\n ...diagnostics,\n released,\n })\n return { released, diagnostics: { ...diagnostics, forceReleased: released } }\n}\n","/**\n * Worker adapters for durable turn storage, single-flight locks, and workspace signals.\n * Namespace interfaces remain structural so Cloudflare bindings and the memory harness\n * run the same authenticated request path.\n * Products provide workspace authorization and their binding's TURN_STREAM_AUTH_SECRET.\n */\n\nimport { connectDurableTurnCancellation, type TurnCancellationConnection, type TurnCancellationIdentity } from './cancellation'\nimport { reconcileStaleTurnLock, type ReconcileStaleTurnLockOptions, type StaleTurnLockOwnerProbeResult } from '../chat-routes/stale-turn-lock'\nimport type { TurnEventStore, TurnStatus } from '../stream/turn-buffer'\nimport {\n TURN_STREAM_PATHS,\n TURN_STREAM_TOKEN_HEADER,\n mintTurnStreamToken,\n scopeIndexChannelKey,\n turnLockChannelKey,\n turnStorageChannelKey,\n workspaceChannelKey,\n type DurableTurnLock,\n type TurnLockAcquireResult,\n type TurnLockReleaseInput,\n type TurnLockInterruptedReleaseInput,\n type TurnLockScope,\n type TurnStreamEvent,\n type TurnStreamTokenClaims,\n} from './core'\n\n// ── structural namespace ────────────────────────────────────────────────────\n\n/** Resolve a stub interface for handling fetch requests with optional initialization parameters */\nexport interface TurnStreamStubLike {\n fetch(input: Request | string, init?: RequestInit): Promise<Response>\n}\n\n/** Cloudflare placement hints. A hint affects only a channel's first creation, never an existing object's location. */\nexport type TurnStreamLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me'\n\n/** The default matches the application D1 region unless its binding descriptor names another region. */\nexport const DEFAULT_TURN_LOCK_LOCATION_HINT: TurnStreamLocationHint = 'enam'\n\n/** The surface of `DurableObjectNamespace` the adapters use. */\nexport interface TurnStreamNamespaceLike {\n idFromName(name: string): unknown\n get(id: unknown, options?: { locationHint?: string }): TurnStreamStubLike\n}\n\nconst INTERNAL_ORIGIN = 'https://turn-stream.internal'\n\n/** The HMAC secret shared between this worker and its `TurnStreamDO` binding.\n * Every adapter call mints a channel-bound capability token from it; the DO\n * refuses requests without one (issue #746). Products pass the same value\n * the DO resolves — `env.TURN_STREAM_AUTH_SECRET`. */\nexport interface TurnStreamAuth {\n secret: string\n}\n\nasync function postJson<T>(\n namespace: TurnStreamNamespaceLike,\n channelKey: string,\n path: string,\n body: unknown,\n auth: TurnStreamAuth,\n claims?: TurnStreamTokenClaims,\n): Promise<{ status: number; body: T }> {\n const stub = namespace.get(namespace.idFromName(channelKey))\n const response = await stub.fetch(`${INTERNAL_ORIGIN}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(channelKey, auth.secret, undefined, undefined, claims),\n },\n body: JSON.stringify(body),\n })\n return { status: response.status, body: (await response.json()) as T }\n}\n\nasync function postJsonOk<T>(\n namespace: TurnStreamNamespaceLike,\n channelKey: string,\n path: string,\n body: unknown,\n auth: TurnStreamAuth,\n claims?: TurnStreamTokenClaims,\n): Promise<T> {\n const result = await postJson<T>(namespace, channelKey, path, body, auth, claims)\n if (result.status !== 200) {\n throw new Error(`turn-stream ${path} failed with status ${result.status}`)\n }\n return result.body\n}\n\n// ── TurnEventStore adapter (the real turnStore) ─────────────────────────────\n\n/**\n * Optional Durable Object backend for {@link TurnEventStore}.\n * Each turn has its own named instance; a per-scope index tracks running turns.\n * Products choose this adapter or the D1 backend independently of their lock\n * and workspace-signal transport.\n */\nexport function createDurableObjectTurnEventStore(\n namespace: TurnStreamNamespaceLike,\n auth: TurnStreamAuth,\n): TurnEventStore {\n return {\n async append(turnId, events) {\n if (!events.length) return\n await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events }, auth)\n },\n async read(turnId, fromSeq) {\n const body = await postJsonOk<{ events: Array<{ seq: number; event: string }> }>(\n namespace,\n turnStorageChannelKey(turnId),\n TURN_STREAM_PATHS.turnEventsRead,\n { fromSeq },\n auth,\n )\n return body.events\n },\n async setStatus(turnId, status, scopeId, options) {\n // This store keeps no update time to preserve or compare; refuse rather than write unguarded.\n if (options?.preserveUpdatedAt || options?.onlyIfRunningBefore !== undefined) {\n throw new Error('The turn-stream Durable Object store does not support guarded or time-preserving status writes')\n }\n await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status }, auth)\n if (scopeId) {\n await postJsonOk(namespace, scopeIndexChannelKey(scopeId), TURN_STREAM_PATHS.scopeStatusSet, {\n turnId,\n status,\n }, auth)\n }\n },\n async getStatus(turnId) {\n const body = await postJsonOk<{ status: TurnStatus | null }>(\n namespace,\n turnStorageChannelKey(turnId),\n TURN_STREAM_PATHS.turnStatusGet,\n {},\n auth,\n )\n return body.status\n },\n async listRunning(scopeId) {\n const body = await postJsonOk<{ running: string[] }>(\n namespace,\n scopeIndexChannelKey(scopeId),\n TURN_STREAM_PATHS.scopeRunningList,\n {},\n auth,\n )\n return body.running\n },\n }\n}\n\n// ── lock primitives (usable outside the route seam too) ─────────────────────\n\n/** Define input parameters required to acquire a durable turn lock in a workspace thread context */\nexport interface AcquireDurableTurnLockInput {\n workspaceId: string\n threadId: string\n scope: TurnLockScope\n executionId: string\n turnId?: string\n /** Supply to reclaim/retry with a stable id; default mints a UUID. */\n lockId?: string\n cancellation?: { turnStreamId: string }\n}\n\n/** Acquire a durable turn lock in the specified namespace with given input parameters */\nexport async function acquireDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: AcquireDurableTurnLockInput,\n auth: TurnStreamAuth,\n): Promise<TurnLockAcquireResult> {\n const lockId = input.lockId ?? crypto.randomUUID()\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n const result = await postJson<TurnLockAcquireResult>(namespace, key, TURN_STREAM_PATHS.lockAcquire, {\n ...input,\n lockId,\n }, auth)\n if (result.status !== 200 && result.status !== 409) {\n throw new Error(`turn-stream lock acquire failed with status ${result.status}`)\n }\n return result.body\n}\n\n/**\n * Read a channel's active turn lock without changing it.\n *\n * The first request to a Durable Object that has never been used creates it,\n * which measured 1.3-2.4 s for a thread's first turn in GTM production\n * against 0.05-0.33 s once it exists; every lock now lives on the\n * workspace channel, which exists after the workspace's first turn. A peek\n * sent as soon as a turn is admitted wakes that object if it was evicted.\n */\nexport async function peekDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: { workspaceId: string } & ({ scope: 'workspace'; threadId?: string } | { scope: TurnLockScope; threadId: string }),\n auth: TurnStreamAuth,\n): Promise<DurableTurnLock | null> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId ?? '', input.scope)\n const result = await postJson<{ active?: DurableTurnLock | null }>(namespace, key, TURN_STREAM_PATHS.lockPeek, {\n scope: input.scope,\n threadId: input.threadId,\n }, auth)\n if (result.status !== 200) throw new Error(`turn-stream lock peek failed with status ${result.status}`)\n return result.body.active ?? null\n}\n\n/** Release a durable turn lock and indicate if the release was successful or deferred */\nexport async function releaseDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: TurnLockReleaseInput,\n auth: TurnStreamAuth,\n): Promise<{ released: boolean; deferred?: boolean }> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth)\n}\n\n/** Define input parameters to release an interrupted durable turn lock in a workspace or thread */\nexport type ReleaseInterruptedDurableTurnLockInput = TurnLockInterruptedReleaseInput\n\n/** Fenced out-of-band release — the DO refuses a successor lock (started\n * after `interruptedAt`) and a turnId mismatch. Returns whether any scope\n * released. */\nexport async function releaseInterruptedDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: ReleaseInterruptedDurableTurnLockInput,\n auth: TurnStreamAuth,\n): Promise<boolean> {\n const scopes: readonly TurnLockScope[] = input.scope ? [input.scope] : ['workspace', 'thread']\n for (const scope of scopes) {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, scope)\n const result = await postJsonOk<{ released: boolean }>(namespace, key, TURN_STREAM_PATHS.lockReleaseInterrupted, {\n scope,\n threadId: input.threadId,\n interruptedAt: input.interruptedAt,\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.recovery ? { recovery: input.recovery } : {}),\n }, auth, input.recovery ? { purpose: 'turn-recovery', identity: input.recovery } : undefined)\n if (result.released) return true\n }\n return false\n}\n\n// ── stale-lock reconciliation against the DO ────────────────────────────────\n\n/** Define options to reconcile stale durable turn locks with context, namespace, workspace, and active lock details */\nexport interface ReconcileStaleDurableTurnLockOptions\n extends Pick<\n ReconcileStaleTurnLockOptions,\n 'probeSandbox' | 'probeSession' | 'graceMs' | 'terminalGraceMs' | 'context' | 'log' | 'now'\n > {\n namespace: TurnStreamNamespaceLike\n auth: TurnStreamAuth\n workspaceId: string\n threadId: string\n /** The lock the acquire attempt was refused on. */\n active: DurableTurnLock\n /** Cancellable Router locks require positive exact outer + child quiescence; native-only probes cannot attest it. */\n probeOwner?(identity: TurnCancellationIdentity): Promise<StaleTurnLockOwnerProbeResult>\n}\n\n/**\n * `/chat-routes`' `reconcileStaleTurnLock` policy wired to the DO: the\n * product supplies the probes (which box, what its session says), the policy\n * decides, and a release lands as a FENCED interrupted release —\n * `interruptedAt` is the policy's `fence.observedAt`, so a successor lock\n * acquired while the probes were in flight survives by construction.\n */\nexport async function reconcileStaleDurableTurnLock(\n options: ReconcileStaleDurableTurnLockOptions,\n): Promise<{ released: boolean; diagnostics: Record<string, unknown> }> {\n const { namespace, auth, workspaceId, threadId, active, probeOwner, ...policy } = options\n const owner = active.cancellation ? { workspaceId: active.workspaceId, threadId: active.threadId, scope: active.scope,\n executionId: active.executionId, lockId: active.lockId, turnStreamId: active.cancellation.turnStreamId } : undefined\n return reconcileStaleTurnLock({\n ...policy,\n lockStartedAt: active.startedAt,\n ...(owner ? { owner: { identity: owner,\n probe: probeOwner ?? (async (identity: TurnCancellationIdentity) => ({ identity, status: 'unknown' as const })) } } : {}),\n release: (fence) =>\n releaseInterruptedDurableTurnLock(namespace, {\n workspaceId,\n threadId: active.threadId,\n scope: active.scope,\n interruptedAt: fence.observedAt,\n ...(active.turnId ? { turnId: active.turnId } : {}),\n ...(owner ? { recovery: owner } : {}),\n }, auth),\n })\n}\n\n// ── ChatTurnLock adapter (the turnLock seam) ────────────────────────────────\n\n/** The subset of `ChatTurnProduceArgs` the lock adapter reads — structural,\n * so this module needs no import from `/chat-routes/turn-routes` (which\n * would drag the `agent-runtime` peer into every `/turn-stream` consumer). */\nexport interface TurnLockSeamArgs<TContext> {\n identity: { tenantId: string; sessionId: string }\n executionId: string\n turnStreamId?: string\n context: TContext\n body: { turnId?: string }\n}\n\n/** Verdict shape of the vertical's `turnLock.acquire`. */\nexport type TurnLockSeamResult =\n | { acquired: true; handle?: unknown; cancellation?: TurnCancellationConnection }\n | { acquired: false; response: Response }\n\n/** Define options for creating a durable turn lock with customizable scope and identification methods */\nexport interface CreateDurableTurnLockOptions<TContext> {\n /** New channels use this hint; existing channel IDs and locations are preserved. */\n locationHint?: TurnStreamLocationHint\n namespace: TurnStreamNamespaceLike\n /** Capability tokens for the DO; pass the worker's\n * `env.TURN_STREAM_AUTH_SECRET`. The DO validates every request. */\n auth: TurnStreamAuth\n /** Which lane serializes this turn: `'workspace'` (shared sandbox — one\n * turn per workspace) or `'thread'` (router lane — one turn per thread). */\n scopeOf(args: TurnLockSeamArgs<TContext>): TurnLockScope\n /** Opt the existing lock into durable Stop. Leave native/durable completion lanes on their existing owner. */\n cancellationOf?(args: TurnLockSeamArgs<TContext>): boolean\n /** Override the execution id the lock records (e.g. a follow-up reclaiming\n * the execution it already dispatched). Default: the turn's own. */\n lockExecutionIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /** Client turn id recorded on the lock (fences interrupted releases to the\n * right turn). Default: the request body's `turnId`. */\n clientTurnIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /**\n * Attempt stale-lock recovery after a refused acquire. Return whether the\n * held lock was released (the adapter then retries the acquire once).\n * Products wire {@link reconcileStaleDurableTurnLock} with their sandbox +\n * session probes here. Omit → a refused acquire is final.\n */\n reconcile?(\n args: TurnLockSeamArgs<TContext>,\n active: DurableTurnLock,\n ): Promise<{ released: boolean; diagnostics?: Record<string, unknown> }>\n /** Build the refusal `Response`. Default: a 409 with the shared body shape\n * (`code`, `message`, lock identity + age, reconcile diagnostics). */\n onRefused?(active: DurableTurnLock, diagnostics: Record<string, unknown> | undefined): Response\n}\n\nfunction defaultRefusalResponse(\n active: DurableTurnLock,\n diagnostics: Record<string, unknown> | undefined,\n): Response {\n const workspaceConflict = active.scope === 'workspace'\n return Response.json(\n {\n error: {\n code: workspaceConflict ? 'workspace_turn_in_flight' : 'chat_turn_in_flight',\n message: workspaceConflict\n ? 'A chat turn is already running for this workspace. Wait for it to finish before starting another.'\n : 'A chat turn is already running for this thread. Reconnect to the active response or wait for it to finish.',\n threadId: active.threadId,\n executionId: active.executionId,\n ...(active.turnId ? { turnId: active.turnId } : {}),\n lockStartedAt: active.startedAt,\n lockAgeMs: Date.now() - active.startedAt,\n ...(diagnostics ? { diagnostics } : {}),\n },\n },\n { status: 409 },\n )\n}\n\n/**\n * The vertical's `turnLock` seam on the shared DO: dual-scope single-flight\n * acquire (with one reconcile-then-retry pass when the product supplies a\n * stale-lock reconciler) and cooperative release on settle. The returned\n * object satisfies `createChatTurnRoutes`' `ChatTurnLock<TContext>`\n * structurally.\n */\nexport function createDurableTurnLock<TContext>(options: CreateDurableTurnLockOptions<TContext>): {\n acquire(args: TurnLockSeamArgs<TContext>): Promise<TurnLockSeamResult>\n release(handle: unknown): Promise<void>\n warm(target: { tenantId: string; threadId?: string }): Promise<void>\n} {\n const namespace: TurnStreamNamespaceLike = {\n idFromName: name => options.namespace.idFromName(name),\n get: (id, init) => options.namespace.get(id, {\n ...init, locationHint: options.locationHint ?? DEFAULT_TURN_LOCK_LOCATION_HINT,\n }),\n }\n return {\n // Every lock lives on the workspace channel, so this wakes that object\n // (evicted after idle) before the turn's acquire reaches it.\n async warm(target) {\n await peekDurableTurnLock(namespace, target.threadId\n ? { workspaceId: target.tenantId, threadId: target.threadId, scope: 'thread' }\n : { workspaceId: target.tenantId, scope: 'workspace' }, options.auth)\n },\n async acquire(args) {\n const workspaceId = args.identity.tenantId\n const threadId = args.identity.sessionId\n const scope = options.scopeOf(args)\n const executionId = options.lockExecutionIdOf?.(args) ?? args.executionId\n const turnId = options.clientTurnIdOf ? options.clientTurnIdOf(args) : args.body.turnId\n const cancellable = options.cancellationOf?.(args) === true\n if (cancellable && !args.turnStreamId) throw new Error('Durable cancellation requires the route turnStreamId')\n const input: AcquireDurableTurnLockInput = {\n workspaceId,\n threadId,\n scope,\n executionId,\n ...(turnId ? { turnId } : {}),\n ...(cancellable ? { cancellation: { turnStreamId: args.turnStreamId! } } : {}),\n }\n\n let acquired = await acquireDurableTurnLock(namespace, input, options.auth)\n let diagnostics: Record<string, unknown> | undefined\n if (!acquired.acquired && options.reconcile) {\n const reconciled = await options.reconcile(args, acquired.active)\n diagnostics = reconciled.diagnostics\n if (reconciled.released) {\n acquired = await acquireDurableTurnLock(namespace, input, options.auth)\n }\n }\n if (!acquired.acquired) {\n return {\n acquired: false,\n response: (options.onRefused ?? defaultRefusalResponse)(acquired.active, diagnostics),\n }\n }\n const handle: TurnLockReleaseInput = {\n workspaceId,\n threadId,\n scope,\n executionId,\n lockId: acquired.lock.lockId,\n }\n if (!cancellable) return { acquired: true, handle }\n try {\n const cancellation = await connectDurableTurnCancellation(options.namespace,\n { ...handle, turnStreamId: args.turnStreamId! }, options.auth)\n return { acquired: true, handle, cancellation }\n } catch (error) {\n // No producer may run without its control connection. Release only this newly acquired generation.\n await releaseDurableTurnLock(options.namespace, handle, options.auth)\n throw error\n }\n },\n async release(handle) {\n if (!handle) return\n await releaseDurableTurnLock(namespace, handle as TurnLockReleaseInput, options.auth)\n },\n }\n}\n\n// ── broadcast helpers (products wire these into onEvent) ────────────────────\n\n/** Coarse per-workspace marker that a thread's turn started / ended — drives\n * a sidebar \"agent responding\" indicator subscribed once per workspace. */\nexport async function broadcastWorkspaceActivity(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n threadId: string,\n phase: 'start' | 'end',\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.activity',\n timestamp: Date.now(),\n data: { threadId, phase, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the indicator is non-critical UI.\n }\n}\n\n/** Per-workspace marker that a new thread was created, so an already-open\n * history list prepends it without a reload. */\nexport async function broadcastThreadCreated(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n thread: { threadId: string; title: string },\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.created',\n timestamp: Date.now(),\n data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the loader reconciles on the next revalidation.\n }\n}\n\n// ── WebSocket upgrade forwarder (worker entry) ──────────────────────────────\n\n/** Represent success or failure of a TURN stream upgrade authorization with optional response data */\nexport type TurnStreamUpgradeAuthorization = { ok: true } | { ok: false; response: Response }\n\n/** Define options for creating a TURN stream upgrade handler including namespace, path, and authorization logic */\nexport interface CreateTurnStreamUpgradeHandlerOptions {\n namespace: TurnStreamNamespaceLike\n /** HMAC secret shared with the DO binding (`env.TURN_STREAM_AUTH_SECRET`).\n * After the product `authorize` passes, the handler mints a channel-bound\n * capability token and the DO verifies it — the browser never holds it. */\n authSecret: string\n /** The worker route serving the stream. Default `/api/session-stream`. */\n path?: string\n /** Viewer access check (session cookie → workspace membership). */\n authorize(\n request: Request,\n target: { workspaceId: string },\n ): Promise<TurnStreamUpgradeAuthorization>\n}\n\n/**\n * The worker-entry WebSocket forwarder — WORKSPACE channel only (the\n * per-thread variant went with the deprecated rebroadcast lane; a thread's\n * live turn replay is the sandbox session gateway's job). Call BEFORE the\n * app router (a router loader cannot return a 101); returns `null` for\n * requests that are not a WebSocket upgrade on the configured path.\n *\n * GET {path}?workspaceId=... → workspace channel (sidebar signals)\n *\n * After the 101, the client sends `{type:'sync'}` and receives the\n * current-activity + recent-threads snapshot, then live signals.\n *\n * Security: the product's `authorize` decides whether THIS caller may see the\n * workspace's signals; the channel-bound token this handler then mints is\n * what the DO itself verifies — two independent gates, and the browser never\n * learns the token (it rides the forwarded upgrade request only).\n */\nexport function createTurnStreamUpgradeHandler(\n options: CreateTurnStreamUpgradeHandlerOptions,\n): (request: Request) => Promise<Response | null> {\n const path = options.path ?? '/api/session-stream'\n if (!options.authSecret || options.authSecret.length < 32) {\n throw new Error('createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) — the DO fails closed without tokens')\n }\n return async (request) => {\n const url = new URL(request.url)\n if (url.pathname !== path || request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') return null\n\n if (url.searchParams.has('threadId')) {\n return new Response('Thread replay uses the sandbox session gateway or chat replay route', { status: 400 })\n }\n const workspaceId = url.searchParams.get('workspaceId')\n if (!workspaceId) return new Response('Missing workspaceId', { status: 400 })\n\n const auth = await options.authorize(request, { workspaceId })\n if (!auth.ok) return auth.response\n\n const key = workspaceChannelKey(workspaceId)\n const stub = options.namespace.get(options.namespace.idFromName(key))\n\n const forwardUrl = new URL(request.url)\n forwardUrl.searchParams.set('sessionId', workspaceId)\n forwardUrl.searchParams.set('scope', 'workspace')\n forwardUrl.searchParams.delete('token')\n const headers = new Headers(request.headers)\n headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret))\n return stub.fetch(new Request(new Request(forwardUrl, request), { headers }))\n }\n}\n"],"mappings":";;;;;;;AAoCO,IAAM,2BAA2B;AAIjC,IAAM,2BAA2B;AAQxC,SAAS,uBAAuB,QAAuC;AACrE,QAAM,EAAE,UAAU,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E,YAAY,CAAC;AAC7D,QAAI,CAAC,KAAK,GAAI,QAAO,KAAK;AAE1B,UAAM,MAAM,oBAAoB,WAAW;AAC3C,UAAM,OAAO,QAAQ,UAAU,IAAI,QAAQ,UAAU,WAAW,GAAG,CAAC;AAEpE,UAAM,aAAa,IAAI,IAAI,QAAQ,GAAG;AACtC,eAAW,aAAa,IAAI,aAAa,WAAW;AACpD,eAAW,aAAa,IAAI,SAAS,WAAW;AAChD,eAAW,aAAa,OAAO,OAAO;AACtC,UAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,YAAQ,IAAI,0BAA0B,MAAM,oBAAoB,KAAK,QAAQ,UAAU,CAAC;AACxF,WAAO,KAAK,MAAM,IAAI,QAAQ,IAAI,QAAQ,YAAY,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC9E;AACF;","names":[]}
@@ -174,4 +174,4 @@ export {
174
174
  assignRolloutArm,
175
175
  decideRollout
176
176
  };
177
- //# sourceMappingURL=chunk-7VTGB4DM.js.map
177
+ //# sourceMappingURL=chunk-OSMMEMDH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rollout/index.ts"],"sourcesContent":["/**\n * Rollout guard: a staged rollout widens only when the stage it leaves met\n * that stage's kill lines on measured production numbers.\n *\n * WHY. Hospitality's routed lane widened from two QA workspaces to `*` at a\n * first-words p50 of 3.54 s, past kill lines of 2.5 s and 3.0 s\n * (hospitality-agent #382). The numbers existed; nothing read them\n * before the list changed. This module is the one place that reads them.\n *\n * THE LIST. A rollout is one comma-separated value, usually a deploy variable\n * such as `HOSPITALITY_ROUTED_BUSINESS_IDS`: workspace ids, `*` for every\n * workspace, `!<id>` to keep one out whatever else matches, and\n * `new-since:<ISO time>` for workspaces created at or after that time.\n * {@link rolloutAdmits} is the reference reading of that grammar.\n *\n * THE RULE ({@link decideRollout}).\n * - Narrowing is always allowed. Holds and widenings measure the current stage.\n * - A widening must land on a declared stage, the next one after the current\n * value's stage, never past it.\n * - The stage being left must have at least `minSamples` measured turns and\n * every kill line met. A missing metric leaves the decision undecided.\n * - Missing samples are undecided; a measured breach names each reason (`first_words_p50_ms 3540 over kill line 2500`).\n * - A hold given `liveSince` (when the deployed commit went live) judges only turns served since then: it refuses\n * a breach only when the measurement's window starts at or after it, and is otherwise undecided. A deploy that\n * keeps the list is never refused on turns the previous deploy already served (Legal, 2026-10-22, run 39714417347).\n *\n * Every decision, allowed, refused or undecided, is returned as one record the caller\n * persists (the CLI appends it to a JSONL ledger and hands it to the\n * config's `record`).\n */\n\n/** A kill line: the measured value must stay at or under `max` and at or over `min`. */\nexport interface RolloutKillLine {\n max?: number\n min?: number\n}\n\nexport interface RolloutStage {\n /** Short name used in refusals and records, e.g. `qa`, `all-but-recenter`. */\n name: string\n /** The exact list value that defines this stage. */\n value: string\n /** Turns the stage must have served, measured, before the rollout may leave it. */\n minSamples: number\n /** Metric name → line. Metric names are the product's, e.g. `first_words_p50_ms`, `failure_rate`. */\n kill: Record<string, RolloutKillLine>\n}\n\nexport interface RolloutPlan {\n /** e.g. `hospitality-routed-chat`. */\n name: string\n /** The deploy variable that carries the list, e.g. `HOSPITALITY_ROUTED_BUSINESS_IDS`. */\n variable: string\n /** In widening order. */\n stages: RolloutStage[]\n}\n\n/** Production numbers for one stage, from the product's own instrument. */\nexport interface StageMeasurement {\n stage: string\n samples: number\n /** Lane name for the stage sample floor; defaults to the stage name. */\n lane?: string\n /** Additional lane sample floors, evaluated as missing evidence rather than breaches. */\n sampleRequirements?: Record<string, { samples: number; minSamples: number }>\n metrics: Record<string, number | null | undefined>\n /** Where the numbers came from (ledger, query, soak), for the record. */\n source?: string\n window?: { from: string; to: string }\n}\n\nexport interface RolloutDecision {\n rollout: string\n variable: string\n from: { value: string; stage: string | null }\n to: { value: string; stage: string | null }\n widens: boolean\n decision: 'allowed' | 'refused' | 'undecided'\n recommendation: 'widen' | 'hold' | 'narrow' | 'refuse'\n turnsNeeded: Record<string, number>\n /** Breaches or evidence deficits, including observations made while narrowing. */\n reasons: string[]\n measured: StageMeasurement | null\n at: string\n}\n\nexport interface ParsedRolloutList {\n all: boolean\n ids: ReadonlySet<string>\n excluded: ReadonlySet<string>\n /** Epoch ms of each `new-since:` entry. */\n newSince: readonly number[]\n}\n\nexport function parseRolloutList(value: string | null | undefined): ParsedRolloutList {\n const ids = new Set<string>()\n const excluded = new Set<string>()\n const newSince: number[] = []\n let all = false\n for (const raw of (value ?? '').split(',')) {\n const entry = raw.trim()\n if (!entry) continue\n if (entry === '*') all = true\n else if (entry.startsWith('!')) excluded.add(entry.slice(1).trim())\n else if (entry.startsWith('new-since:')) {\n const at = Date.parse(entry.slice('new-since:'.length))\n if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`)\n newSince.push(at)\n } else ids.add(entry)\n }\n return { all, ids, excluded, newSince }\n}\n\n/** Whether a list admits one workspace. `createdAt` (epoch ms) is needed only for `new-since:` entries. */\nexport function rolloutAdmits(value: string | ParsedRolloutList, workspace: { id: string; createdAt?: number }): boolean {\n const list = typeof value === 'string' ? parseRolloutList(value) : value\n if (list.excluded.has(workspace.id)) return false\n if (list.all || list.ids.has(workspace.id)) return true\n return workspace.createdAt !== undefined && list.newSince.some(at => workspace.createdAt! >= at)\n}\n\n/**\n * Whether `to` may admit a workspace `from` does not. Conservative: a change it\n * cannot prove narrower counts as a widening.\n */\nexport function rolloutWidens(fromValue: string, toValue: string): boolean {\n const from = parseRolloutList(fromValue)\n const to = parseRolloutList(toValue)\n if (to.all) {\n if (!from.all) return true\n // Under `*` on both sides, only a dropped exclusion widens.\n return [...from.excluded].some(id => !to.excluded.has(id))\n }\n if ([...to.ids].some(id => !rolloutAdmits(from, { id }))) return true\n // An id `from` admitted only because it was listed, which `to` now excludes, narrows; nothing else here widens.\n const earliest = (list: ParsedRolloutList) => list.newSince.length ? Math.min(...list.newSince) : Infinity\n if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true\n return false\n}\n\n/** Canonical form for matching a value to a stage: entries trimmed and sorted. */\nexport function normalizeRolloutValue(value: string): string {\n return value.split(',').map(entry => entry.trim()).filter(Boolean).sort().join(',')\n}\n\nfunction stageOf(plan: RolloutPlan, value: string): RolloutStage | null {\n const key = normalizeRolloutValue(value)\n return plan.stages.find(stage => normalizeRolloutValue(stage.value) === key) ?? null\n}\n\n/** Finite measured breaches only. Missing observations and sample floors are evidence deficits. */\nexport function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[] {\n if (!measured || measured.stage !== stage.name) return []\n return Object.entries(stage.kill).flatMap(([metric, line]) => {\n const value = measured.metrics[metric]\n if (typeof value !== 'number' || !Number.isFinite(value)) return []\n return [\n ...(line.max !== undefined && value > line.max ? [`${metric} ${value} over kill line ${line.max}`] : []),\n ...(line.min !== undefined && value < line.min && !metric.endsWith('samples') ? [`${metric} ${value} under kill line ${line.min}`] : []),\n ]\n })\n}\n\nexport function validateRolloutPlan(plan: RolloutPlan): void {\n if (!plan.name || !plan.variable) throw new Error('a rollout plan needs a name and a variable')\n if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`)\n const names = new Set<string>()\n const values = new Set<string>()\n for (const stage of plan.stages) {\n if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`)\n names.add(stage.name)\n const value = normalizeRolloutValue(stage.value)\n if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`)\n values.add(value)\n parseRolloutList(stage.value)\n if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {\n throw new Error(`stage ${stage.name} needs minSamples of at least 1`)\n }\n if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`)\n }\n for (let index = 1; index < plan.stages.length; index++) {\n const previous = plan.stages[index - 1]!\n const stage = plan.stages[index]!\n if (!rolloutWidens(previous.value, stage.value)) {\n throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`)\n }\n }\n}\n\n/** Stable per-turn percentage assignment; the product records the returned arm on its row and trace. */\nexport function assignRolloutArm(turnId: string, treatmentPct: number): 'control' | 'treatment' {\n if (!Number.isFinite(treatmentPct) || treatmentPct < 0 || treatmentPct > 100) {\n throw new RangeError('treatmentPct must be between 0 and 100')\n }\n let hash = 2166136261\n for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619)\n return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? 'treatment' : 'control'\n}\n\nconst DEFAULT_MEASUREMENT_TIMEOUT_MS = 5_000\n\n/** Measure the current stage for widening, holding and narrowing. Narrowing always remains available. */\nexport async function decideRollout(input: {\n plan: RolloutPlan\n fromValue: string\n toValue: string\n /** `scope.since` (epoch ms) is set for a hold given `liveSince`: measure the turns at or after it. */\n measure(stage: RolloutStage, signal?: AbortSignal, scope?: { since?: number }): Promise<StageMeasurement | null>\n /** Bound observation even when the product instrument ignores cancellation. */\n measurementTimeoutMs?: number\n /** Epoch ms the deployed commit went live. A hold refuses only a breach measured on turns since then. */\n liveSince?: number\n now?: () => Date\n}): Promise<RolloutDecision> {\n const { plan, fromValue, toValue } = input\n validateRolloutPlan(plan)\n const fromStage = stageOf(plan, fromValue)\n const toStage = stageOf(plan, toValue)\n const widens = rolloutWidens(fromValue, toValue)\n const narrowing = !widens && normalizeRolloutValue(fromValue) !== normalizeRolloutValue(toValue)\n const holdSince = !widens && !narrowing && Number.isFinite(input.liveSince) ? input.liveSince : undefined\n const record = (decision: RolloutDecision['decision'], reasons: string[], measured: StageMeasurement | null,\n turnsNeeded: Record<string, number> = {}, breach = false): RolloutDecision => ({\n rollout: plan.name, variable: plan.variable,\n from: { value: fromValue, stage: fromStage?.name ?? null },\n to: { value: toValue, stage: toStage?.name ?? null }, widens, decision,\n recommendation: narrowing || breach ? 'narrow' : decision === 'refused' ? 'refuse' : decision === 'undecided' ? 'hold' : widens ? 'widen' : 'hold',\n turnsNeeded, reasons, measured, at: (input.now?.() ?? new Date()).toISOString(),\n })\n if (widens) {\n if (!toStage) return record('refused', [`${toValue} is not a declared stage of ${plan.name}`], null)\n const target = plan.stages.indexOf(toStage)\n if (!fromStage) {\n const empty = !normalizeRolloutValue(fromValue)\n return empty && target === 0 ? record('allowed', [], null)\n : record('refused', [`the current value ${fromValue || '(empty)'} is not a declared stage of ${plan.name}`], null)\n }\n const current = plan.stages.indexOf(fromStage)\n if (target > current + 1) return record('refused', [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map(stage => stage.name).join(', ')}`], null)\n }\n if (!fromStage) return record('allowed', [], null)\n const timeoutMs = input.measurementTimeoutMs ?? DEFAULT_MEASUREMENT_TIMEOUT_MS\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError('measurementTimeoutMs must be positive')\n const abort = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let measured: StageMeasurement | null\n try {\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const error = new Error('measurement timed out')\n abort.abort(error)\n reject(error)\n }, timeoutMs)\n })\n measured = await Promise.race([input.measure(fromStage, abort.signal, holdSince === undefined ? undefined : { since: holdSince }), deadline])\n }\n catch (error) {\n return record(narrowing ? 'allowed' : 'undecided', [`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null,\n { [fromStage.name]: fromStage.minSamples })\n } finally {\n clearTimeout(timer)\n }\n const lane = measured?.lane ?? fromStage.name\n const requirements = { ...measured?.sampleRequirements }\n requirements[lane] = {\n samples: Math.min(measured?.samples ?? 0, requirements[lane]?.samples ?? Infinity),\n minSamples: Math.max(fromStage.minSamples, requirements[lane]?.minSamples ?? 0),\n }\n // Older product configs expressed control floors as *_samples minimum kill lines.\n for (const [metric, line] of Object.entries(fromStage.kill)) {\n if (metric.endsWith('samples') && line.min !== undefined) {\n requirements[metric] = { samples: measured?.metrics[metric] ?? 0, minSamples: line.min }\n }\n }\n const turnsNeeded = Object.fromEntries(Object.entries(requirements)\n .map(([lane, floor]) => [lane, Math.max(0, Math.ceil(floor.minSamples - (Number.isFinite(floor.samples) ? floor.samples : 0)))] as const)\n .filter(([, needed]) => needed > 0))\n const measuredStage = measured?.stage === fromStage.name\n const breaches = killLineBreaches(fromStage, measured)\n const missing = !measuredStage ? [`stage ${fromStage.name} has no matching measurement`]\n : Object.keys(fromStage.kill).filter(metric => !Number.isFinite(measured!.metrics[metric])).map(metric => `${metric} was not measured`)\n const windowFrom = Date.parse(measured?.window?.from ?? '')\n const stale = holdSince !== undefined && breaches.length > 0 && !(windowFrom >= holdSince)\n ? [`the breach was measured on turns from ${measured?.window?.from ?? 'an unstated time'}, before the deployed commit went live at ${new Date(holdSince).toISOString()}; only turns since then can refuse a hold`]\n : []\n const reasons = [...breaches, ...stale, ...missing, ...Object.entries(turnsNeeded).map(([lane, needed]) => `${lane} needs ${needed} more turns`)]\n return record(narrowing ? 'allowed' : breaches.length && !stale.length ? 'refused' : reasons.length ? 'undecided' : 'allowed', reasons, measured, turnsNeeded, breaches.length > 0)\n}\n"],"mappings":";AA8FO,SAAS,iBAAiB,OAAqD;AACpF,QAAM,MAAM,oBAAI,IAAY;AAC5B,QAAM,WAAW,oBAAI,IAAY;AACjC,QAAM,WAAqB,CAAC;AAC5B,MAAI,MAAM;AACV,aAAW,QAAQ,SAAS,IAAI,MAAM,GAAG,GAAG;AAC1C,UAAM,QAAQ,IAAI,KAAK;AACvB,QAAI,CAAC,MAAO;AACZ,QAAI,UAAU,IAAK,OAAM;AAAA,aAChB,MAAM,WAAW,GAAG,EAAG,UAAS,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,CAAC;AAAA,aACzD,MAAM,WAAW,YAAY,GAAG;AACvC,YAAM,KAAK,KAAK,MAAM,MAAM,MAAM,aAAa,MAAM,CAAC;AACtD,UAAI,CAAC,OAAO,SAAS,EAAE,EAAG,OAAM,IAAI,MAAM,sBAAsB,KAAK,sBAAsB;AAC3F,eAAS,KAAK,EAAE;AAAA,IAClB,MAAO,KAAI,IAAI,KAAK;AAAA,EACtB;AACA,SAAO,EAAE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AQ,YAAY,EAC/D,IAAI,CAAC,CAACE,OAAM,KAAK,MAAM,CAACA,OAAM,KAAK,IAAI,GAAG,KAAK,KAAK,MAAM,cAAc,OAAO,SAAS,MAAM,OAAO,IAAI,MAAM,UAAU,EAAE,CAAC,CAAC,CAAU,EACvI,OAAO,CAAC,CAAC,EAAE,MAAM,MAAM,SAAS,CAAC,CAAC;AACrC,QAAM,gBAAgB,UAAU,UAAU,UAAU;AACpD,QAAM,WAAW,iBAAiB,WAAW,QAAQ;AACrD,QAAM,UAAU,CAAC,gBAAgB,CAAC,SAAS,UAAU,IAAI,8BAA8B,IACnF,OAAO,KAAK,UAAU,IAAI,EAAE,OAAO,YAAU,CAAC,OAAO,SAAS,SAAU,QAAQ,MAAM,CAAC,CAAC,EAAE,IAAI,YAAU,GAAG,MAAM,mBAAmB;AACxI,QAAM,aAAa,KAAK,MAAM,UAAU,QAAQ,QAAQ,EAAE;AAC1D,QAAM,QAAQ,cAAc,UAAa,SAAS,SAAS,KAAK,EAAE,cAAc,aAC5E,CAAC,yCAAyC,UAAU,QAAQ,QAAQ,kBAAkB,6CAA6C,IAAI,KAAK,SAAS,EAAE,YAAY,CAAC,2CAA2C,IAC/M,CAAC;AACL,QAAM,UAAU,CAAC,GAAG,UAAU,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,QAAQ,WAAW,EAAE,IAAI,CAAC,CAACA,OAAM,MAAM,MAAM,GAAGA,KAAI,UAAU,MAAM,aAAa,CAAC;AAChJ,SAAO,OAAO,YAAY,YAAY,SAAS,UAAU,CAAC,MAAM,SAAS,YAAY,QAAQ,SAAS,cAAc,WAAW,SAAS,UAAU,aAAa,SAAS,SAAS,CAAC;AACpL;","names":["reasons","measured","turnsNeeded","lane"]}
@@ -248,4 +248,4 @@ export {
248
248
  runPreflight,
249
249
  formatPreflightReport
250
250
  };
251
- //# sourceMappingURL=chunk-5FAKBTCK.js.map
251
+ //# sourceMappingURL=chunk-OYFA7BAK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/preflight/index.ts"],"sourcesContent":["/**\n * `/preflight` — deploy-time secret-liveness probes.\n *\n * WHY THIS EXISTS: four secrets were simultaneously dead in one\n * production day — a dead `SANDBOX_API_KEY`, a stale `SANDBOX_API_URL`, and a\n * dead LiteLLM router key + URL. Each one was present in `wrangler secret list`\n * (so nothing looked wrong) yet invalid against its live endpoint, and nothing\n * anywhere checked liveness. CI cannot hold production secrets, so this binds\n * at DEPLOY time instead: a product declares a handful of probes built from its\n * real env, the deploy workflow runs `agent-app-preflight` as a step, and a\n * dead secret fails the deploy with a message that names exactly which secret\n * to rotate.\n *\n * A probe is `{ name, run, critical? }`; `run()` returns `{ ok, detail? }`.\n * The standard builders (`requiredValueProbe`, `routerChatProbe`,\n * `sandboxAuthProbe`, `httpHeadProbe`) each take explicit config — they read\n * nothing global — so the same probe runs identically in a deploy step, a test,\n * or a local check. `runPreflight` fans\n * the probes out, times each, and folds them into a pass/fail report: any\n * failed CRITICAL probe fails the whole run (probes are critical by default).\n *\n * Server-only: probes carry live API keys and hit live endpoints. This subpath\n * must never reach a browser bundle.\n */\n\n/** One probe's outcome. `detail` should name the secret to rotate on failure. */\nexport interface PreflightProbeResult {\n ok: boolean\n detail?: string\n}\n\n/**\n * A liveness probe. `run` performs one cheap live call and maps the result to\n * `{ ok, detail }`. `critical` defaults to `true` — a failed critical probe\n * fails the whole preflight (and the deploy).\n */\nexport interface PreflightProbe {\n name: string\n run: () => Promise<PreflightProbeResult>\n critical?: boolean\n}\n\n/** Per-probe verdict enriched with the resolved criticality and measured latency. */\nexport interface PreflightProbeVerdict {\n name: string\n ok: boolean\n critical: boolean\n latencyMs: number\n detail?: string\n}\n\n/** Aggregate of every probe verdict plus the overall pass/fail decision. */\nexport interface PreflightReport {\n /** `false` if any critical probe failed. */\n ok: boolean\n probes: PreflightProbeVerdict[]\n passed: number\n failed: number\n criticalFailures: number\n durationMs: number\n}\n\n/** Deploy-time deadline for a single probe. Cold upstreams are slow; a dead\n * endpoint should still fail fast, so 10s is the ceiling, not the target. */\nconst DEFAULT_TIMEOUT_MS = 10_000\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now()\n}\n\nfunction isAbortLike(err: unknown): boolean {\n return err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')\n}\n\n/** Strip bearer tokens / key material before an upstream string is surfaced in\n * a report (deploy logs are not always private). */\nfunction sanitizeUpstreamMessage(input: unknown): string {\n const message = input instanceof Error ? input.message : String(input)\n return message\n .replace(/Bearer\\s+[^\\s]+/gi, 'Bearer [redacted]')\n .replace(/\\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\\b/g, '[redacted-key]')\n}\n\nfunction snippet(body: string): string {\n const trimmed = body.trim()\n if (!trimmed) return ''\n const clipped = trimmed.length > 180 ? `${trimmed.slice(0, 180)}…` : trimmed\n return `: ${sanitizeUpstreamMessage(clipped)}`\n}\n\ntype ProbeOutcome =\n | { kind: 'status'; status: number; bodyText: string }\n | { kind: 'timeout'; timeoutMs: number }\n | { kind: 'network'; message: string }\n\ninterface HttpProbeCall {\n fetchImpl: typeof fetch\n url: string\n method: string\n headers?: Record<string, string>\n body?: string\n timeoutMs: number\n}\n\n/** One live HTTP call, folded to a probe outcome. Never throws: a timeout, a\n * DNS/connection failure, and any thrown error all become an outcome so the\n * probe can classify them into an actionable detail. */\nasync function runHttp(call: HttpProbeCall): Promise<ProbeOutcome> {\n let response: Response\n try {\n response = await call.fetchImpl(call.url, {\n method: call.method,\n headers: call.headers,\n body: call.body,\n signal: AbortSignal.timeout(call.timeoutMs),\n })\n } catch (err) {\n if (isAbortLike(err)) return { kind: 'timeout', timeoutMs: call.timeoutMs }\n return { kind: 'network', message: sanitizeUpstreamMessage(err) }\n }\n let bodyText = ''\n try {\n bodyText = await response.text()\n } catch {\n bodyText = ''\n }\n return { kind: 'status', status: response.status, bodyText }\n}\n\ninterface AuthedClassifyContext {\n /** Full endpoint reached, for the message. */\n endpoint: string\n /** How to name the API-key secret when the endpoint reports auth failure. */\n keyLabel: string\n /** How to name the URL secret when the endpoint is unreachable. */\n urlLabel: string\n}\n\n/**\n * Shared classification for an authed liveness endpoint (router, sandbox):\n * 2xx → live; 401/403 → the KEY is dead, name it; 503 → the UPSTREAM is down,\n * the key still looks valid, don't rotate; timeout / unreachable → the URL is\n * likely stale, name it; anything else → an unexpected status with a snippet.\n */\nfunction classifyAuthed(outcome: ProbeOutcome, ctx: AuthedClassifyContext): PreflightProbeResult {\n switch (outcome.kind) {\n case 'status': {\n const { status, bodyText } = outcome\n if (status >= 200 && status < 300) return { ok: true, detail: `${status} OK` }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n detail: `DEAD KEY — ${ctx.endpoint} returned ${status}; rotate ${ctx.keyLabel}`,\n }\n }\n if (status === 503) {\n return {\n ok: false,\n detail: `UPSTREAM DOWN — ${ctx.endpoint} returned 503; ${ctx.keyLabel} still looks valid, retry or check the provider (do NOT rotate)`,\n }\n }\n return { ok: false, detail: `UNEXPECTED ${status} from ${ctx.endpoint}${snippet(bodyText)}` }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${ctx.endpoint} — check ${ctx.urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${ctx.endpoint} (${outcome.message}) — check ${ctx.urlLabel}`,\n }\n }\n}\n\nfunction trimTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\n// --- Standard probe builders --------------------------------------------------\n\n/** Configuration for a required non-empty production value. */\nexport interface RequiredValueProbeConfig {\n /** Human-readable value name, normally the environment variable name. */\n name: string\n /** Value supplied by the caller. It is checked but never included in output. */\n value: string | null | undefined\n /** Default `true`. */\n critical?: boolean\n /** Failure detail. Defaults to `NAME is unset`. */\n missingDetail?: string\n}\n\n/**\n * Require a non-empty string without ever printing its value.\n *\n * This covers local signing keys and other values that have no external\n * endpoint to probe. Credentials with a live API should use a liveness probe\n * instead, because presence alone cannot detect an expired key.\n */\nexport function requiredValueProbe(config: RequiredValueProbeConfig): PreflightProbe {\n return {\n name: `required:${config.name}`,\n critical: config.critical,\n run: async () => {\n const ok = typeof config.value === 'string' && config.value.trim().length > 0\n return { ok, detail: ok ? undefined : (config.missingDetail ?? `${config.name} is unset`) }\n },\n }\n}\n\n/** Define configuration options for probing an LLM router with authentication and model details */\nexport interface RouterChatProbeConfig {\n /** LLM router base URL (LiteLLM / OpenAI-compatible), e.g. `https://router…`. */\n baseUrl: string\n apiKey: string\n /** A cheap model id available on the router. */\n model: string\n /** Probe name in the report. Default `'router-chat'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe an OpenAI-compatible LLM router with one cheap `POST /chat/completions`\n * (`max_tokens: 1`). 200 → live; 401/403 → dead router key; 503 → upstream\n * provider down (key still valid); timeout / unreachable → check the router URL.\n */\nexport function routerChatProbe(config: RouterChatProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the router API key'\n const urlLabel = config.urlSecret ?? 'the router base URL'\n return {\n name: config.name ?? 'router-chat',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/chat/completions`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'POST',\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n max_tokens: 1,\n }),\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for probing sandbox authentication endpoints */\nexport interface SandboxAuthProbeConfig {\n /** Sandbox API base URL. */\n baseUrl: string\n apiKey: string\n /** Probe name in the report. Default `'sandbox-auth'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe the sandbox API with a cheap authed `GET /v1/sandboxes?limit=1`.\n * 200 → live; 401/403 → dead sandbox key; 503 → sandbox platform down (key\n * still valid); timeout / unreachable → check the sandbox URL.\n */\nexport function sandboxAuthProbe(config: SandboxAuthProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the sandbox API key'\n const urlLabel = config.urlSecret ?? 'the sandbox base URL'\n return {\n name: config.name ?? 'sandbox-auth',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/v1/sandboxes?limit=1`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'GET',\n headers: { Authorization: `Bearer ${config.apiKey}` },\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for performing an HTTP HEAD probe to check URL availability */\nexport interface HttpHeadProbeConfig {\n /** Probe name in the report. */\n name: string\n /** URL to `HEAD`. */\n url: string\n /**\n * Accepted status(es). A single number requires an exact match; an array\n * requires membership. Omitted → any 2xx/3xx (the host is up and the path\n * resolves) counts as live.\n */\n expectStatus?: number | number[]\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the URL, named verbatim in a failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\nfunction statusMatches(status: number, expect?: number | number[]): boolean {\n if (expect === undefined) return status >= 200 && status < 400\n if (Array.isArray(expect)) return expect.includes(status)\n return status === expect\n}\n\nfunction describeExpected(expect?: number | number[]): string {\n if (expect === undefined) return '2xx/3xx'\n if (Array.isArray(expect)) return expect.join(' or ')\n return String(expect)\n}\n\n/**\n * Probe a plain reachability endpoint (e.g. a platform base URL) with a `HEAD`.\n * Confirms the URL is live and resolving — the class of failure behind a stale\n * platform URL that still sits in the secret store.\n */\nexport function httpHeadProbe(config: HttpHeadProbeConfig): PreflightProbe {\n const urlLabel = config.urlSecret ?? `the URL for ${config.name}`\n return {\n name: config.name,\n critical: config.critical,\n run: async () => {\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: config.url,\n method: 'HEAD',\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n switch (outcome.kind) {\n case 'status': {\n if (statusMatches(outcome.status, config.expectStatus)) {\n return { ok: true, detail: `${outcome.status} OK` }\n }\n return {\n ok: false,\n detail: `UNEXPECTED ${outcome.status} from ${config.url} (expected ${describeExpected(config.expectStatus)}) — check ${urlLabel}`,\n }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${config.url} — check ${urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${config.url} (${outcome.message}) — check ${urlLabel}`,\n }\n }\n },\n }\n}\n\n// --- Runner + report ----------------------------------------------------------\n\nasync function runOne(probe: PreflightProbe): Promise<PreflightProbeVerdict> {\n const critical = probe.critical ?? true\n const start = nowMs()\n try {\n const result = await probe.run()\n return {\n name: probe.name,\n ok: result.ok,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: result.detail,\n }\n } catch (err) {\n return {\n name: probe.name,\n ok: false,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: `probe threw: ${sanitizeUpstreamMessage(err)}`,\n }\n }\n}\n\n/**\n * Run every probe (concurrently), time each, and fold into a report. The run\n * fails (`ok: false`) iff a critical probe fails; a failed non-critical probe\n * is a warning that does not block the deploy.\n */\nexport async function runPreflight(probes: PreflightProbe[]): Promise<PreflightReport> {\n const start = nowMs()\n const verdicts = await Promise.all(probes.map(runOne))\n const failed = verdicts.filter((v) => !v.ok)\n const criticalFailures = failed.filter((v) => v.critical).length\n return {\n ok: criticalFailures === 0,\n probes: verdicts,\n passed: verdicts.length - failed.length,\n failed: failed.length,\n criticalFailures,\n durationMs: Math.round(nowMs() - start),\n }\n}\n\ninterface FormatRow {\n status: string\n name: string\n latency: string\n detail: string\n}\n\n/** Render a report as an aligned, operator-readable table + verdict line. Pure\n * (no I/O) so it is trivially testable and reusable by the bin. */\nexport function formatPreflightReport(report: PreflightReport): string {\n const header: FormatRow = { status: 'STATUS', name: 'PROBE', latency: 'LATENCY', detail: 'DETAIL' }\n const rows: FormatRow[] = report.probes.map((p) => ({\n status: p.ok ? 'PASS' : p.critical ? 'FAIL' : 'WARN',\n name: p.name,\n latency: `${p.latencyMs}ms`,\n detail: p.detail ?? '',\n }))\n const statusW = Math.max(header.status.length, ...rows.map((r) => r.status.length))\n const nameW = Math.max(header.name.length, ...rows.map((r) => r.name.length))\n const latencyW = Math.max(header.latency.length, ...rows.map((r) => r.latency.length))\n const line = (r: FormatRow): string =>\n `${r.status.padEnd(statusW)} ${r.name.padEnd(nameW)} ${r.latency.padStart(latencyW)} ${r.detail}`.trimEnd()\n\n const out: string[] = [\n line(header),\n `${'-'.repeat(statusW)} ${'-'.repeat(nameW)} ${'-'.repeat(latencyW)} ------`,\n ...rows.map(line),\n '',\n ]\n if (report.ok) {\n const warn = report.failed > 0 ? ` (${report.failed} non-critical warning(s))` : ''\n out.push(`Preflight PASSED — ${report.passed}/${report.probes.length} probe(s) live${warn}`)\n } else {\n const dead = report.probes\n .filter((p) => !p.ok && p.critical)\n .map((p) => p.name)\n .join(', ')\n out.push(`Preflight FAILED — ${report.criticalFailures} critical probe(s) dead: ${dead}`)\n out.push('Rotate the secret named in each FAIL row above, then redeploy.')\n }\n return out.join('\\n')\n}\n"],"mappings":";AAgEA,IAAM,qBAAqB;AAE3B,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,YAAY,KAAuB;AAC1C,SAAO,eAAe,UAAU,IAAI,SAAS,kBAAkB,IAAI,SAAS;AAC9E;AAIA,SAAS,wBAAwB,OAAwB;AACvD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,SAAO,QACJ,QAAQ,qBAAqB,mBAAmB,EAChD,QAAQ,0CAA0C,gBAAgB;AACvE;AAEA,SAAS,QAAQ,MAAsB;AACrC,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,QAAQ,SAAS,MAAM,GAAG,QAAQ,MAAM,GAAG,GAAG,CAAC,WAAM;AACrE,SAAO,KAAK,wBAAwB,OAAO,CAAC;AAC9C;AAmBA,eAAe,QAAQ,MAA4C;AACjE,MAAI;AACJ,MAAI;AACF,eAAW,MAAM,KAAK,UAAU,KAAK,KAAK;AAAA,MACxC,QAAQ,KAAK;AAAA,MACb,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,QAAQ,YAAY,QAAQ,KAAK,SAAS;AAAA,IAC5C,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,YAAY,GAAG,EAAG,QAAO,EAAE,MAAM,WAAW,WAAW,KAAK,UAAU;AAC1E,WAAO,EAAE,MAAM,WAAW,SAAS,wBAAwB,GAAG,EAAE;AAAA,EAClE;AACA,MAAI,WAAW;AACf,MAAI;AACF,eAAW,MAAM,SAAS,KAAK;AAAA,EACjC,QAAQ;AACN,eAAW;AAAA,EACb;AACA,SAAO,EAAE,MAAM,UAAU,QAAQ,SAAS,QAAQ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