@tangle-network/agent-app 4.0.8 → 4.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +2 -1
- package/dist/assistant/index.js.map +1 -1
- package/dist/billing/identity-bound.d.ts +7 -0
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.js +3 -1
- package/dist/chat-routes/detached-turn.d.ts +2 -0
- package/dist/chat-routes/failure-wording.d.ts +61 -0
- package/dist/chat-routes/index.js +30 -22
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-producer.d.ts +6 -14
- package/dist/chat-routes/turn-event-stream.d.ts +5 -0
- package/dist/chat-routes/turn-route-contracts.d.ts +23 -0
- package/dist/chat-routes/turn-routes.d.ts +3 -1
- package/dist/{chunk-R5PW3FO4.js → chunk-2IGXFHUO.js} +13 -2
- package/dist/chunk-2IGXFHUO.js.map +1 -0
- package/dist/{chunk-4OR7NNYB.js → chunk-CD4SJXYC.js} +125 -730
- package/dist/chunk-CD4SJXYC.js.map +1 -0
- package/dist/{chunk-FTGKXM7O.js → chunk-EK7A5Y7P.js} +12 -4
- package/dist/chunk-EK7A5Y7P.js.map +1 -0
- package/dist/{chunk-FZOHBYGV.js → chunk-KPCNNFBO.js} +13 -2
- package/dist/chunk-KPCNNFBO.js.map +1 -0
- package/dist/{chunk-QXPOBDPU.js → chunk-M4LA7JMU.js} +1 -21
- package/dist/chunk-M4LA7JMU.js.map +1 -0
- package/dist/{chunk-ASWAPIJM.js → chunk-QMQB725F.js} +4 -14
- package/dist/chunk-QMQB725F.js.map +1 -0
- package/dist/chunk-QUV5M7SZ.js +23 -0
- package/dist/chunk-QUV5M7SZ.js.map +1 -0
- package/dist/chunk-RNDWCT4O.js +1136 -0
- package/dist/chunk-RNDWCT4O.js.map +1 -0
- package/dist/{chunk-W2DIPVHW.js → chunk-TMWUWKLU.js} +6 -5
- package/dist/chunk-TMWUWKLU.js.map +1 -0
- package/dist/{chunk-A2M75YRP.js → chunk-VTMMTQ4P.js} +2 -2
- package/dist/chunk-VTMMTQ4P.js.map +1 -0
- package/dist/journeys/cli.js +1 -1
- package/dist/journeys/index.js +1 -1
- package/dist/preset-cloudflare/index.js +8 -5
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/public-consultation/index.js +6 -5
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/sandbox/index.js +4 -4
- package/dist/turn-health/index.js +2 -1
- package/dist/turn-health/index.js.map +1 -1
- package/dist/turn-health/sweep.d.ts +1 -1
- package/dist/turn-stream/adapters.d.ts +14 -1
- package/dist/turn-stream/core.d.ts +2 -0
- package/dist/turn-stream/do.d.ts +17 -0
- package/dist/turn-stream/index.d.ts +1 -1
- package/dist/turn-stream/index.js +11 -2
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/web-react/index.d.ts +1 -1
- package/dist/web-react/index.js +4 -2
- package/package.json +1 -1
- package/dist/chunk-4OR7NNYB.js.map +0 -1
- package/dist/chunk-A2M75YRP.js.map +0 -1
- package/dist/chunk-ASWAPIJM.js.map +0 -1
- package/dist/chunk-FTGKXM7O.js.map +0 -1
- package/dist/chunk-FZOHBYGV.js.map +0 -1
- package/dist/chunk-K4YIDNX5.js +0 -263
- package/dist/chunk-K4YIDNX5.js.map +0 -1
- package/dist/chunk-QXPOBDPU.js.map +0 -1
- package/dist/chunk-R5PW3FO4.js.map +0 -1
- package/dist/chunk-W2DIPVHW.js.map +0 -1
- /package/dist/{web-react → web}/turn-funding-recovery.d.ts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/billing/identity-locks.ts","../src/billing/identity-bound.ts","../src/billing/index.ts"],"sourcesContent":["import type { DurableWorkspaceKeyManagerOptions } from './identity-bound'\n\nexport function createWorkspaceKeyLocks(\n leaseWaitMs: number,\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n leaseMs: number,\n leasePollMs: number,\n leaseRenewIntervalMs: number,\n operationId: () => string,\n sleep: (ms: number) => Promise<void>,\n) {\n const localLocks = new Map<string, Promise<void>>()\n\n async function withLocalLock<T>(scope: string, work: () => Promise<T>): Promise<T> {\n const previous = localLocks.get(scope) ?? Promise.resolve()\n let release!: () => void\n const current = new Promise<void>((resolve) => { release = resolve })\n localLocks.set(scope, current)\n await previous\n try {\n return await work()\n } finally {\n release()\n if (localLocks.get(scope) === current) localLocks.delete(scope)\n }\n }\n\n async function withDurableLease<T>(\n scope: string,\n work: () => Promise<T>,\n onLeaseLost?: () => Promise<void>,\n ): Promise<T> {\n const leaseOperationId = operationId()\n const startedAt = Date.now()\n let acquired = false\n while (!acquired && Date.now() - startedAt <= leaseWaitMs) {\n acquired = await options.store.acquireLease(scope, leaseOperationId, now(), leaseMs)\n if (!acquired) await sleep(leasePollMs)\n }\n if (!acquired) throw new Error('workspace child-key issuance is busy; retry the request')\n\n let stopped = false\n let leaseLost: Error | null = null\n let leaseTimer: ReturnType<typeof setTimeout> | undefined\n let renewalPromise: Promise<void> | undefined\n const scheduleRenewal = () => {\n if (stopped || leaseLost) return\n leaseTimer = setTimeout(() => {\n leaseTimer = undefined\n const renewal = (async () => {\n try {\n if (!await options.store.renewLease(scope, leaseOperationId, now(), leaseMs)) {\n leaseLost = new Error('workspace child-key lease was lost during reconciliation')\n return\n }\n scheduleRenewal()\n } catch (error) {\n leaseLost = error instanceof Error ? error : new Error('workspace child-key lease renewal failed')\n }\n })()\n renewalPromise = renewal\n void renewal.finally(() => {\n if (renewalPromise === renewal) renewalPromise = undefined\n }).catch(() => undefined)\n }, leaseRenewIntervalMs)\n }\n scheduleRenewal()\n\n let workError: unknown\n let leaseLossCleanupError: unknown\n try {\n const result = await work()\n if (leaseLost) throw leaseLost\n return result\n } catch (error) {\n workError = error\n throw error\n } finally {\n stopped = true\n if (leaseTimer) clearTimeout(leaseTimer)\n if (renewalPromise) await renewalPromise\n if (leaseLost && onLeaseLost) {\n try {\n await onLeaseLost()\n } catch (error) {\n leaseLossCleanupError = error\n }\n }\n try {\n await options.store.releaseLease(scope, leaseOperationId)\n } catch (error) {\n if (workError === undefined) throw error\n }\n if (workError === undefined && leaseLossCleanupError) {\n throw new Error('workspace child-key lease was lost and cleanup failed', { cause: leaseLossCleanupError })\n }\n if (workError === undefined && leaseLost) throw leaseLost\n }\n }\n return { withLocalLock, withDurableLease }\n}\n","import { createWorkspaceKeyLocks } from './identity-locks'\nimport { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\nimport type { KeyCrypto, KeyProvisioner } from './index'\n\n/** Lifecycle state for a durable delegated key row. */\nexport type WorkspaceKeyStatus =\n | 'legacy'\n | 'provisioning'\n | 'active'\n | 'revocation_pending'\n | 'revoked'\n | 'orphaned'\n\n/** Product partition used by the key store and remote provisioner. */\nexport type WorkspaceKeyProduct = string\n\n/** The identity fields that bind a child key to its paying owner and source. */\nexport interface WorkspaceKeyIdentity {\n workspaceId: string\n ownerUserId: string\n platformUserId: string\n sourceKeyId?: string | null\n /** A non-secret digest of the source credential. */\n sourceKeyFingerprint: string\n}\n\n/** A product/workspace/owner lookup scope. */\nexport interface DurableWorkspaceKeyScope {\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n}\n\n/** A persisted child-key row owned by this manager. */\nexport interface DurableWorkspaceKeyRecord {\n id: string\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n platformUserId: string\n sourceKeyId: string | null\n sourceKeyFingerprint: string\n /** The persisted name used to recover a remote create after a crash. Null only for pre-name rows. */\n name: string | null\n /** The persisted retry identity for the remote create. Absent on legacy rows without a persisted create identity. */\n idempotencyKey?: string | null\n keyId: string\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date\n status: WorkspaceKeyStatus\n revocationAttempts: number\n nextRevocationAt: Date | null\n lastRevocationError: string | null\n createdAt: Date\n}\n\n/** A row that has been written before its remote child key exists. */\nexport interface DurableWorkspaceKeyProvisioningRecord extends DurableWorkspaceKeyRecord {\n status: 'provisioning'\n}\n\ntype DurableWorkspaceKeyCreateResult = Awaited<ReturnType<KeyProvisioner['createKey']>> & {\n budgetUsd?: number | null\n budgetRemaining?: number\n expiresAt?: string | null\n}\n\n/** The exact request identity that must be reused when recovering a create. */\nexport interface DurableWorkspaceKeyCreateInput {\n name: string\n product: string\n budgetUsd: number\n expiresAt: string\n /** Stable across process restarts for one persisted provisioning row. */\n idempotencyKey: string\n}\n\n/** The remote operations required by the durable manager. */\nexport interface DurableWorkspaceKeyProvisioner {\n /** True only when replay returns the original child for the persisted request identity. */\n supportsIdempotentCreate?: true\n /** Create one child key. Non-idempotent providers recover through stable-name discovery only. */\n createKey(input: DurableWorkspaceKeyCreateInput): Promise<DurableWorkspaceKeyCreateResult>\n getKey(id: string): Promise<{\n budgetUsd?: number | null\n budgetSpent?: number\n expiresAt?: string | null\n }>\n /**\n * Retire one child. `slot` is the row that minted it: its name, its own source and Platform user, so a child minted\n * under an earlier source is retired through that source's slot. A typed refusal carries `refusal.status`.\n */\n revokeKey(id: string, slot?: Pick<DurableWorkspaceKeyRecord, 'name' | 'sourceKeyId' | 'platformUserId'>): Promise<unknown>\n /** Find remote keys for a specific persisted provisioning attempt. */\n findCreatedKeys(input: {\n name: string\n product: string\n sourceKeyId?: string | null\n }): Promise<Array<{ id: string }>>\n}\n\n/** Optional compare-and-set lifecycle writes for stores that support fencing. */\nexport interface DurableWorkspaceKeyConditionalWrites {\n /** Return false when the row was no longer provisioning. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<boolean>\n /** Return false when the row was no longer provisioning. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<boolean>\n}\n\n/** Persistence operations for identity-bound key lifecycle state. */\nexport interface DurableWorkspaceKeyStore {\n /** Return the active row for this exact product scope. */\n getActive(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyRecord | null>\n /** Return every unfinished provisioning row for this exact product scope. */\n listProvisioning(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyProvisioningRecord[]>\n /** Insert before the remote create so a crashed create can be recovered. */\n insertProvisioning(record: DurableWorkspaceKeyProvisioningRecord): Promise<void>\n /** Save the remote id while the row remains in provisioning state. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<void>\n /** Promote a fully encrypted row to active state. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<void>\n /**\n * Optional fenced writes. The manager uses false to compensate a stale\n * creator. Stores without this field retain the pre-fence behavior.\n */\n conditionalWrites?: DurableWorkspaceKeyConditionalWrites\n /** Keep a failed cleanup visible and schedule a later retry. Terminal rows are immutable. */\n markRevocationPending(input: {\n id: string\n error?: string | null\n nextAttemptAt: Date\n incrementAttempts: boolean\n }): Promise<void>\n /** Mark a remote key as revoked. Missing remote keys count as revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n /** Mark a provisioning row terminal when no remote key remains to clean. */\n markOrphaned(id: string, error: string): Promise<void>\n /** Query due cleanup rows. The implementation should filter by the supplied scope. */\n listPendingRevocations(input: {\n product: WorkspaceKeyProduct\n workspaceId?: string\n ownerUserId?: string\n now: Date\n limit: number\n /** Include rows scheduled for a later retry when checking before issuance. */\n includeFuture?: boolean\n }): Promise<DurableWorkspaceKeyRecord[]>\n /** Acquire a cross-process lease for one product/workspace/owner scope. */\n acquireLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Renew an acquired lease before its expiry. */\n renewLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Release an acquired lease. */\n releaseLease(scope: string, operationId: string): Promise<void>\n}\n\n/** Live budget information for a child key. */\nexport interface WorkspaceKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string\n exhausted: boolean\n}\n\n/** The decrypted key plus the usage snapshot used to issue it. */\nexport interface WorkspaceRuntimeKey {\n key: string\n usage: WorkspaceKeyUsage\n /** True when this call minted a new remote key. */\n refreshed: boolean\n}\n\n/** Identity-bound durable key manager API. */\nexport interface DurableWorkspaceKeyManager {\n /** Reuse a matching active key or reconcile and mint one under a lease. */\n ensureKey(identity: WorkspaceKeyIdentity, options?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey>\n /** Read usage without returning the child secret. */\n getUsage(identity: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null>\n /**\n * Retry due cleanup rows. A supplied owner/workspace limits the retry to its\n * scope. Empty provisioning rows also require the full identity so a retry\n * can use the original source binding safely.\n */\n retryPendingRevocations(\n scope?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identity?: WorkspaceKeyIdentity,\n ): Promise<number>\n}\n\n/** Configuration for {@link createIdentityBoundWorkspaceKeyManager}. */\nexport interface DurableWorkspaceKeyManagerOptions {\n store: DurableWorkspaceKeyStore\n provisioner: DurableWorkspaceKeyProvisioner\n /**\n * Control-plane client for historical get/revoke/list operations. Use this\n * when the source credential can rotate or disappear. It never mints keys.\n */\n recoveryProvisioner?: Pick<DurableWorkspaceKeyProvisioner, 'getKey' | 'revokeKey' | 'findCreatedKeys'>\n crypto: KeyCrypto\n /** Product partition. Products must use separate values. */\n product: WorkspaceKeyProduct\n defaultBudgetUsd: number\n now?: () => Date\n /** Local lifetime used when the remote response omits an expiry. */\n keyLifetimeMs?: number\n /** Lease lifetime for remote operations. */\n leaseMs?: number\n /** Maximum time to wait for another issuer to release the scope lease. */\n leaseWaitMs?: number\n /** Poll delay while waiting for a scope lease. */\n leasePollMs?: number\n /** Renewal interval. It must be shorter than `leaseMs`. */\n leaseRenewIntervalMs?: number\n /** Initial delay for a failed remote revoke. */\n revocationRetryBaseMs?: number\n /** Maximum delay for a failed remote revoke. */\n revocationRetryMaxMs?: number\n /** Stable remote name. The operation id makes the default crash-safe. */\n nameForIdentity?: (identity: WorkspaceKeyIdentity, operationId: string) => string\n /** Resolve names for rows written before `name` became durable. Null blocks issuance safely. */\n legacyNameForRecord?: (record: DurableWorkspaceKeyRecord) => string | null | undefined\n /** Recognize a missing remote key without depending on a provider SDK. */\n isRemoteMissing?: (error: unknown) => boolean\n}\n\nconst DEFAULT_KEY_LIFETIME_MS = 55 * 60_000\nconst DEFAULT_LEASE_MS = 60_000\nconst DEFAULT_LEASE_WAIT_MS = 15_000\nconst DEFAULT_LEASE_POLL_MS = 50\nconst DEFAULT_LEASE_RENEW_INTERVAL_MS = Math.floor(DEFAULT_LEASE_MS / 3)\nconst DEFAULT_REVOCATION_RETRY_BASE_MS = 2_000\nconst DEFAULT_REVOCATION_RETRY_MAX_MS = 60_000\nconst PENDING_REVOCATION_BATCH_SIZE = 20\n// Covers clock skew between this host and the platform that enforces the child's expiry.\nconst ORPHAN_AFTER_EXPIRY_GRACE_MS = 5 * 60_000\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction operationId(): string {\n return globalThis.crypto.randomUUID()\n}\n\nfunction requirePositive(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be a positive finite number`)\n return value\n}\n\nfunction requireNonNegative(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be a non-negative finite number`)\n return value\n}\n\nfunction normalizeIdentity(identity: WorkspaceKeyIdentity): WorkspaceKeyIdentity {\n const workspaceId = identity.workspaceId.trim()\n const ownerUserId = identity.ownerUserId.trim()\n const platformUserId = identity.platformUserId.trim()\n const sourceKeyFingerprint = identity.sourceKeyFingerprint.trim()\n const sourceKeyId = identity.sourceKeyId?.trim() || null\n if (!workspaceId || !ownerUserId || !platformUserId || !sourceKeyFingerprint) {\n throw new Error('workspace child key identity is incomplete')\n }\n return { workspaceId, ownerUserId, platformUserId, sourceKeyId, sourceKeyFingerprint }\n}\n\nfunction scopeFor(identity: Pick<WorkspaceKeyIdentity, 'workspaceId' | 'ownerUserId'>, product: string): DurableWorkspaceKeyScope {\n return { workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId, product }\n}\n\nfunction scopeKey(scope: DurableWorkspaceKeyScope): string {\n return JSON.stringify([scope.product, scope.workspaceId, scope.ownerUserId])\n}\n\nfunction safeNamePart(value: string): string {\n const normalized = value.replace(/[^A-Za-z0-9._-]/g, '-').replace(/-+/g, '-')\n return normalized.slice(0, 80) || 'unknown'\n}\n\nfunction defaultKeyName(identity: WorkspaceKeyIdentity, product: string, operationId: string): string {\n return `agent-app:${safeNamePart(product)}:${safeNamePart(identity.workspaceId)}:${safeNamePart(identity.platformUserId)}:${operationId}`\n}\n\nfunction sourceKeyId(identity: WorkspaceKeyIdentity): string | null {\n return identity.sourceKeyId?.trim() || null\n}\n\nfunction sameIdentity(row: DurableWorkspaceKeyRecord, identity: WorkspaceKeyIdentity, product: string): boolean {\n return row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId\n && row.product === product\n && row.platformUserId === identity.platformUserId\n && row.sourceKeyId === sourceKeyId(identity)\n && row.sourceKeyFingerprint === identity.sourceKeyFingerprint\n}\n\n/**\n * Whether an ACTIVE child may be reused: it belongs to its workspace, owner, product and Platform user, not to the\n * source credential that minted it. Every sign-in presents a new source credential (sourceKeyId, sourceKeyFingerprint),\n * so matching on it made the same member's second sign-in revoke the child a running turn held. The payer cannot\n * differ for one Platform user: delegation refuses a child not paid by that user (`platform/delegated-keys.ts`:\n * non-user payer and payer id checks). A revoked source takes its children with it: their read-back is a definite\n * gone verdict. Cleanup goes through the row's own slot (`slotOf`). Recovery of a half-provisioned row still needs the\n * exact minting source (`sameIdentity`).\n */\nfunction sameOwner(row: DurableWorkspaceKeyRecord, owner: Pick<DurableWorkspaceKeyRecord, 'workspaceId' | 'ownerUserId' | 'platformUserId'>,\n product: string): boolean {\n return row.workspaceId === owner.workspaceId\n && row.ownerUserId === owner.ownerUserId\n && row.product === product\n && row.platformUserId === owner.platformUserId\n}\n\n/** The slot a child was minted in, for the provisioner's revoke. Never the secret. */\nfunction slotOf(row: DurableWorkspaceKeyRecord): Pick<DurableWorkspaceKeyRecord, 'name' | 'sourceKeyId' | 'platformUserId'> {\n return { name: row.name, sourceKeyId: row.sourceKeyId, platformUserId: row.platformUserId }\n}\n\n/**\n * A refused cleanup of a live child waits for the child's own expiry and blocks no issuance meanwhile. Only that\n * deferral schedules the row AT the expiry (`settleFailedRevoke`); a transient retry that lands at or past it still\n * blocks, so a second child never mints while the first is live.\n */\nfunction waitsForExpiry(row: DurableWorkspaceKeyRecord): boolean {\n return row.nextRevocationAt !== null && row.nextRevocationAt.getTime() === row.expiresAt.getTime()\n}\n\nfunction errorMessage(error: unknown, fallback: string): string {\n return (error instanceof Error ? error.message : fallback)\n .replace(/Bearer\\s+[^\\s,;]+/gi, 'Bearer [redacted]')\n .replace(/((?:authorization|api[-_ ]?key|token|secret|password)\\s*[:=]\\s*)(?!Bearer\\b)[^\\s,;]+/gi, '$1[redacted]')\n .slice(0, 240)\n}\n\nfunction isProvisioningId(value: string): boolean {\n return value.startsWith('provisioning:')\n}\n\nasync function markProvisioningRemote(\n store: DurableWorkspaceKeyStore,\n input: { id: string; keyId: string },\n): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markProvisioningRemote(input)\n await store.markProvisioningRemote(input)\n return true\n}\n\nasync function markActive(\n store: DurableWorkspaceKeyStore,\n input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n },\n): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markActive(input)\n await store.markActive(input)\n return true\n}\n\nfunction usageFromRemote(\n row: DurableWorkspaceKeyRecord,\n remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>,\n now: Date,\n): WorkspaceKeyUsage {\n const budgetUsd = remote.budgetUsd ?? row.budgetUsd\n const budgetSpent = remote.budgetSpent ?? 0\n if (!Number.isFinite(budgetUsd) || budgetUsd < 0) throw new Error('workspace child key budget is malformed')\n if (!Number.isFinite(budgetSpent) || budgetSpent < 0) throw new Error('workspace child key usage is malformed')\n const expiresAt = remote.expiresAt ?? row.expiresAt.toISOString()\n const expiryMs = Date.parse(expiresAt)\n if (!Number.isFinite(expiryMs)) throw new Error('workspace child key expiry is malformed')\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: row.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt,\n exhausted: budgetRemaining <= 0 || expiryMs <= now.getTime(),\n }\n}\n\nfunction defaultRemoteMissing(error: unknown): boolean {\n const value = error as { status?: unknown; code?: unknown } | null\n return value?.status === 404 || value?.code === 'not_found'\n}\n\n/** `<status> <code>` for a typed refusal Platform decided (a 4xx other than 408 and 429): a retry gets the same answer. */\nfunction definiteRefusal(error: unknown): string | null {\n const refusal = (error as { refusal?: { status?: unknown; code?: unknown; platformCode?: unknown } } | null)?.refusal\n const status = refusal?.status\n if (typeof status !== 'number' || status < 400 || status > 499 || status === 408 || status === 429) return null\n return `${status} ${String(refusal?.platformCode ?? refusal?.code ?? 'refused')}`\n}\n\n/**\n * Create a product-neutral manager for child-key issuance and cleanup.\n *\n * The provisioner must already be authenticated for the current source\n * credential. The manager persists the source id and its non-secret\n * fingerprint with each row, reuses an active row for the same workspace,\n * owner, product and Platform user, and cleans each row through its own slot.\n */\nexport function createIdentityBoundWorkspaceKeyManager(\n options: DurableWorkspaceKeyManagerOptions,\n): DurableWorkspaceKeyManager {\n const product = options.product.trim()\n if (!product) throw new Error('workspace child key product is required')\n const defaultBudgetUsd = requirePositive(options.defaultBudgetUsd, 'defaultBudgetUsd')\n const keyLifetimeMs = requirePositive(options.keyLifetimeMs ?? DEFAULT_KEY_LIFETIME_MS, 'keyLifetimeMs')\n const leaseMs = requirePositive(options.leaseMs ?? DEFAULT_LEASE_MS, 'leaseMs')\n const leaseWaitMs = requireNonNegative(options.leaseWaitMs ?? DEFAULT_LEASE_WAIT_MS, 'leaseWaitMs')\n const leasePollMs = requirePositive(options.leasePollMs ?? DEFAULT_LEASE_POLL_MS, 'leasePollMs')\n const leaseRenewIntervalMs = requirePositive(\n options.leaseRenewIntervalMs ?? Math.min(DEFAULT_LEASE_RENEW_INTERVAL_MS, Math.floor(leaseMs / 3)),\n 'leaseRenewIntervalMs',\n )\n if (leaseRenewIntervalMs >= leaseMs) throw new Error('leaseRenewIntervalMs must be shorter than leaseMs')\n const revocationRetryBaseMs = requirePositive(\n options.revocationRetryBaseMs ?? DEFAULT_REVOCATION_RETRY_BASE_MS,\n 'revocationRetryBaseMs',\n )\n const revocationRetryMaxMs = requirePositive(\n options.revocationRetryMaxMs ?? DEFAULT_REVOCATION_RETRY_MAX_MS,\n 'revocationRetryMaxMs',\n )\n if (revocationRetryMaxMs < revocationRetryBaseMs) throw new Error('revocationRetryMaxMs must cover the base delay')\n\n const now = options.now ?? (() => new Date())\n const isRemoteMissing = options.isRemoteMissing ?? defaultRemoteMissing\n const recoveryProvisioner = options.recoveryProvisioner ?? options.provisioner\n const { withLocalLock, withDurableLease } = createWorkspaceKeyLocks(leaseWaitMs, options, now, leaseMs, leasePollMs, leaseRenewIntervalMs, operationId, sleep)\n\n const { revokePending, markPending, cleanupProvisioning, reconcileProvisioning } = createWorkspaceKeyRecovery(revocationRetryMaxMs, revocationRetryBaseMs, options, now, recoveryProvisioner, isRemoteMissing, product)\n\n async function retryPendingRevocationsUnlocked(\n scopeFilter?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n activeIdentity?: WorkspaceKeyIdentity,\n ): Promise<{ completed: number; pending: number }> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: scopeFilter?.workspaceId,\n ownerUserId: scopeFilter?.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n })\n let completed = 0\n let pending = 0\n for (const row of rows) {\n if (row.product !== product) continue\n if (scopeFilter && (row.workspaceId !== scopeFilter.workspaceId || row.ownerUserId !== scopeFilter.ownerUserId)) continue\n if (await revokePending(row, activeIdentity)) completed += 1\n else pending += 1\n }\n return { completed, pending }\n }\n\n async function assertNoPendingRevocations(identity: WorkspaceKeyIdentity): Promise<void> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n includeFuture: true,\n })\n if (rows.some((row) => row.product === product\n && row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId && !waitsForExpiry(row))) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n\n async function retryPendingRevocations(\n scopeInput?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identityInput?: WorkspaceKeyIdentity,\n ): Promise<number> {\n const identity = identityInput ? normalizeIdentity(identityInput) : undefined\n if (identity && scopeInput\n && (identity.workspaceId !== scopeInput.workspaceId || identity.ownerUserId !== scopeInput.ownerUserId)) {\n throw new Error('workspace child key retry identity does not match its scope')\n }\n if (scopeInput) {\n const workspaceId = scopeInput.workspaceId.trim()\n const ownerUserId = scopeInput.ownerUserId.trim()\n if (!workspaceId || !ownerUserId) throw new Error('workspace child key retry scope is incomplete')\n const scope = scopeKey({ workspaceId, ownerUserId, product })\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId, ownerUserId }, identity)).completed))\n }\n\n if (identity) {\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId }, identity)).completed))\n }\n\n const rows = await options.store.listPendingRevocations({ product, now: now(), limit: PENDING_REVOCATION_BATCH_SIZE })\n let completed = 0\n const scopes = new Set<string>()\n for (const row of rows) {\n if (row.product !== product) continue\n const scope = scopeKey({ workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product })\n if (scopes.has(scope)) continue\n scopes.add(scope)\n completed += await withLocalLock(scope, () => withDurableLease(scope, async () => (await retryPendingRevocationsUnlocked({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n })).completed))\n }\n return completed\n }\n\n async function readActive(identity: WorkspaceKeyIdentity): Promise<{ row: DurableWorkspaceKeyRecord; usage: WorkspaceKeyUsage } | null> {\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row) return null\n if (!sameOwner(row, identity, product)) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key belongs to another workspace owner or Platform user',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n\n let remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>\n try {\n remote = await recoveryProvisioner.getKey(row.keyId)\n } catch (error) {\n if (isRemoteMissing(error)) {\n await options.store.markRevoked(row.id, now())\n return null\n }\n throw error\n }\n const usage = usageFromRemote(row, remote, now())\n if (usage.exhausted) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key is expired or exhausted',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n return { row, usage }\n }\n\n const { mint } = createWorkspaceKeyMinter(options, now, keyLifetimeMs, product, markPending, cleanupProvisioning, revokePending)\n\n async function ensureKey(identityInput: WorkspaceKeyIdentity, keyOptions?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey> {\n const identity = normalizeIdentity(identityInput)\n const budgetUsd = keyOptions?.budgetUsd ?? defaultBudgetUsd\n requirePositive(budgetUsd, 'budgetUsd')\n const scope = scopeKey(scopeFor(identity, product))\n let mintedRemote: { row: DurableWorkspaceKeyProvisioningRecord; remoteId: string } | null = null\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const initialCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (initialCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await reconcileProvisioning(identity)\n const active = await readActive(identity)\n if (active) {\n const key = await options.crypto.decrypt(active.row.keyEncrypted)\n if (!key.trim()) throw new Error('workspace child key secret is empty')\n // The decrypt is awaited after the expiry check; a key that expired meanwhile is never handed out.\n if (Date.parse(active.usage.expiresAt) > now().getTime()) return { key, usage: active.usage, refreshed: false }\n await options.store.markRevocationPending({\n id: active.row.id,\n error: 'active child key expired while it was read',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n }\n const finalCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (finalCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await assertNoPendingRevocations(identity)\n return mint(identity, budgetUsd, (row, remoteId) => {\n mintedRemote = { row, remoteId }\n })\n }, async () => {\n const remote = mintedRemote\n if (!remote) return\n const cleaned = await revokePending({\n ...remote.row,\n keyId: remote.remoteId,\n status: 'revocation_pending',\n }, identity)\n if (!cleaned) throw new Error('lease-loss child-key cleanup is pending')\n }))\n }\n\n async function getUsage(identityInput: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null> {\n const identity = normalizeIdentity(identityInput)\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const active = await readActive(identity)\n return active?.usage ?? null\n }))\n }\n\n return { ensureKey, getUsage, retryPendingRevocations }\n}\n\nfunction createWorkspaceKeyRecovery(\n revocationRetryMaxMs: ReturnType<typeof requirePositive>,\n revocationRetryBaseMs: ReturnType<typeof requirePositive>,\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n recoveryProvisioner: Pick<DurableWorkspaceKeyProvisioner, \"getKey\" | \"revokeKey\" | \"findCreatedKeys\">,\n isRemoteMissing: (error: unknown) => boolean,\n product: string,\n) {\n function retryDelay(attempts: number): number {\n return Math.min(revocationRetryMaxMs, revocationRetryBaseMs * 2 ** Math.min(Math.max(attempts - 1, 0), 5))\n }\n\n async function markPending(id: string, error: unknown, incrementAttempts: boolean): Promise<void> {\n const delay = incrementAttempts ? retryDelay(1) : 0\n await options.store.markRevocationPending({\n id,\n error: errorMessage(error, 'remote key cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + delay),\n incrementAttempts,\n })\n }\n\n /**\n * A refusal to revoke never blocks the scope. Missing is gone. After a definite refusal the child's own verdict\n * decides: past its expiry, or unable to authenticate or spend, it is gone; live or refused for now, it is retired\n * at its expiry. Null keeps today's retry: a transient failure, or a verdict read that failed transiently.\n */\n async function settleFailedRevoke(row: DurableWorkspaceKeyRecord, keyId: string, error: unknown): Promise<'gone' | 'waits' | null> {\n // An expired child can neither authenticate nor spend, whatever answered: it never holds the scope.\n if (isRemoteMissing(error) || now().getTime() >= row.expiresAt.getTime()) return 'gone'\n const refused = definiteRefusal(error)\n if (!refused) return null\n try {\n if (usageFromRemote(row, await recoveryProvisioner.getKey(keyId), now()).exhausted) return 'gone'\n } catch (readError) {\n if (isRemoteMissing(readError)) return 'gone'\n if (!definiteRefusal(readError)) return null\n }\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(new Error(`cleanup refused (${refused}); the child is retired at its expiry`), 'cleanup refused'),\n nextAttemptAt: row.expiresAt,\n incrementAttempts: true,\n })\n return 'waits'\n }\n\n async function revokePending(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n if (!row.keyId || isProvisioningId(row.keyId)) return cleanupProvisioning(row, identity)\n const active = await options.store.getActive({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n product: row.product,\n })\n if (active && active.id !== row.id && active.keyId === row.keyId) {\n await options.store.markRevoked(row.id, now())\n return true\n }\n try {\n await recoveryProvisioner.revokeKey(row.keyId, slotOf(row))\n await options.store.markRevoked(row.id, now())\n return true\n } catch (error) {\n const settled = await settleFailedRevoke(row, row.keyId, error)\n if (settled === 'gone') await options.store.markRevoked(row.id, now())\n if (settled) return true\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote key revocation failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n async function provisioningCandidates(row: DurableWorkspaceKeyRecord): Promise<{\n name: string\n candidates: Array<{ id: string }>\n } | null> {\n if (row.keyId && !isProvisioningId(row.keyId)) {\n return { name: row.name?.trim() ?? '', candidates: [{ id: row.keyId }] }\n }\n const name = row.name?.trim() || options.legacyNameForRecord?.(row)?.trim()\n if (!name) return null\n return {\n name,\n candidates: await recoveryProvisioner.findCreatedKeys({\n name,\n product: row.product,\n sourceKeyId: row.sourceKeyId,\n }),\n }\n }\n\n async function probeProvisioning(\n row: DurableWorkspaceKeyRecord,\n identity: WorkspaceKeyIdentity | undefined,\n name: string,\n ): Promise<Array<{ id: string }> | null> {\n const idempotencyKey = row.idempotencyKey?.trim()\n if (!identity || !sameIdentity(row, identity, product)\n || !options.provisioner.supportsIdempotentCreate || !idempotencyKey) return []\n try {\n const created = await options.provisioner.createKey({\n name,\n product: row.product,\n budgetUsd: row.budgetUsd,\n expiresAt: row.expiresAt.toISOString(),\n idempotencyKey,\n })\n const remoteId = created.id?.trim()\n if (remoteId) return [{ id: remoteId }]\n } catch (error) {\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning recovery failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return null\n }\n return (await provisioningCandidates({ ...row, name, keyId: `provisioning:${idempotencyKey}` }))?.candidates ?? []\n }\n\n async function cleanupProvisioning(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n const resolved = await provisioningCandidates(row)\n if (!resolved) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'provisioning row has no recoverable remote name; migrate the row or configure legacyNameForRecord',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return false\n }\n let { name, candidates } = resolved\n if (candidates.length === 0) {\n const probed = await probeProvisioning(row, identity, name)\n if (probed === null) return false\n candidates = probed\n }\n\n const scope = { workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product: row.product }\n const active = await options.store.getActive(scope)\n const activeMatches = active && sameOwner(active, identity ?? row, product)\n const activeKeyId = activeMatches ? active.keyId : null\n const toRevoke = candidates\n .map((candidate) => candidate.id.trim())\n .filter((candidateId) => candidateId && candidateId !== activeKeyId)\n\n for (const keyId of toRevoke) {\n try {\n await recoveryProvisioner.revokeKey(keyId, slotOf(row))\n } catch (error) {\n const settled = await settleFailedRevoke(row, keyId, error)\n if (settled === 'gone') continue\n if (settled) return true\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n if (candidates.length > 0) {\n await options.store.markRevoked(row.id, now())\n } else if (now().getTime() >= row.expiresAt.getTime() + ORPHAN_AFTER_EXPIRY_GRACE_MS) {\n // An empty lookup cannot prove no child exists, but any child this row's create made\n // carries this expiry and can no longer spend; retrying forever would block issuance.\n await options.store.markOrphaned(row.id, 'no remote child matched the durable provisioning record before its expiry')\n } else {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'no remote child matched the durable provisioning record; retrying crash recovery',\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n return true\n }\n\n async function reconcileProvisioning(identity: WorkspaceKeyIdentity): Promise<void> {\n const scope = scopeFor(identity, product)\n const rows = await options.store.listProvisioning(scope)\n for (const row of rows) {\n if (!(await cleanupProvisioning(row, identity))) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n }\n return { revokePending, markPending, cleanupProvisioning, reconcileProvisioning }\n}\n\nfunction createWorkspaceKeyMinter(\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n keyLifetimeMs: ReturnType<typeof requirePositive>,\n product: string,\n markPending: ReturnType<typeof createWorkspaceKeyRecovery>['markPending'],\n cleanupProvisioning: ReturnType<typeof createWorkspaceKeyRecovery>['cleanupProvisioning'],\n revokePending: ReturnType<typeof createWorkspaceKeyRecovery>['revokePending'],\n) {\n async function mint(\n identity: WorkspaceKeyIdentity,\n budgetUsd: number,\n onRemoteKey?: (row: DurableWorkspaceKeyProvisioningRecord, remoteId: string) => void,\n ): Promise<WorkspaceRuntimeKey> {\n await assertWorkspaceKeyCryptoUsable(options.crypto)\n const mintOperationId = operationId()\n const createdAt = now()\n const expiresAt = new Date(createdAt.getTime() + keyLifetimeMs)\n const name = (options.nameForIdentity?.(identity, mintOperationId) ?? defaultKeyName(identity, product, mintOperationId)).trim()\n if (!name) throw new Error('workspace child key remote name is required')\n const rowId = operationId()\n const idempotencyKey = `workspace-key:${rowId}`\n const provisioningRow: DurableWorkspaceKeyProvisioningRecord = {\n id: rowId,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n product,\n platformUserId: identity.platformUserId,\n sourceKeyId: sourceKeyId(identity),\n sourceKeyFingerprint: identity.sourceKeyFingerprint,\n name,\n idempotencyKey,\n keyId: `provisioning:${mintOperationId}`,\n keyEncrypted: '',\n budgetUsd,\n expiresAt,\n status: 'provisioning',\n revocationAttempts: 0,\n nextRevocationAt: null,\n lastRevocationError: null,\n createdAt,\n }\n await options.store.insertProvisioning(provisioningRow)\n\n let created: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['createKey']>>\n try {\n created = await options.provisioner.createKey({\n name,\n product,\n budgetUsd,\n expiresAt: expiresAt.toISOString(),\n idempotencyKey,\n })\n } catch (error) {\n // Keep cleanup running even when the state write fails. The remote\n // request may have committed before its response failed.\n try {\n await markPending(rowId, error, false)\n } catch {\n // cleanupProvisioning below can still find the remote name.\n }\n try {\n await cleanupProvisioning({ ...provisioningRow, status: 'revocation_pending' }, identity)\n } catch (cleanupError) {\n throw new Error('remote create failed and its cleanup could not be completed', { cause: cleanupError })\n }\n throw error\n }\n\n const remoteId = created.id?.trim() ?? ''\n const secret = created.key?.trim() ?? ''\n if (!remoteId || !secret) {\n if (remoteId) {\n try {\n await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n } catch {\n // revokePending uses the returned id even when this state write fails.\n }\n }\n try {\n await markPending(rowId, new Error('remote create returned no usable child key'), false)\n } catch {\n // Always attempt remote cleanup below.\n }\n const pendingRow = { ...provisioningRow, keyId: remoteId || provisioningRow.keyId, status: 'revocation_pending' as const }\n await revokePending(pendingRow, identity)\n throw new Error('remote create returned no usable child key')\n }\n\n let cleanupRow = provisioningRow\n onRemoteKey?.(cleanupRow, remoteId)\n\n async function retainRetiredCreatorCleanup(): Promise<void> {\n // A retired row cannot hold another pending transition. Persist the\n // returned child separately before revocation so a failed revoke survives restart.\n const retainedRow = { ...provisioningRow, id: operationId(), keyId: remoteId }\n try {\n await options.store.insertProvisioning(retainedRow)\n } catch (cause) {\n throw new Error('returned child cleanup record could not be persisted', { cause })\n }\n cleanupRow = retainedRow\n onRemoteKey?.(cleanupRow, remoteId)\n }\n\n try {\n const recorded = await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n if (!recorded) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before the remote id was recorded')\n }\n const keyEncrypted = await options.crypto.encrypt(secret)\n const remoteExpiresAt = created.expiresAt?.trim()\n const activeExpiresAt = remoteExpiresAt ? new Date(remoteExpiresAt) : expiresAt\n if (!Number.isFinite(activeExpiresAt.getTime())) throw new Error('remote child key expiry is malformed')\n const activeBudgetUsd = created.budgetUsd ?? budgetUsd\n if (!Number.isFinite(activeBudgetUsd) || activeBudgetUsd < 0) throw new Error('remote child key budget is malformed')\n const activated = await markActive(options.store, {\n id: rowId,\n keyId: remoteId,\n keyEncrypted,\n expiresAt: activeExpiresAt,\n budgetUsd: activeBudgetUsd,\n })\n if (!activated) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before activation')\n }\n } catch (error) {\n // A persistence failure must not strand the already-created remote key.\n try {\n await markPending(cleanupRow.id, error, false)\n } catch {\n // revokePending below still has the remote id and attempts cleanup.\n }\n await revokePending({ ...cleanupRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row || row.keyId !== remoteId || !sameIdentity(row, identity, product)) {\n const error = new Error('workspace child key was not persisted as active')\n try {\n await options.store.markRevocationPending({\n id: rowId,\n error: error.message,\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n } catch {\n // The remote id is still available for the cleanup attempt below.\n }\n await revokePending({ ...provisioningRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n const usage = usageFromRemote(row, {\n budgetUsd: created.budgetUsd,\n budgetSpent: 0,\n expiresAt: created.expiresAt ?? expiresAt.toISOString(),\n }, now())\n return { key: secret, usage, refreshed: true }\n }\n return { mint }\n}\n","import { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\n\n/**\n * Per-workspace budget-capped model keys — app-owned billing, metered on Tangle.\n *\n * Each workspace (the paying entity) runs the agent on its OWN child API key\n * minted from the platform parent key. The child carries a hard USD budget the\n * Tangle Router enforces AT THE KEY — model spend can't exceed the allowance,\n * zero app-side accounting. The app charges its own subscription (e.g. 5× the\n * allowance) and re-provisions each period. Child budgets are IMMUTABLE on the\n * platform, so a new budget = a fresh key + revoke the prior (rotate).\n *\n * The mint / rotate / rollover / usage LOGIC is generic and lives here.\n * Persistence (which D1 table), secret encryption, and key provisioning are\n * SEAMS each product supplies — so this module imports no DB and no key-mgmt\n * SDK (structural contracts only, like `../tangle`). The `@tangle-network/tcloud`\n * SDK is the provisioner a product passes in; it is not a dependency here.\n */\n\n/** The key-provisioning operations the key manager needs. Wire it from the\n * platform via {@link createTcloudKeyProvisioner} rather than casting. */\nexport interface KeyProvisioner {\n createKey(input: { name: string; product: string; budgetUsd: number; expiresAt: string }): Promise<{ id?: string; key?: string }>\n revokeKey(keyId: string): Promise<unknown>\n getKey(keyId: string): Promise<{ budgetUsd?: number; budgetSpent?: number; expiresAt?: string | null }>\n}\n\n/**\n * The subset of the `@tangle-network/tcloud` `TCloudClient` the provisioner uses\n * — declared with METHOD syntax so the real client (whose `product` is a narrow\n * union and whose budgets are `number | null`) is assignable bivariantly. The\n * real SDK client satisfies this; pass it straight in.\n */\nexport interface TcloudKeyClient {\n createKey(opts: {\n name: string\n product?: string\n budgetUsd?: number\n expiresAt?: string\n parentKeyId?: string\n allowedModels?: string[]\n rpmLimit?: number\n }): Promise<{ id: string; key: string }>\n getKey(id: string): Promise<{ budgetUsd?: number | null; budgetSpent?: number; expiresAt?: string | null }>\n revokeKey(id: string): Promise<unknown>\n}\n\n/**\n * Adapt the tcloud SDK client to {@link KeyProvisioner} — the typed seam that\n * replaces the `as unknown as KeyProvisioner` cast every consumer otherwise\n * repeats. The platform already exposes child-key minting (parent→child key,\n * per-key USD budget, expiry); this maps its shapes (`product` union,\n * `number | null` budgets) onto the manager's contract (`null → undefined`).\n */\nexport function createTcloudKeyProvisioner(client: TcloudKeyClient): KeyProvisioner {\n return {\n createKey: async (input) => {\n const created = await client.createKey(input)\n return { id: created.id, key: created.key }\n },\n revokeKey: (keyId) => client.revokeKey(keyId),\n getKey: async (keyId) => {\n const info = await client.getKey(keyId)\n return {\n budgetUsd: info.budgetUsd ?? undefined,\n budgetSpent: info.budgetSpent ?? undefined,\n expiresAt: info.expiresAt ?? null,\n }\n },\n }\n}\n\n/** A stored child-key record (the app's row, shape-normalized). */\nexport interface WorkspaceKeyRecord {\n /** App row id (opaque). */\n id: string\n keyId: string\n /** The encrypted secret — decrypted via {@link KeyCrypto.decrypt}. */\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date | null\n}\n\n/** Persistence seam — the product implements this against its own D1 table. */\nexport interface WorkspaceKeyStore {\n /** Most-recent active key for the workspace, or null. */\n getActive(workspaceId: string): Promise<WorkspaceKeyRecord | null>\n /** All active keys (to revoke priors on rotate). */\n listActive(workspaceId: string): Promise<Array<{ id: string; keyId: string }>>\n /** Persist a freshly minted active key. */\n insert(record: { workspaceId: string; keyId: string; keyEncrypted: string; budgetUsd: number; expiresAt: Date }): Promise<void>\n /** Mark a prior row revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n}\n\n/** Secret encryption seam (the app's at-rest crypto). */\nexport interface KeyCrypto {\n encrypt(secret: string): Promise<string>\n decrypt(encrypted: string): Promise<string>\n}\n\n/** Define configuration options for managing workspace keys including provisioning, storage, and cryptography */\nexport interface WorkspaceKeyManagerOptions {\n provisioner: KeyProvisioner\n store: WorkspaceKeyStore\n crypto: KeyCrypto\n /** Default monthly allowance (USD) when a call doesn't specify one. */\n defaultBudgetUsd: number\n /** Injectable clock. Default `() => new Date()`. */\n now?: () => Date\n /** tcloud product the key is scoped to. Default `'router'`. */\n product?: string\n}\n\n/** Describe usage and budget details for a workspace model key including expiration and exhaustion status */\nexport interface WorkspaceModelKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string | null\n exhausted: boolean\n}\n\n/** Manage workspace keys by ensuring, rotating, and tracking usage of active child-key secrets */\nexport interface WorkspaceKeyManager {\n /** The workspace's active child-key secret, provisioning one if absent/expired. */\n ensureKey(workspaceId: string, opts?: { budgetUsd?: number }): Promise<string>\n /** Mint a fresh key + revoke priors (period renewal / top-up). `rollover`\n * carries the prior key's unused budget into the new one, bounded by\n * `rolloverCapUsd`. Returns the new secret. */\n rotateKey(workspaceId: string, opts?: { budgetUsd?: number; rollover?: boolean; rolloverCapUsd?: number }): Promise<string>\n /** Live budget usage for the active key (drives the \"$X of $Y used\" panel). */\n getUsage(workspaceId: string): Promise<WorkspaceModelKeyUsage | null>\n}\n\n/** Period end = first day of next month, midnight UTC. Keys expire at the period\n * boundary so a forgotten rotation fails closed rather than running free. */\nfunction nextPeriodEnd(now: Date): Date {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0))\n}\n\n// ---------------------------------------------------------------------------\n// Shared-platform-balance billing\n//\n// A DIFFERENT model from the per-workspace child-key manager above: here every\n// user runs against a SHARED platform balance (id.tangle.tools), keyed by the\n// user's platform identity. The app owns no key minting — it reads the balance,\n// gates a billable turn, and deducts spend through the platform billing API.\n// Plan limits, the platform transport, and identity resolution are SEAMS the\n// product supplies; this module imports no DB and no HTTP client.\n// ---------------------------------------------------------------------------\n\n/** A user's resolved platform identity (from the app's SSO account store). */\nexport interface PlatformIdentity {\n platformUserId: string\n /** The user's per-user platform API key (reads), or null when unlinked. */\n apiKey: string | null\n}\n\n/** Spendable balance for a platform user. */\nexport interface PlatformBalanceInfo {\n balance: number\n lifetimeSpent: number\n}\n\n/** Per-product spend aggregate. */\nexport interface PlatformProductUsage {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Plan limits — a PARAMETER per product (dollar allowance, concurrency,\n * overage policy). Never baked into the framework. */\nexport interface PlanLimit {\n monthlyBalanceUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * The platform billing transport — the product wires these to id.tangle.tools\n * (or any balance backend). Reads authenticate as the user (their `apiKey`);\n * the deduct write is a service-token call naming the target user. This module\n * never touches HTTP — it only sequences these calls.\n */\nexport interface PlatformBillingClient<Plan extends string> {\n /** Resolve the user's platform identity, or null when there is no SSO account. */\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n /** Subscription plan for the user (via their platform key). */\n getPlan(apiKey: string): Promise<Plan>\n /** Spendable balance for the user (via their platform key). */\n getBalance(apiKey: string): Promise<PlatformBalanceInfo>\n /** Per-product usage rows for the user (via their platform key). */\n getUsageByProduct(apiKey: string): Promise<PlatformProductUsage[]>\n /** Deduct spend against the user's balance (service-token write). */\n deduct(input: { platformUserId: string; amountUsd: number; type: string; description: string; referenceId: string; keyId?: string }): Promise<void>\n}\n\n/** Define shared billing state including user ID, plan, balances, concurrency, and overage permission */\nexport interface SharedBillingState<Plan extends string> {\n /** Platform user id, or null when the user has no Tangle SSO account. */\n platformUserId: string | null\n plan: Plan\n monthlyBalanceUsd: number\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Reads one platform key's plan and balance for {@link readSharedBillingState}. */\nexport interface SharedBillingReads<Plan extends string> {\n getPlan(apiKey: string): Promise<Plan>\n getBalance(apiKey: string): Promise<PlatformBalanceInfo>\n /** Plan → limits map (the product's pricing). */\n planLimits: Record<Plan, PlanLimit>\n /** The plan a key-less user falls to. */\n freePlan: Plan\n}\n\n/**\n * The plan, limits and balance behind one platform key. No key means the user\n * is not linked: the free plan with zero balance, and no read is issued with\n * an empty key.\n */\nexport async function readSharedBillingState<Plan extends string>(\n apiKey: string | null | undefined,\n reads: SharedBillingReads<Plan>,\n): Promise<Omit<SharedBillingState<Plan>, 'platformUserId'>> {\n if (!apiKey) {\n const limits = reads.planLimits[reads.freePlan]\n return {\n plan: reads.freePlan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n }\n const [plan, balance] = await Promise.all([reads.getPlan(apiKey), reads.getBalance(apiKey)])\n const limits = reads.planLimits[plan]\n return {\n plan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n}\n\n/** Define configuration options for managing platform balance based on billing plans */\nexport interface PlatformBalanceManagerOptions<Plan extends string> {\n client: PlatformBillingClient<Plan>\n /** Plan → limits map (the product's pricing). */\n planLimits: Record<Plan, PlanLimit>\n /** The plan an unlinked / outage user falls to (fails CLOSED). */\n freePlan: Plan\n /** The product slug to attribute usage to (for `getProductUsage`). */\n productSlug: string\n}\n\n/** Manage user plans and balances including state retrieval, billing authorization, deduction, and usage tracking */\nexport interface PlatformBalanceManager<Plan extends string> {\n /** Resolve the user's plan + balance. Unlinked or platform-outage users fail\n * CLOSED: free plan, zero remaining balance — a billable run is never started\n * against an unknown balance. */\n getState(userId: string): Promise<SharedBillingState<Plan>>\n /** Gate a billable turn: allowed when the plan permits overage or remaining\n * balance is positive. Returns the state so the caller deducts against it. */\n canStartBillableTurn(userId: string): Promise<{ allowed: boolean; state: SharedBillingState<Plan> }>\n /** Deduct `amountUsd` against the user's platform balance. Throws when the\n * user is not platform-linked. */\n deduct(userId: string, params: { amountUsd: number; type: string; description: string; referenceId: string; keyId?: string }): Promise<void>\n /** This product's spend for the user (drives a usage panel). */\n getProductUsage(userId: string): Promise<{ spentUsd: number; transactionCount: number }>\n}\n\n/** Create a platform balance manager to handle user plan limits and state based on provided options */\nexport function createPlatformBalanceManager<Plan extends string>(\n opts: PlatformBalanceManagerOptions<Plan>,\n): PlatformBalanceManager<Plan> {\n const { client, planLimits, freePlan, productSlug } = opts\n\n const getState: PlatformBalanceManager<Plan>['getState'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n // No SSO account, or linked without a platform key: unlinked free tier with\n // zero balance.\n const state = await readSharedBillingState(identity?.apiKey, {\n getPlan: (apiKey) => client.getPlan(apiKey),\n getBalance: (apiKey) => client.getBalance(apiKey),\n planLimits,\n freePlan,\n })\n return { platformUserId: identity?.platformUserId ?? null, ...state }\n }\n\n const canStartBillableTurn: PlatformBalanceManager<Plan>['canStartBillableTurn'] = async (userId) => {\n const state = await getState(userId)\n if (!state.platformUserId) return { allowed: false, state }\n const allowed = state.overageAllowed || state.remainingBalanceUsd > 0\n return { allowed, state }\n }\n\n const deduct: PlatformBalanceManager<Plan>['deduct'] = async (userId, params) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity) throw new Error('Shared billing requires a platform-linked user')\n await client.deduct({\n platformUserId: identity.platformUserId,\n amountUsd: params.amountUsd,\n type: params.type,\n description: params.description,\n referenceId: params.referenceId,\n keyId: params.keyId,\n })\n }\n\n const getProductUsage: PlatformBalanceManager<Plan>['getProductUsage'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity?.apiKey) return { spentUsd: 0, transactionCount: 0 }\n const rows = await client.getUsageByProduct(identity.apiKey)\n const product = rows.find((row) => row.product === productSlug)\n return { spentUsd: product?.totalSpent ?? 0, transactionCount: product?.count ?? 0 }\n }\n\n return { getState, canStartBillableTurn, deduct, getProductUsage }\n}\n\n/** Create a workspace key manager that handles key provisioning and budget tracking */\nexport function createWorkspaceKeyManager(opts: WorkspaceKeyManagerOptions): WorkspaceKeyManager {\n const clock = opts.now ?? (() => new Date())\n const product = opts.product ?? 'router'\n\n const getUsage: WorkspaceKeyManager['getUsage'] = async (workspaceId) => {\n const active = await opts.store.getActive(workspaceId)\n if (!active) return null\n const info = await opts.provisioner.getKey(active.keyId)\n const budgetUsd = info.budgetUsd ?? active.budgetUsd\n const budgetSpent = info.budgetSpent ?? 0\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: active.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt: info.expiresAt ?? (active.expiresAt ? active.expiresAt.toISOString() : null),\n exhausted: budgetRemaining <= 0,\n }\n }\n\n const rotateKey: WorkspaceKeyManager['rotateKey'] = async (workspaceId, ropts) => {\n const now = clock()\n const allowance = ropts?.budgetUsd ?? opts.defaultBudgetUsd\n\n let budgetUsd = allowance\n if (ropts?.rollover) {\n const prior = await getUsage(workspaceId).catch(() => null)\n budgetUsd = allowance + (prior?.budgetRemaining ?? 0)\n if (ropts.rolloverCapUsd != null) budgetUsd = Math.min(budgetUsd, ropts.rolloverCapUsd)\n }\n\n // Prove the at-rest crypto seam is usable BEFORE spending a platform mint.\n // The `KeyCrypto` impl may close over an env-resolved key (createFieldCrypto)\n // that is empty/invalid and only throws at encrypt time — after the mint —\n // orphaning the child key. A round-trip probe makes a misconfigured consumer\n // fail loud with ZERO platform spend.\n await assertWorkspaceKeyCryptoUsable(opts.crypto)\n\n const expiresAt = nextPeriodEnd(now)\n const created = await opts.provisioner.createKey({ name: `ws:${workspaceId}`, product, budgetUsd, expiresAt: expiresAt.toISOString() })\n if (!created.key || !created.id) throw new Error('tcloud createKey returned no key')\n const mintedKeyId = created.id\n\n // Past this point the platform has minted a budget-bearing child key. ANY\n // failure before the row is persisted (encrypt, insert) MUST revoke the\n // just-minted key, else it leaks as a zombie holding parent-key headroom —\n // a missing/invalid encryption key would otherwise burn the child budget\n // per mint attempt until the parent can no longer mint (fleet-wide outage).\n let keyEncrypted: string\n let priors: Array<{ id: string; keyId: string }>\n try {\n keyEncrypted = await opts.crypto.encrypt(created.key)\n priors = await opts.store.listActive(workspaceId)\n await opts.store.insert({ workspaceId, keyId: mintedKeyId, keyEncrypted, budgetUsd, expiresAt })\n } catch (err) {\n // Best-effort revoke of the orphan. A revoke failure must NOT mask the\n // original cause — log it loudly and rethrow the original error.\n try {\n await opts.provisioner.revokeKey(mintedKeyId)\n } catch (revokeErr) {\n console.error(\n `[workspace-key-manager] FAILED to revoke orphaned child key ${mintedKeyId} ` +\n `for workspace ${workspaceId} after a post-mint failure — it now leaks parent-key budget. ` +\n `Revoke error:`,\n revokeErr,\n )\n }\n throw err\n }\n\n for (const p of priors) {\n await opts.store.markRevoked(p.id, now)\n // Best-effort upstream revoke — the row is already revoked and an expired\n // key fails closed regardless, so a transient error is non-fatal.\n try {\n await opts.provisioner.revokeKey(p.keyId)\n } catch {\n /* non-fatal */\n }\n }\n return created.key\n }\n\n const ensureKey: WorkspaceKeyManager['ensureKey'] = async (workspaceId, eopts) => {\n const now = clock()\n const active = await opts.store.getActive(workspaceId)\n if (active && (!active.expiresAt || active.expiresAt.getTime() > now.getTime())) {\n return opts.crypto.decrypt(active.keyEncrypted)\n }\n // An expired child can no longer spend, yet the platform keeps its budget\n // reserved on the parent until it is revoked. Revoke it BEFORE minting the\n // renewal: minting first needs a second child's budget of headroom, so a\n // fully reserved parent could never renew and the expired key would hold\n // its reservation forever. Best-effort: on failure the row stays active and\n // rotateKey retries the revoke after its mint.\n if (active) {\n try {\n await opts.provisioner.revokeKey(active.keyId)\n await opts.store.markRevoked(active.id, now)\n } catch {\n /* rotateKey revokes remaining priors after the mint */\n }\n }\n return rotateKey(workspaceId, { budgetUsd: eopts?.budgetUsd })\n }\n\n return { ensureKey, rotateKey, getUsage }\n}\n\nexport {\n createIdentityBoundWorkspaceKeyManager,\n type DurableWorkspaceKeyManager,\n type DurableWorkspaceKeyManagerOptions,\n type DurableWorkspaceKeyCreateInput,\n type DurableWorkspaceKeyConditionalWrites,\n type DurableWorkspaceKeyProvisioner,\n type DurableWorkspaceKeyProvisioningRecord,\n type DurableWorkspaceKeyRecord,\n type DurableWorkspaceKeyScope,\n type DurableWorkspaceKeyStore,\n type WorkspaceKeyIdentity,\n type WorkspaceKeyProduct,\n type WorkspaceKeyStatus,\n type WorkspaceKeyUsage,\n type WorkspaceRuntimeKey,\n} from './identity-bound'\n"],"mappings":";;;;;AAEO,SAAS,wBACd,aACA,SACA,KACA,SACA,aACA,sBACAA,cACAC,QACA;AACA,QAAM,aAAa,oBAAI,IAA2B;AAElD,iBAAe,cAAiB,OAAe,MAAoC;AACjF,UAAM,WAAW,WAAW,IAAI,KAAK,KAAK,QAAQ,QAAQ;AAC1D,QAAI;AACJ,UAAM,UAAU,IAAI,QAAc,CAAC,YAAY;AAAE,gBAAU;AAAA,IAAQ,CAAC;AACpE,eAAW,IAAI,OAAO,OAAO;AAC7B,UAAM;AACN,QAAI;AACF,aAAO,MAAM,KAAK;AAAA,IACpB,UAAE;AACA,cAAQ;AACR,UAAI,WAAW,IAAI,KAAK,MAAM,QAAS,YAAW,OAAO,KAAK;AAAA,IAChE;AAAA,EACF;AAEA,iBAAe,iBACb,OACA,MACA,aACY;AACZ,UAAM,mBAAmBD,aAAY;AACrC,UAAM,YAAY,KAAK,IAAI;AAC3B,QAAI,WAAW;AACf,WAAO,CAAC,YAAY,KAAK,IAAI,IAAI,aAAa,aAAa;AACzD,iBAAW,MAAM,QAAQ,MAAM,aAAa,OAAO,kBAAkB,IAAI,GAAG,OAAO;AACnF,UAAI,CAAC,SAAU,OAAMC,OAAM,WAAW;AAAA,IACxC;AACA,QAAI,CAAC,SAAU,OAAM,IAAI,MA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IAChD;AAOA,QAAI,QAAQ;AACV,UAAI;AACF,cAAM,KAAK,YAAY,UAAU,OAAO,KAAK;AAC7C,cAAM,KAAK,MAAM,YAAY,OAAO,IAAI,GAAG;AAAA,MAC7C,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,UAAU,aAAa,EAAE,WAAW,OAAO,UAAU,CAAC;AAAA,EAC/D;AAEA,SAAO,EAAE,WAAW,WAAW,SAAS;AAC1C;","names":["operationId","sleep","sourceKeyId","operationId","limits"]}
|
|
@@ -1 +0,0 @@
|
|
|
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 lockPark: '/chat-turn-lock/park',\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 // Snapshot the clock BEFORE the probes and use that one instant for BOTH the\n // grace decision and the release fence on every branch: the release is only\n // valid against the lock as it was when the state was observed, not after an\n // arbitrarily slow round trip. Re-reading the clock after a probe would let a\n // slow round trip age the lock past the grace on paper, and would hand the\n // store a fence newer than a successor lock acquired meanwhile.\n const observedAt = (options.now ?? Date.now)()\n let sandbox: StaleTurnLockSandboxProbeResult\n try {\n sandbox = await options.probeSandbox()\n } catch (err) {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: 'SANDBOX_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (sandbox.status !== 'running') {\n return forceReleaseUnreachable(options, observedAt, {\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 let session: StaleTurnLockSessionProbeResult\n try {\n session = await options.probeSession()\n } catch (err) {\n return forceReleaseUnreachable(options, observedAt, {\n unreachableReason: 'SESSION_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (!session.reachable) {\n return forceReleaseUnreachable(options, observedAt, {\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 * The caller's pre-probe clock read (`observedAt`) serves as the age gate AND\n * the release fence here too, exactly as on the terminal branch.\n */\nasync function forceReleaseUnreachable(\n options: ReconcileStaleTurnLockOptions,\n observedAt: number,\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 lockAgeMs = observedAt - 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 })\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/** Park the exact lock's release for its durable owner; any answer but a parked 200 leaves the lock held. */\nexport async function parkDurableTurnLock(namespace: TurnStreamNamespaceLike, input: TurnLockReleaseInput, auth: TurnStreamAuth): Promise<boolean> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n return (await postJsonOk<{ deferred?: boolean }>(namespace, key, TURN_STREAM_PATHS.lockPark, input, auth)).deferred === true\n}\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: TurnLockInterruptedReleaseInput,\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/** What the box a held lock's turn ran work on reports: executions still active and sessions seen, or no answer. */\nexport type HolderBoxReport = { live: number; sessions: number } | 'unreachable' | 'timeout'\n\n/** Whether a held lock's turn still runs, in the owner rule's terms; diagnostics are counts and classes only. */\ntype HolderEvidence = { status: 'live' | 'abandoned' | 'unknown'; diagnostics: Record<string, unknown> }\n\n/**\n * The reclaim for a lock whose turn died with its invocation (a closed tab, a runtime limit), which releases nothing,\n * so without it the lock refuses every turn in its scope until its TTL. A live turn renews its running row every 30 s,\n * so a holder thread with an unexpired running turn holds. Box work a turn started (a sandbox turn, a detached computer\n * step) outlives the invocation, so with no running row the box answers next: an active execution there holds. Without\n * `readHolderBox` no box is read. A holder with neither is released past the policy's terminal grace, so a turn must\n * write its running row within that grace of taking the lock. A parked release and a store that cannot answer hold. A\n * box that does not answer sends a lock to the policy's unreachable bound; a durable-Stop lock goes through the owner\n * rule on the same evidence, where an unanswered read is `unknown` and holds. The 409 carries counts and classes only.\n * Enable it through `createDurableTurnLock`'s `turnStore` rather than as a product `reconcile`: only that lock makes the\n * routes write the early running row and hold a handed-off lock, which this evidence relies on.\n */\nexport async function reconcileTurnLockFromStoreAndBox(input: {\n namespace: TurnStreamNamespaceLike\n auth: TurnStreamAuth\n turnStore: Required<Pick<TurnEventStore, 'listRunning'>>\n readHolderBox?(active: DurableTurnLock): Promise<HolderBoxReport>\n active: DurableTurnLock\n /** The policy's clock. Default `Date.now`. */\n now?(): number\n}): Promise<{ released: boolean; diagnostics: Record<string, unknown> }> {\n const { active, turnStore, readHolderBox } = input\n const unknown = (probeError: string): HolderEvidence => ({ status: 'unknown', diagnostics: { probeError } })\n // A failed read is logged here by class; its message never reaches the 409.\n const unreadable = (probeError: string, error: unknown) => {\n console.warn('[turn-lock] held lock evidence unreadable', { class: probeError, error: error instanceof Error ? error.name : typeof error,\n workspaceId: active.workspaceId, lockId: active.lockId })\n return unknown(probeError)\n }\n const evidence = async (): Promise<HolderEvidence> => {\n if (active.releasePending) return { status: 'live', diagnostics: { releasePending: true } }\n let running: string[]\n try { running = await turnStore.listRunning(active.threadId) }\n catch (error) { return unreadable('turn_store_unreadable', error) }\n if (running.length > 0) return { status: 'live', diagnostics: { runningTurns: running.length } }\n let box: HolderBoxReport\n try { box = readHolderBox ? await readHolderBox(active) : { live: 0, sessions: 0 } }\n catch (error) { return unreadable('box_unreachable', error) }\n if (box === 'unreachable' || box === 'timeout') return unknown(box === 'timeout' ? 'box_read_timeout' : 'box_unreachable')\n if (box.live > 0) return { status: 'live', diagnostics: { liveBoxSessions: box.live, boxSessions: box.sessions } }\n return { status: 'abandoned', diagnostics: { runningTurns: 0, liveBoxSessions: 0, boxSessions: box.sessions } }\n }\n return reconcileStaleDurableTurnLock({\n namespace: input.namespace, auth: input.auth, workspaceId: active.workspaceId, threadId: active.threadId, active, now: input.now,\n context: { workspaceId: active.workspaceId, threadId: active.threadId, executionId: active.executionId, lockId: active.lockId },\n probeSandbox: async () => ({ status: 'running' }),\n // A native lock: an unreadable store holds; a box that does not answer goes to the policy's unreachable bound.\n probeSession: async () => {\n const { status, diagnostics } = await evidence()\n if (status === 'unknown' && diagnostics.probeError !== 'turn_store_unreadable') return { reachable: false, reason: String(diagnostics.probeError) }\n return { reachable: true, terminal: status === 'abandoned', diagnostics }\n },\n // A durable-Stop lock: the owner rule judges the same evidence; unknown holds.\n probeOwner: async identity => ({ identity, ...await evidence() }),\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 /** The store the routes renew running turns in. Given it and no `reconcile`, a dead holder is reclaimed\n * ({@link reconcileTurnLockFromStoreAndBox}). */\n turnStore?: Required<Pick<TurnEventStore, 'listRunning'>>\n /** Read the box the holder's turn ran work on (`readHolderBoxSessions` from `/sandbox`). Omit when turns run no box\n * work: the default reclaim then reads the turn store alone. */\n readHolderBox?(active: DurableTurnLock): Promise<HolderBoxReport>\n /** The stale-lock policy's clock for the default reclaim, for tests and simulations; the lock's own start stays the\n * Durable Object's wall clock. Default `Date.now`. */\n now?(): number\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 → {@link reconcileTurnLockFromStoreAndBox} when `turnStore` is given, else a refused\n * 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 park(handle: unknown): Promise<boolean>\n /** Present only with the default reclaim: a handed-off turn's lock is parked so the reclaim reads it as held. */\n holdForHandoff?(handle: unknown): Promise<boolean>\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 const { turnStore } = options\n const reconcile = options.reconcile ?? (turnStore\n ? (_args: TurnLockSeamArgs<TContext>, active: DurableTurnLock) => reconcileTurnLockFromStoreAndBox({\n namespace, auth: options.auth, turnStore, readHolderBox: options.readHolderBox, active, now: options.now })\n : undefined)\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 && reconcile) {\n const reconciled = await 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 async park(handle) {\n return Boolean(handle) && parkDurableTurnLock(namespace, handle as TurnLockReleaseInput, options.auth)\n },\n // A product reconciler or a lock without the default reads `releasePending` its own way; leave it untouched.\n ...(turnStore && !options.reconcile\n ? { holdForHandoff: async (handle: unknown) => Boolean(handle) && parkDurableTurnLock(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; 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,QAAQ,IAAI;AAC9B,MAAI,CAAC,CAAC,gBAAgB,eAAe,eAAe,EAAE,SAAS,OAAO,KACjE,CAAC,YAAY,CAAC,CAAC,UAAU,WAAW,EAAE,SAAS,SAAS,KAAK,KAC7D,CAAC,SAAS,aAAa,SAAS,UAAU,SAAS,aAAa,SAAS,QAAQ,SAAS,YAAY,EACtG,KAAK,WAAS,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,CAAC,EAAG,OAAM,IAAI,MAAM,oCAAoC;AACpH,SAAO,oBAAoB,KAAK,UAAU;AAAA,IAAC;AAAA,IAAS,SAAS;AAA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