@tangle-network/agent-app 0.62.4 → 0.63.0
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/README.md +1 -1
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +4 -1
- package/dist/agent-profiles/index.js +1 -1
- package/dist/app-auth/index.js +2 -2
- package/dist/assistant/index.js +7 -7
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/cancellation.d.ts +61 -0
- package/dist/chat-routes/dispatch-first.d.ts +14 -25
- package/dist/chat-routes/early-turn-work.d.ts +10 -0
- package/dist/chat-routes/hybrid-producer.d.ts +4 -3
- package/dist/chat-routes/index.d.ts +2 -1
- package/dist/chat-routes/index.js +86 -1874
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/native-turn-timing.d.ts +15 -0
- package/dist/chat-routes/producer-stream.d.ts +5 -0
- package/dist/chat-routes/route-producer.d.ts +3 -0
- package/dist/chat-routes/route-storage.d.ts +7 -0
- package/dist/chat-routes/router-producer.d.ts +31 -5
- package/dist/chat-routes/turn-admission.d.ts +2 -1
- package/dist/chat-routes/turn-execution.d.ts +6 -11
- package/dist/chat-routes/turn-ownership.d.ts +22 -0
- package/dist/chat-routes/turn-route-contracts.d.ts +112 -105
- package/dist/chat-routes/turn-routes.d.ts +4 -4
- package/dist/chat-routes/wire.d.ts +0 -7
- package/dist/chat-store/index.d.ts +1 -1
- package/dist/chat-store/index.js +21 -3
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/schema.d.ts +3 -2
- package/dist/chat-store/store.d.ts +8 -0
- package/dist/{chunk-GIEUZBQQ.js → chunk-4CALWPN5.js} +3 -7
- package/dist/chunk-4CALWPN5.js.map +1 -0
- package/dist/chunk-4DBHC63F.js +54 -0
- package/dist/chunk-4DBHC63F.js.map +1 -0
- package/dist/{chunk-G7M2C72Q.js → chunk-5TSRFF5W.js} +1 -1
- package/dist/chunk-5TSRFF5W.js.map +1 -0
- package/dist/chunk-A2NQMVMF.js +485 -0
- package/dist/chunk-A2NQMVMF.js.map +1 -0
- package/dist/{chunk-PCAY23GS.js → chunk-AVBNS64P.js} +172 -2
- package/dist/chunk-AVBNS64P.js.map +1 -0
- package/dist/{chunk-4P5NFBWX.js → chunk-BI5AZAOO.js} +4 -4
- package/dist/chunk-BV3VZEKB.js +483 -0
- package/dist/chunk-BV3VZEKB.js.map +1 -0
- package/dist/{chunk-UW2DKTEM.js → chunk-IDG2XR5O.js} +20 -10
- package/dist/chunk-IDG2XR5O.js.map +1 -0
- package/dist/{chunk-KS4I7KVC.js → chunk-JRTWTADT.js} +184 -123
- package/dist/chunk-JRTWTADT.js.map +1 -0
- package/dist/chunk-KG2Y44XT.js +1 -0
- package/dist/chunk-KG2Y44XT.js.map +1 -0
- package/dist/chunk-MM3GOLHO.js +3365 -0
- package/dist/chunk-MM3GOLHO.js.map +1 -0
- package/dist/chunk-N6URQ6DM.js +225 -0
- package/dist/chunk-N6URQ6DM.js.map +1 -0
- package/dist/{chunk-ISRPOPMM.js → chunk-ND5XWLRU.js} +21 -18
- package/dist/chunk-ND5XWLRU.js.map +1 -0
- package/dist/{chunk-IUVDR3KJ.js → chunk-NHVSO47Q.js} +2 -2
- package/dist/{chunk-FAXSYC2C.js → chunk-RZLCBWGG.js} +2 -2
- package/dist/{chunk-MRZP65DZ.js → chunk-SRWQCWLR.js} +14 -3
- package/dist/chunk-SRWQCWLR.js.map +1 -0
- package/dist/{chunk-JRW6LCIA.js → chunk-V6YGLAQC.js} +2 -2
- package/dist/{chunk-54YIL7WM.js → chunk-WPPDNS63.js} +4 -4
- package/dist/{chunk-CQZVJVME.js → chunk-YCMVNXAX.js} +2 -2
- package/dist/design-canvas/index.js +3 -3
- package/dist/openui/index.js +3 -3
- package/dist/operator/index.js +2 -2
- package/dist/platform/billable-turn-admission.d.ts +13 -9
- package/dist/platform/delegated-keys.d.ts +4 -3
- package/dist/platform/delegated-turn-keys.d.ts +17 -6
- package/dist/platform/index.js +80 -23
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.d.ts +2 -0
- package/dist/preset-cloudflare/index.js +344 -0
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/preset-cloudflare/native-completion-owner.d.ts +90 -0
- package/dist/preset-cloudflare/native-completion-store.d.ts +56 -0
- package/dist/preset-cloudflare/native-completion-workflow.d.ts +10 -0
- package/dist/public-consultation/index.js +28 -7
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/rollout/d1.d.ts +103 -3
- package/dist/rollout/d1.js +152 -5
- package/dist/rollout/d1.js.map +1 -1
- package/dist/runtime/index.js +3 -4
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +4 -0
- package/dist/runtime/router-turn.js +2 -3
- package/dist/sandbox/index.js +3 -4
- package/dist/sandbox/sandbox-run-tool.d.ts +5 -0
- package/dist/sequences/index.js +5 -5
- package/dist/signoff/cli.js +6 -1
- package/dist/signoff/cli.js.map +1 -1
- package/dist/signoff/config.d.ts +3 -1
- package/dist/signoff/index.d.ts +2 -1
- package/dist/signoff/index.js +3 -1
- package/dist/signoff/phases.d.ts +3 -0
- package/dist/signoff/proof.js +3 -0
- package/dist/signoff/proof.js.map +1 -1
- package/dist/signoff/run.d.ts +3 -1
- package/dist/signoff/types.d.ts +13 -0
- package/dist/skills-placement/box.js +5 -5
- package/dist/skills-placement/index.js +2 -2
- package/dist/tools/index.js +1 -1
- package/dist/turn-stream/adapters.d.ts +10 -4
- package/dist/turn-stream/index.js +33 -356
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/turn-trace/index.d.ts +1 -0
- package/dist/turn-trace/index.js +4 -5
- package/dist/turn-trace/phase-timing.d.ts +20 -0
- package/dist/turn-trace/recorder.d.ts +3 -0
- package/dist/turn-trace/turn-facts.d.ts +17 -0
- package/dist/web-react/agent-profile-editor.js +1 -1
- package/dist/web-react/chat-stream.d.ts +0 -7
- package/dist/web-react/index.js +7 -9
- package/dist/work-product/index.js +7 -7
- package/package.json +1 -1
- package/dist/chat-routes/minted-thread.d.ts +0 -63
- package/dist/chunk-6R73V3Y5.js +0 -17
- package/dist/chunk-6R73V3Y5.js.map +0 -1
- package/dist/chunk-CCVWR33L.js +0 -99
- package/dist/chunk-CCVWR33L.js.map +0 -1
- package/dist/chunk-EFQUAWWF.js +0 -1749
- package/dist/chunk-EFQUAWWF.js.map +0 -1
- package/dist/chunk-G7M2C72Q.js.map +0 -1
- package/dist/chunk-GIEUZBQQ.js.map +0 -1
- package/dist/chunk-ISRPOPMM.js.map +0 -1
- package/dist/chunk-KS4I7KVC.js.map +0 -1
- package/dist/chunk-MRZP65DZ.js.map +0 -1
- package/dist/chunk-PCAY23GS.js.map +0 -1
- package/dist/chunk-UW2DKTEM.js.map +0 -1
- package/dist/chunk-VK3F4N4U.js +0 -133
- package/dist/chunk-VK3F4N4U.js.map +0 -1
- /package/dist/{chunk-4P5NFBWX.js.map → chunk-BI5AZAOO.js.map} +0 -0
- /package/dist/{chunk-IUVDR3KJ.js.map → chunk-NHVSO47Q.js.map} +0 -0
- /package/dist/{chunk-FAXSYC2C.js.map → chunk-RZLCBWGG.js.map} +0 -0
- /package/dist/{chunk-JRW6LCIA.js.map → chunk-V6YGLAQC.js.map} +0 -0
- /package/dist/{chunk-54YIL7WM.js.map → chunk-WPPDNS63.js.map} +0 -0
- /package/dist/{chunk-CQZVJVME.js.map → chunk-YCMVNXAX.js.map} +0 -0
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import {
|
|
2
|
+
base64UrlEncodeText,
|
|
3
|
+
constantTimeEqual,
|
|
4
|
+
hmacSha256Base64Url
|
|
5
|
+
} from "./chunk-S5SRJJQG.js";
|
|
6
|
+
|
|
7
|
+
// src/chat-routes/stale-turn-lock.ts
|
|
8
|
+
var DEFAULT_STALE_TURN_LOCK_GRACE_MS = 5 * 60 * 1e3;
|
|
9
|
+
var DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS = 60 * 1e3;
|
|
10
|
+
function messageOf(err) {
|
|
11
|
+
return err instanceof Error ? err.message : String(err);
|
|
12
|
+
}
|
|
13
|
+
async function reconcileStaleTurnLock(options) {
|
|
14
|
+
let sandbox;
|
|
15
|
+
try {
|
|
16
|
+
sandbox = await options.probeSandbox();
|
|
17
|
+
} catch (err) {
|
|
18
|
+
return forceReleaseUnreachable(options, {
|
|
19
|
+
unreachableReason: "SANDBOX_PROBE_FAILED",
|
|
20
|
+
unreachableDetail: messageOf(err)
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (sandbox.status !== "running") {
|
|
24
|
+
return forceReleaseUnreachable(options, {
|
|
25
|
+
unreachableReason: sandbox.status === "absent" ? "SANDBOX_ABSENT" : "SANDBOX_NOT_RUNNING",
|
|
26
|
+
...sandbox.status === "not-running" && sandbox.state !== void 0 ? { sandboxState: sandbox.state } : {}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const observedAt = (options.now ?? Date.now)();
|
|
30
|
+
let session;
|
|
31
|
+
try {
|
|
32
|
+
session = await options.probeSession();
|
|
33
|
+
} catch (err) {
|
|
34
|
+
return forceReleaseUnreachable(options, {
|
|
35
|
+
unreachableReason: "SESSION_PROBE_FAILED",
|
|
36
|
+
unreachableDetail: messageOf(err)
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (!session.reachable) {
|
|
40
|
+
return forceReleaseUnreachable(options, {
|
|
41
|
+
unreachableReason: "SESSION_UNREACHABLE",
|
|
42
|
+
...session.reason !== void 0 ? { sessionProbeError: session.reason } : {}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const diagnostics = {
|
|
46
|
+
sandboxReachable: true,
|
|
47
|
+
sessionTerminal: session.terminal,
|
|
48
|
+
...session.diagnostics ?? {}
|
|
49
|
+
};
|
|
50
|
+
if (!session.terminal) return { released: false, diagnostics };
|
|
51
|
+
const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS;
|
|
52
|
+
const lockAgeMs = observedAt - options.lockStartedAt;
|
|
53
|
+
if (lockAgeMs < terminalGraceMs) {
|
|
54
|
+
const log = options.log ?? ((message, meta) => console.warn(message, meta));
|
|
55
|
+
const withheld = {
|
|
56
|
+
...diagnostics,
|
|
57
|
+
lockAgeMs,
|
|
58
|
+
terminalReleaseGraceMs: terminalGraceMs,
|
|
59
|
+
terminalReleaseWithheld: "LOCK_WITHIN_TERMINAL_GRACE_PERIOD"
|
|
60
|
+
};
|
|
61
|
+
log("[chat-routes] stale turn lock held: terminal verdict but lock is younger than the registration window", {
|
|
62
|
+
...options.context ?? {},
|
|
63
|
+
...withheld
|
|
64
|
+
});
|
|
65
|
+
return { released: false, diagnostics: withheld };
|
|
66
|
+
}
|
|
67
|
+
const released = await options.release({ observedAt });
|
|
68
|
+
return {
|
|
69
|
+
released,
|
|
70
|
+
diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, released, observedAt }
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function forceReleaseUnreachable(options, reason) {
|
|
74
|
+
const log = options.log ?? ((message, meta) => console.warn(message, meta));
|
|
75
|
+
const graceMs = options.graceMs ?? DEFAULT_STALE_TURN_LOCK_GRACE_MS;
|
|
76
|
+
const at = (options.now ?? Date.now)();
|
|
77
|
+
const lockAgeMs = at - options.lockStartedAt;
|
|
78
|
+
const diagnostics = {
|
|
79
|
+
...reason,
|
|
80
|
+
sandboxReachable: false,
|
|
81
|
+
lockAgeMs,
|
|
82
|
+
forceReleaseGraceMs: graceMs
|
|
83
|
+
};
|
|
84
|
+
if (lockAgeMs < graceMs) {
|
|
85
|
+
log("[chat-routes] stale turn lock held: sandbox unreachable but lock is inside the grace period", {
|
|
86
|
+
...options.context ?? {},
|
|
87
|
+
...diagnostics
|
|
88
|
+
});
|
|
89
|
+
return { released: false, diagnostics: { ...diagnostics, forceReleaseWithheld: "LOCK_WITHIN_GRACE_PERIOD" } };
|
|
90
|
+
}
|
|
91
|
+
const released = await options.release({ observedAt: at });
|
|
92
|
+
log("[chat-routes] force-released stale turn lock: sandbox unreachable, no turn can be executing", {
|
|
93
|
+
...options.context ?? {},
|
|
94
|
+
...diagnostics,
|
|
95
|
+
released
|
|
96
|
+
});
|
|
97
|
+
return { released, diagnostics: { ...diagnostics, forceReleased: released } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/turn-stream/core.ts
|
|
101
|
+
var TURN_STREAM_TOKEN_TTL_MS = 6e4;
|
|
102
|
+
var TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
|
|
103
|
+
async function mintTurnStreamToken(channelName, secret, now = Date.now, ttlMs = TURN_STREAM_TOKEN_TTL_MS) {
|
|
104
|
+
if (!secret || secret.length < 32) throw new Error("turn-stream token secret must be at least 32 characters");
|
|
105
|
+
const expiresAt = now() + ttlMs;
|
|
106
|
+
const payload = `v1.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}`;
|
|
107
|
+
return `${payload}.${await hmacSha256Base64Url(payload, secret)}`;
|
|
108
|
+
}
|
|
109
|
+
async function verifyTurnStreamToken(channelName, token, secret, now = Date.now) {
|
|
110
|
+
if (!secret || secret.length < 32) return false;
|
|
111
|
+
const parts = token.split(".");
|
|
112
|
+
if (parts.length !== 4 || parts[0] !== "v1") return false;
|
|
113
|
+
const [, name, expires36, mac] = parts;
|
|
114
|
+
if (name !== base64UrlEncodeText(channelName)) return false;
|
|
115
|
+
if (!/^[0-9a-z]+$/.test(expires36)) return false;
|
|
116
|
+
const expiresAt = parseInt(expires36, 36);
|
|
117
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= now()) return false;
|
|
118
|
+
const expected = await hmacSha256Base64Url(`v1.${name}.${expires36}`, secret);
|
|
119
|
+
return constantTimeEqual(mac, expected);
|
|
120
|
+
}
|
|
121
|
+
function threadChannelKey(workspaceId, threadId) {
|
|
122
|
+
return `${workspaceId}:${threadId}`;
|
|
123
|
+
}
|
|
124
|
+
function workspaceChannelKey(workspaceId) {
|
|
125
|
+
return workspaceId;
|
|
126
|
+
}
|
|
127
|
+
function turnLockChannelKey(workspaceId, _threadId, _scope) {
|
|
128
|
+
return workspaceChannelKey(workspaceId);
|
|
129
|
+
}
|
|
130
|
+
function turnLockStorageKey(scope, threadId) {
|
|
131
|
+
return scope === "workspace" ? TURN_STREAM_STORAGE_KEYS.lock : `${TURN_STREAM_STORAGE_KEYS.threadLockPrefix}${threadId}`;
|
|
132
|
+
}
|
|
133
|
+
function turnStorageChannelKey(turnId) {
|
|
134
|
+
return `turn:${turnId}`;
|
|
135
|
+
}
|
|
136
|
+
function scopeIndexChannelKey(scopeId) {
|
|
137
|
+
return `scope:${scopeId}`;
|
|
138
|
+
}
|
|
139
|
+
var MAX_RECENT_CREATED = 50;
|
|
140
|
+
var ACTIVITY_TTL_MS = 15 * 60 * 1e3;
|
|
141
|
+
function pruneStaleThreads(active, now, ttlMs) {
|
|
142
|
+
const removed = [];
|
|
143
|
+
for (const [threadId, startedAt] of active) {
|
|
144
|
+
if (now - startedAt > ttlMs) {
|
|
145
|
+
active.delete(threadId);
|
|
146
|
+
removed.push(threadId);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return removed;
|
|
150
|
+
}
|
|
151
|
+
var TURN_LOCK_TTL_MS = 30 * 60 * 1e3;
|
|
152
|
+
function activeTurnLock(stored, now) {
|
|
153
|
+
if (!stored) return null;
|
|
154
|
+
const lock = stored.scope ? stored : { ...stored, scope: "thread" };
|
|
155
|
+
return lock.expiresAt > now ? lock : null;
|
|
156
|
+
}
|
|
157
|
+
function createTurnLock(input, now, ttlMs = TURN_LOCK_TTL_MS) {
|
|
158
|
+
return {
|
|
159
|
+
workspaceId: input.workspaceId,
|
|
160
|
+
threadId: input.threadId,
|
|
161
|
+
scope: input.scope,
|
|
162
|
+
executionId: input.executionId,
|
|
163
|
+
lockId: input.lockId,
|
|
164
|
+
startedAt: now,
|
|
165
|
+
expiresAt: now + ttlMs,
|
|
166
|
+
...input.turnId ? { turnId: input.turnId } : {}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function turnLockMatchesRelease(active, input) {
|
|
170
|
+
if (active.executionId !== input.executionId) return false;
|
|
171
|
+
if (input.lockId && active.lockId !== input.lockId) return false;
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
function interruptedReleaseApplies(active, input) {
|
|
175
|
+
if (active.threadId !== input.threadId) return false;
|
|
176
|
+
if (active.startedAt > input.interruptedAt) return false;
|
|
177
|
+
if (active.turnId) {
|
|
178
|
+
if (active.turnId !== input.turnId) return false;
|
|
179
|
+
} else if (input.turnId) {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
var TURN_STREAM_PATHS = {
|
|
185
|
+
broadcast: "/broadcast",
|
|
186
|
+
lockAcquire: "/chat-turn-lock/acquire",
|
|
187
|
+
/** Read the active lock without changing it; also brings the object up before a turn needs it. */
|
|
188
|
+
lockPeek: "/chat-turn-lock/peek",
|
|
189
|
+
lockRelease: "/chat-turn-lock/release",
|
|
190
|
+
lockReleaseInterrupted: "/chat-turn-lock/release-interrupted",
|
|
191
|
+
turnEventsAppend: "/turn-events/append",
|
|
192
|
+
turnEventsRead: "/turn-events/read",
|
|
193
|
+
turnStatusSet: "/turn-status/set",
|
|
194
|
+
turnStatusGet: "/turn-status/get",
|
|
195
|
+
scopeStatusSet: "/turn-scope/set",
|
|
196
|
+
scopeRunningList: "/turn-scope/running"
|
|
197
|
+
};
|
|
198
|
+
var TURN_STREAM_STORAGE_KEYS = {
|
|
199
|
+
lock: "chatTurnLock",
|
|
200
|
+
threadLockPrefix: "chatTurnLock:thread:",
|
|
201
|
+
activeThreads: "activeThreads",
|
|
202
|
+
turnStatus: "turnStatus",
|
|
203
|
+
turnScope: "turnScopeIndex",
|
|
204
|
+
turnEventPrefix: "turnEvent:"
|
|
205
|
+
};
|
|
206
|
+
function turnEventStorageKey(seq) {
|
|
207
|
+
return `${TURN_STREAM_STORAGE_KEYS.turnEventPrefix}${String(seq).padStart(10, "0")}`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/turn-stream/adapters.ts
|
|
211
|
+
var INTERNAL_ORIGIN = "https://turn-stream.internal";
|
|
212
|
+
async function postJson(namespace, channelKey, path, body, auth) {
|
|
213
|
+
const stub = namespace.get(namespace.idFromName(channelKey));
|
|
214
|
+
const response = await stub.fetch(`${INTERNAL_ORIGIN}${path}`, {
|
|
215
|
+
method: "POST",
|
|
216
|
+
headers: {
|
|
217
|
+
"Content-Type": "application/json",
|
|
218
|
+
[TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(channelKey, auth.secret)
|
|
219
|
+
},
|
|
220
|
+
body: JSON.stringify(body)
|
|
221
|
+
});
|
|
222
|
+
return { status: response.status, body: await response.json() };
|
|
223
|
+
}
|
|
224
|
+
async function postJsonOk(namespace, channelKey, path, body, auth) {
|
|
225
|
+
const result = await postJson(namespace, channelKey, path, body, auth);
|
|
226
|
+
if (result.status !== 200) {
|
|
227
|
+
throw new Error(`turn-stream ${path} failed with status ${result.status}`);
|
|
228
|
+
}
|
|
229
|
+
return result.body;
|
|
230
|
+
}
|
|
231
|
+
function createDurableObjectTurnEventStore(namespace, auth) {
|
|
232
|
+
return {
|
|
233
|
+
async append(turnId, events) {
|
|
234
|
+
if (!events.length) return;
|
|
235
|
+
await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events }, auth);
|
|
236
|
+
},
|
|
237
|
+
async read(turnId, fromSeq) {
|
|
238
|
+
const body = await postJsonOk(
|
|
239
|
+
namespace,
|
|
240
|
+
turnStorageChannelKey(turnId),
|
|
241
|
+
TURN_STREAM_PATHS.turnEventsRead,
|
|
242
|
+
{ fromSeq },
|
|
243
|
+
auth
|
|
244
|
+
);
|
|
245
|
+
return body.events;
|
|
246
|
+
},
|
|
247
|
+
async setStatus(turnId, status, scopeId, options) {
|
|
248
|
+
if (options?.preserveUpdatedAt || options?.onlyIfRunningBefore !== void 0) {
|
|
249
|
+
throw new Error("The turn-stream Durable Object store does not support guarded or time-preserving status writes");
|
|
250
|
+
}
|
|
251
|
+
await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status }, auth);
|
|
252
|
+
if (scopeId) {
|
|
253
|
+
await postJsonOk(namespace, scopeIndexChannelKey(scopeId), TURN_STREAM_PATHS.scopeStatusSet, {
|
|
254
|
+
turnId,
|
|
255
|
+
status
|
|
256
|
+
}, auth);
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
async getStatus(turnId) {
|
|
260
|
+
const body = await postJsonOk(
|
|
261
|
+
namespace,
|
|
262
|
+
turnStorageChannelKey(turnId),
|
|
263
|
+
TURN_STREAM_PATHS.turnStatusGet,
|
|
264
|
+
{},
|
|
265
|
+
auth
|
|
266
|
+
);
|
|
267
|
+
return body.status;
|
|
268
|
+
},
|
|
269
|
+
async listRunning(scopeId) {
|
|
270
|
+
const body = await postJsonOk(
|
|
271
|
+
namespace,
|
|
272
|
+
scopeIndexChannelKey(scopeId),
|
|
273
|
+
TURN_STREAM_PATHS.scopeRunningList,
|
|
274
|
+
{},
|
|
275
|
+
auth
|
|
276
|
+
);
|
|
277
|
+
return body.running;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
async function acquireDurableTurnLock(namespace, input, auth) {
|
|
282
|
+
const lockId = input.lockId ?? crypto.randomUUID();
|
|
283
|
+
const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
|
|
284
|
+
const result = await postJson(namespace, key, TURN_STREAM_PATHS.lockAcquire, {
|
|
285
|
+
...input,
|
|
286
|
+
lockId
|
|
287
|
+
}, auth);
|
|
288
|
+
if (result.status !== 200 && result.status !== 409) {
|
|
289
|
+
throw new Error(`turn-stream lock acquire failed with status ${result.status}`);
|
|
290
|
+
}
|
|
291
|
+
return result.body;
|
|
292
|
+
}
|
|
293
|
+
async function peekDurableTurnLock(namespace, input, auth) {
|
|
294
|
+
const key = turnLockChannelKey(input.workspaceId, input.threadId ?? "", input.scope);
|
|
295
|
+
const result = await postJson(namespace, key, TURN_STREAM_PATHS.lockPeek, {
|
|
296
|
+
scope: input.scope,
|
|
297
|
+
threadId: input.threadId
|
|
298
|
+
}, auth);
|
|
299
|
+
if (result.status !== 200) throw new Error(`turn-stream lock peek failed with status ${result.status}`);
|
|
300
|
+
return result.body.active ?? null;
|
|
301
|
+
}
|
|
302
|
+
async function releaseDurableTurnLock(namespace, input, auth) {
|
|
303
|
+
const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
|
|
304
|
+
return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth);
|
|
305
|
+
}
|
|
306
|
+
async function releaseInterruptedDurableTurnLock(namespace, input, auth) {
|
|
307
|
+
const scopes = input.scope ? [input.scope] : ["workspace", "thread"];
|
|
308
|
+
for (const scope of scopes) {
|
|
309
|
+
const key = turnLockChannelKey(input.workspaceId, input.threadId, scope);
|
|
310
|
+
const result = await postJsonOk(namespace, key, TURN_STREAM_PATHS.lockReleaseInterrupted, {
|
|
311
|
+
scope,
|
|
312
|
+
threadId: input.threadId,
|
|
313
|
+
interruptedAt: input.interruptedAt,
|
|
314
|
+
...input.turnId ? { turnId: input.turnId } : {}
|
|
315
|
+
}, auth);
|
|
316
|
+
if (result.released) return true;
|
|
317
|
+
}
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
async function reconcileStaleDurableTurnLock(options) {
|
|
321
|
+
const { namespace, auth, workspaceId, threadId, active, ...policy } = options;
|
|
322
|
+
return reconcileStaleTurnLock({
|
|
323
|
+
...policy,
|
|
324
|
+
lockStartedAt: active.startedAt,
|
|
325
|
+
release: (fence) => releaseInterruptedDurableTurnLock(namespace, {
|
|
326
|
+
workspaceId,
|
|
327
|
+
threadId: active.threadId,
|
|
328
|
+
scope: active.scope,
|
|
329
|
+
interruptedAt: fence.observedAt,
|
|
330
|
+
...active.turnId ? { turnId: active.turnId } : {}
|
|
331
|
+
}, auth)
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function defaultRefusalResponse(active, diagnostics) {
|
|
335
|
+
const workspaceConflict = active.scope === "workspace";
|
|
336
|
+
return Response.json(
|
|
337
|
+
{
|
|
338
|
+
error: {
|
|
339
|
+
code: workspaceConflict ? "workspace_turn_in_flight" : "chat_turn_in_flight",
|
|
340
|
+
message: workspaceConflict ? "A chat turn is already running for this workspace. Wait for it to finish before starting another." : "A chat turn is already running for this thread. Reconnect to the active response or wait for it to finish.",
|
|
341
|
+
threadId: active.threadId,
|
|
342
|
+
executionId: active.executionId,
|
|
343
|
+
...active.turnId ? { turnId: active.turnId } : {},
|
|
344
|
+
lockStartedAt: active.startedAt,
|
|
345
|
+
lockAgeMs: Date.now() - active.startedAt,
|
|
346
|
+
...diagnostics ? { diagnostics } : {}
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
{ status: 409 }
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
function createDurableTurnLock(options) {
|
|
353
|
+
return {
|
|
354
|
+
// Every lock lives on the workspace channel, so this wakes that object
|
|
355
|
+
// (evicted after idle) before the turn's acquire reaches it.
|
|
356
|
+
async warm(target) {
|
|
357
|
+
await peekDurableTurnLock(options.namespace, target.threadId ? { workspaceId: target.tenantId, threadId: target.threadId, scope: "thread" } : { workspaceId: target.tenantId, scope: "workspace" }, options.auth);
|
|
358
|
+
},
|
|
359
|
+
async acquire(args) {
|
|
360
|
+
const workspaceId = args.identity.tenantId;
|
|
361
|
+
const threadId = args.identity.sessionId;
|
|
362
|
+
const scope = options.scopeOf(args);
|
|
363
|
+
const executionId = options.lockExecutionIdOf?.(args) ?? args.executionId;
|
|
364
|
+
const turnId = options.clientTurnIdOf ? options.clientTurnIdOf(args) : args.body.turnId;
|
|
365
|
+
const input = {
|
|
366
|
+
workspaceId,
|
|
367
|
+
threadId,
|
|
368
|
+
scope,
|
|
369
|
+
executionId,
|
|
370
|
+
...turnId ? { turnId } : {}
|
|
371
|
+
};
|
|
372
|
+
let acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
|
|
373
|
+
let diagnostics;
|
|
374
|
+
if (!acquired.acquired && options.reconcile) {
|
|
375
|
+
const reconciled = await options.reconcile(args, acquired.active);
|
|
376
|
+
diagnostics = reconciled.diagnostics;
|
|
377
|
+
if (reconciled.released) {
|
|
378
|
+
acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (!acquired.acquired) {
|
|
382
|
+
return {
|
|
383
|
+
acquired: false,
|
|
384
|
+
response: (options.onRefused ?? defaultRefusalResponse)(acquired.active, diagnostics)
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
const handle = {
|
|
388
|
+
workspaceId,
|
|
389
|
+
threadId,
|
|
390
|
+
scope,
|
|
391
|
+
executionId,
|
|
392
|
+
lockId: acquired.lock.lockId
|
|
393
|
+
};
|
|
394
|
+
return { acquired: true, handle };
|
|
395
|
+
},
|
|
396
|
+
async release(handle) {
|
|
397
|
+
if (!handle) return;
|
|
398
|
+
await releaseDurableTurnLock(options.namespace, handle, options.auth);
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
async function broadcastWorkspaceActivity(namespace, workspaceId, threadId, phase, auth) {
|
|
403
|
+
try {
|
|
404
|
+
await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
|
|
405
|
+
type: "thread.activity",
|
|
406
|
+
timestamp: Date.now(),
|
|
407
|
+
data: { threadId, phase, workspaceId, sessionId: workspaceId }
|
|
408
|
+
}, auth);
|
|
409
|
+
} catch {
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
async function broadcastThreadCreated(namespace, workspaceId, thread, auth) {
|
|
413
|
+
try {
|
|
414
|
+
await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
|
|
415
|
+
type: "thread.created",
|
|
416
|
+
timestamp: Date.now(),
|
|
417
|
+
data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId }
|
|
418
|
+
}, auth);
|
|
419
|
+
} catch {
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
function createTurnStreamUpgradeHandler(options) {
|
|
423
|
+
const path = options.path ?? "/api/session-stream";
|
|
424
|
+
if (!options.authSecret || options.authSecret.length < 32) {
|
|
425
|
+
throw new Error("createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) \u2014 the DO fails closed without tokens");
|
|
426
|
+
}
|
|
427
|
+
return async (request) => {
|
|
428
|
+
const url = new URL(request.url);
|
|
429
|
+
if (url.pathname !== path || request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return null;
|
|
430
|
+
if (url.searchParams.has("threadId")) {
|
|
431
|
+
return new Response("Thread replay uses the sandbox session gateway or chat replay route", { status: 400 });
|
|
432
|
+
}
|
|
433
|
+
const workspaceId = url.searchParams.get("workspaceId");
|
|
434
|
+
if (!workspaceId) return new Response("Missing workspaceId", { status: 400 });
|
|
435
|
+
const auth = await options.authorize(request, { workspaceId });
|
|
436
|
+
if (!auth.ok) return auth.response;
|
|
437
|
+
const key = workspaceChannelKey(workspaceId);
|
|
438
|
+
const stub = options.namespace.get(options.namespace.idFromName(key));
|
|
439
|
+
const forwardUrl = new URL(request.url);
|
|
440
|
+
forwardUrl.searchParams.set("sessionId", workspaceId);
|
|
441
|
+
forwardUrl.searchParams.set("scope", "workspace");
|
|
442
|
+
forwardUrl.searchParams.delete("token");
|
|
443
|
+
const headers = new Headers(request.headers);
|
|
444
|
+
headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret));
|
|
445
|
+
return stub.fetch(new Request(new Request(forwardUrl, request), { headers }));
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export {
|
|
450
|
+
DEFAULT_STALE_TURN_LOCK_GRACE_MS,
|
|
451
|
+
DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS,
|
|
452
|
+
reconcileStaleTurnLock,
|
|
453
|
+
TURN_STREAM_TOKEN_TTL_MS,
|
|
454
|
+
TURN_STREAM_TOKEN_HEADER,
|
|
455
|
+
mintTurnStreamToken,
|
|
456
|
+
verifyTurnStreamToken,
|
|
457
|
+
threadChannelKey,
|
|
458
|
+
workspaceChannelKey,
|
|
459
|
+
turnLockChannelKey,
|
|
460
|
+
turnLockStorageKey,
|
|
461
|
+
turnStorageChannelKey,
|
|
462
|
+
scopeIndexChannelKey,
|
|
463
|
+
MAX_RECENT_CREATED,
|
|
464
|
+
ACTIVITY_TTL_MS,
|
|
465
|
+
pruneStaleThreads,
|
|
466
|
+
TURN_LOCK_TTL_MS,
|
|
467
|
+
activeTurnLock,
|
|
468
|
+
createTurnLock,
|
|
469
|
+
turnLockMatchesRelease,
|
|
470
|
+
interruptedReleaseApplies,
|
|
471
|
+
TURN_STREAM_PATHS,
|
|
472
|
+
TURN_STREAM_STORAGE_KEYS,
|
|
473
|
+
turnEventStorageKey,
|
|
474
|
+
createDurableObjectTurnEventStore,
|
|
475
|
+
acquireDurableTurnLock,
|
|
476
|
+
peekDurableTurnLock,
|
|
477
|
+
releaseDurableTurnLock,
|
|
478
|
+
releaseInterruptedDurableTurnLock,
|
|
479
|
+
reconcileStaleDurableTurnLock,
|
|
480
|
+
createDurableTurnLock,
|
|
481
|
+
broadcastWorkspaceActivity,
|
|
482
|
+
broadcastThreadCreated,
|
|
483
|
+
createTurnStreamUpgradeHandler
|
|
484
|
+
};
|
|
485
|
+
//# sourceMappingURL=chunk-A2NQMVMF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/stale-turn-lock.ts","../src/turn-stream/core.ts","../src/turn-stream/adapters.ts"],"sourcesContent":["/**\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 * The 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/**\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 /** 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 let sandbox: StaleTurnLockSandboxProbeResult\n try {\n sandbox = await options.probeSandbox()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SANDBOX_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (sandbox.status !== 'running') {\n return forceReleaseUnreachable(options, {\n unreachableReason: sandbox.status === 'absent' ? 'SANDBOX_ABSENT' : 'SANDBOX_NOT_RUNNING',\n ...(sandbox.status === 'not-running' && sandbox.state !== undefined\n ? { sandboxState: sandbox.state }\n : {}),\n })\n }\n\n // Snapshot the clock BEFORE the probe and use that one instant for BOTH the\n // grace decision and the release fence: the release is only valid against the\n // lock as it was when the state was observed, not after an arbitrarily slow\n // round trip. Re-reading the clock after the probe would let a slow round\n // trip age the lock past the grace on paper, and would hand the store a fence\n // newer than a successor lock acquired meanwhile.\n const observedAt = (options.now ?? Date.now)()\n let session: StaleTurnLockSessionProbeResult\n try {\n session = await options.probeSession()\n } catch (err) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SESSION_PROBE_FAILED',\n unreachableDetail: messageOf(err),\n })\n }\n if (!session.reachable) {\n return forceReleaseUnreachable(options, {\n unreachableReason: 'SESSION_UNREACHABLE',\n ...(session.reason !== undefined ? { sessionProbeError: session.reason } : {}),\n })\n }\n\n const diagnostics: Record<string, unknown> = {\n sandboxReachable: true,\n sessionTerminal: session.terminal,\n ...(session.diagnostics ?? {}),\n }\n // The authority answered and says the execution is live: the lock is doing\n // its job. Nothing below this point may override that.\n if (!session.terminal) return { released: false, diagnostics }\n\n // Terminal, but about WHICH execution? The probe is thread-keyed, so a lock\n // younger than the registration window may be reading the previous turn's\n // verdict — hold until it is old enough that the verdict has to be its own.\n const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS\n const lockAgeMs = observedAt - options.lockStartedAt\n if (lockAgeMs < terminalGraceMs) {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const withheld = {\n ...diagnostics,\n lockAgeMs,\n terminalReleaseGraceMs: terminalGraceMs,\n terminalReleaseWithheld: 'LOCK_WITHIN_TERMINAL_GRACE_PERIOD',\n }\n log('[chat-routes] stale turn lock held: terminal verdict but lock is younger than the registration window', {\n ...(options.context ?? {}),\n ...withheld,\n })\n return { released: false, diagnostics: withheld }\n }\n\n const released = await options.release({ observedAt })\n return {\n released,\n diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, released, observedAt },\n }\n}\n\n/**\n * The fallback: the session authority could not attest to the execution's\n * state because the box is gone, stopped, or unreachable. Release the lock\n * once it is old enough that it cannot belong to a turn still provisioning its\n * box — and say so either way, with the reason, the lock's age, and the grace\n * period it was measured against.\n *\n * One clock read (`at`) serves as the age gate AND the release fence here too,\n * for the same reason the terminal branch uses `observedAt` for both.\n */\nasync function forceReleaseUnreachable(\n options: ReconcileStaleTurnLockOptions,\n reason: Record<string, unknown> & { unreachableReason: string },\n): Promise<ReconcileStaleTurnLockResult> {\n const log = options.log ?? ((message, meta) => console.warn(message, meta))\n const graceMs = options.graceMs ?? DEFAULT_STALE_TURN_LOCK_GRACE_MS\n const at = (options.now ?? Date.now)()\n const lockAgeMs = at - options.lockStartedAt\n const diagnostics: Record<string, unknown> = {\n ...reason,\n sandboxReachable: false,\n lockAgeMs,\n forceReleaseGraceMs: graceMs,\n }\n\n if (lockAgeMs < graceMs) {\n log('[chat-routes] stale turn lock held: sandbox unreachable but lock is inside the grace period', {\n ...(options.context ?? {}),\n ...diagnostics,\n })\n return { released: false, diagnostics: { ...diagnostics, forceReleaseWithheld: 'LOCK_WITHIN_GRACE_PERIOD' } }\n }\n\n const released = await options.release({ observedAt: at })\n log('[chat-routes] force-released stale turn lock: sandbox unreachable, no turn can be executing', {\n ...(options.context ?? {}),\n ...diagnostics,\n released,\n })\n return { released, diagnostics: { ...diagnostics, forceReleased: released } }\n}\n","/**\n * 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/** `v1.<base64url-channel>.<exp-ms-36>.<base64url-mac>` — the expiry is inside the signed payload so\n * it cannot be extended by editing the token. */\nexport async function mintTurnStreamToken(\n channelName: string,\n secret: string,\n now: () => number = Date.now,\n ttlMs: number = TURN_STREAM_TOKEN_TTL_MS,\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 = `v1.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}`\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): Promise<boolean> {\n if (!secret || secret.length < 32) return false\n const parts = token.split('.')\n if (parts.length !== 4 || parts[0] !== 'v1') return false\n const [, name, expires36, mac] = parts as [string, string, string, string]\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(`v1.${name}.${expires36}`, 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 (2026-10-20) 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}\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}\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}\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 }\n}\n\n/** A cooperative release matches the execution and, when supplied, lock ID. */\nexport function turnLockMatchesRelease(\n active: DurableTurnLock,\n input: { executionId: string; lockId?: string },\n): boolean {\n if (active.executionId !== input.executionId) return false\n if (input.lockId && active.lockId !== input.lockId) return false\n return true\n}\n\n/**\n * The interrupted/stale release fence. `interruptedAt` is the instant the\n * releasing evidence was observed (the stop click, the stale-lock probe) —\n * a lock STARTED after that instant is a successor the evidence says nothing\n * about, so it survives. When the lock recorded a client turnId, the release\n * must name the same turn; a lock without one refuses a turn-specific\n * release (it cannot prove it is that turn).\n */\nexport function interruptedReleaseApplies(\n active: DurableTurnLock,\n input: { threadId: string; interruptedAt: number; turnId?: string },\n): boolean {\n if (active.threadId !== input.threadId) return false\n if (active.startedAt > input.interruptedAt) return false\n if (active.turnId) {\n if (active.turnId !== input.turnId) return false\n } else if (input.turnId) {\n return false\n }\n return true\n}\n\n// ── wire contract (adapter ↔ DO endpoint paths) ─────────────────────────────\n//\n// Kept byte-identical to the reference consumer's DO where an endpoint\n// existed there, so a product deletes its fork by re-pointing a binding, not\n// by re-speaking a protocol.\n\n/** Provide constant paths for managing chat turn streams and locks */\nexport const TURN_STREAM_PATHS = {\n broadcast: '/broadcast',\n lockAcquire: '/chat-turn-lock/acquire',\n /** Read the active lock without changing it; also brings the object up before a turn needs it. */\n lockPeek: '/chat-turn-lock/peek',\n lockRelease: '/chat-turn-lock/release',\n lockReleaseInterrupted: '/chat-turn-lock/release-interrupted',\n turnEventsAppend: '/turn-events/append',\n turnEventsRead: '/turn-events/read',\n turnStatusSet: '/turn-status/set',\n turnStatusGet: '/turn-status/get',\n scopeStatusSet: '/turn-scope/set',\n scopeRunningList: '/turn-scope/running',\n} as const\n\n/** Storage keys inside a DO instance. Exported for subclass coexistence —\n * a product extending the DO must not collide with these. */\nexport const TURN_STREAM_STORAGE_KEYS = {\n lock: 'chatTurnLock',\n threadLockPrefix: 'chatTurnLock:thread:',\n activeThreads: 'activeThreads',\n turnStatus: 'turnStatus',\n turnScope: 'turnScopeIndex',\n turnEventPrefix: 'turnEvent:',\n} as const\n\n/** Zero-padded seq so DO storage `list({ prefix })` returns rows in replay\n * order without a sort. 10 digits holds any realistic turn. */\nexport function turnEventStorageKey(seq: number): string {\n return `${TURN_STREAM_STORAGE_KEYS.turnEventPrefix}${String(seq).padStart(10, '0')}`\n}\n","/**\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 { reconcileStaleTurnLock, type ReconcileStaleTurnLockOptions } 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 TurnLockScope,\n type TurnStreamEvent,\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/** 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): 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),\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): Promise<T> {\n const result = await postJson<T>(namespace, channelKey, path, body, auth)\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}\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 * (2026-10-10) against 0.05-0.33 s once it exists; every lock now lives on the\n * workspace channel, which exists after the workspace's first turn. A peek\n * sent as soon as a turn is admitted wakes that object if it was evicted.\n */\nexport async function peekDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: { workspaceId: string } & ({ scope: 'workspace'; threadId?: string } | { scope: TurnLockScope; threadId: string }),\n auth: TurnStreamAuth,\n): Promise<DurableTurnLock | null> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId ?? '', input.scope)\n const result = await postJson<{ active?: DurableTurnLock | null }>(namespace, key, TURN_STREAM_PATHS.lockPeek, {\n scope: input.scope,\n threadId: input.threadId,\n }, auth)\n if (result.status !== 200) throw new Error(`turn-stream lock peek failed with status ${result.status}`)\n return result.body.active ?? null\n}\n\n/** Release a durable turn lock and indicate if the release was successful or deferred */\nexport async function releaseDurableTurnLock(\n namespace: TurnStreamNamespaceLike,\n input: TurnLockReleaseInput,\n auth: TurnStreamAuth,\n): Promise<{ released: boolean; deferred?: boolean }> {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope)\n return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth)\n}\n\n/** Define input parameters to release an interrupted durable turn lock in a workspace or thread */\nexport interface ReleaseInterruptedDurableTurnLockInput {\n workspaceId: string\n threadId: string\n /** Try only this scope; omit to try workspace then thread (a stop button\n * doesn't know which lane the wedged turn ran on). */\n scope?: TurnLockScope\n interruptedAt: number\n turnId?: string\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: ReleaseInterruptedDurableTurnLockInput,\n auth: TurnStreamAuth,\n): Promise<boolean> {\n const scopes: readonly TurnLockScope[] = input.scope ? [input.scope] : ['workspace', 'thread']\n for (const scope of scopes) {\n const key = turnLockChannelKey(input.workspaceId, input.threadId, scope)\n const result = await postJsonOk<{ released: boolean }>(namespace, key, TURN_STREAM_PATHS.lockReleaseInterrupted, {\n scope,\n threadId: input.threadId,\n interruptedAt: input.interruptedAt,\n ...(input.turnId ? { turnId: input.turnId } : {}),\n }, auth)\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}\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, ...policy } = options\n return reconcileStaleTurnLock({\n ...policy,\n lockStartedAt: active.startedAt,\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 }, auth),\n })\n}\n\n// ── ChatTurnLock adapter (the turnLock seam) ────────────────────────────────\n\n/** The subset of `ChatTurnProduceArgs` the lock adapter reads — structural,\n * so this module needs no import from `/chat-routes/turn-routes` (which\n * would drag the `agent-runtime` peer into every `/turn-stream` consumer). */\nexport interface TurnLockSeamArgs<TContext> {\n identity: { tenantId: string; sessionId: string }\n executionId: string\n 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 }\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 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 /** Override the execution id the lock records (e.g. a follow-up reclaiming\n * the execution it already dispatched). Default: the turn's own. */\n lockExecutionIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /** Client turn id recorded on the lock (fences interrupted releases to the\n * right turn). Default: the request body's `turnId`. */\n clientTurnIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined\n /**\n * Attempt stale-lock recovery after a refused acquire. Return whether the\n * held lock was released (the adapter then retries the acquire once).\n * Products wire {@link reconcileStaleDurableTurnLock} with their sandbox +\n * session probes here. Omit → a refused acquire is final.\n */\n reconcile?(\n args: TurnLockSeamArgs<TContext>,\n active: DurableTurnLock,\n ): Promise<{ released: boolean; diagnostics?: Record<string, unknown> }>\n /** Build the refusal `Response`. Default: a 409 with the shared body shape\n * (`code`, `message`, lock identity + age, reconcile diagnostics). */\n onRefused?(active: DurableTurnLock, diagnostics: Record<string, unknown> | undefined): Response\n}\n\nfunction defaultRefusalResponse(\n active: DurableTurnLock,\n diagnostics: Record<string, unknown> | undefined,\n): Response {\n const workspaceConflict = active.scope === 'workspace'\n return Response.json(\n {\n error: {\n code: workspaceConflict ? 'workspace_turn_in_flight' : 'chat_turn_in_flight',\n message: workspaceConflict\n ? 'A chat turn is already running for this workspace. Wait for it to finish before starting another.'\n : 'A chat turn is already running for this thread. Reconnect to the active response or wait for it to finish.',\n threadId: active.threadId,\n executionId: active.executionId,\n ...(active.turnId ? { turnId: active.turnId } : {}),\n lockStartedAt: active.startedAt,\n lockAgeMs: Date.now() - active.startedAt,\n ...(diagnostics ? { diagnostics } : {}),\n },\n },\n { status: 409 },\n )\n}\n\n/**\n * The vertical's `turnLock` seam on the shared DO: dual-scope single-flight\n * acquire (with one reconcile-then-retry pass when the product supplies a\n * stale-lock reconciler) and cooperative release on settle. The returned\n * object satisfies `createChatTurnRoutes`' `ChatTurnLock<TContext>`\n * structurally.\n */\nexport function createDurableTurnLock<TContext>(options: CreateDurableTurnLockOptions<TContext>): {\n acquire(args: TurnLockSeamArgs<TContext>): Promise<TurnLockSeamResult>\n release(handle: unknown): Promise<void>\n warm(target: { tenantId: string; threadId?: string }): Promise<void>\n} {\n 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(options.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 input: AcquireDurableTurnLockInput = {\n workspaceId,\n threadId,\n scope,\n executionId,\n ...(turnId ? { turnId } : {}),\n }\n\n let acquired = await acquireDurableTurnLock(options.namespace, input, options.auth)\n let diagnostics: Record<string, unknown> | undefined\n if (!acquired.acquired && options.reconcile) {\n const reconciled = await options.reconcile(args, acquired.active)\n diagnostics = reconciled.diagnostics\n if (reconciled.released) {\n acquired = await acquireDurableTurnLock(options.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 return { acquired: true, handle }\n },\n async release(handle) {\n if (!handle) return\n await releaseDurableTurnLock(options.namespace, handle as TurnLockReleaseInput, options.auth)\n },\n }\n}\n\n// ── broadcast helpers (products wire these into onEvent) ────────────────────\n\n/** Coarse per-workspace marker that a thread's turn started / ended — drives\n * a sidebar \"agent responding\" indicator subscribed once per workspace. */\nexport async function broadcastWorkspaceActivity(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n threadId: string,\n phase: 'start' | 'end',\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.activity',\n timestamp: Date.now(),\n data: { threadId, phase, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the indicator is non-critical UI.\n }\n}\n\n/** Per-workspace marker that a new thread was created, so an already-open\n * history list prepends it without a reload. */\nexport async function broadcastThreadCreated(\n namespace: TurnStreamNamespaceLike,\n workspaceId: string,\n thread: { threadId: string; title: string },\n auth: TurnStreamAuth,\n): Promise<void> {\n try {\n await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {\n type: 'thread.created',\n timestamp: Date.now(),\n data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId },\n } satisfies TurnStreamEvent, auth)\n } catch {\n // Best-effort: the loader reconciles on the next revalidation.\n }\n}\n\n// ── WebSocket upgrade forwarder (worker entry) ──────────────────────────────\n\n/** Represent success or failure of a TURN stream upgrade authorization with optional response data */\nexport type TurnStreamUpgradeAuthorization = { ok: true } | { ok: false; response: Response }\n\n/** Define options for creating a TURN stream upgrade handler including namespace, path, and authorization logic */\nexport interface CreateTurnStreamUpgradeHandlerOptions {\n namespace: TurnStreamNamespaceLike\n /** HMAC secret shared with the DO binding (`env.TURN_STREAM_AUTH_SECRET`).\n * After the product `authorize` passes, the handler mints a channel-bound\n * capability token and the DO verifies it — the browser never holds it. */\n authSecret: string\n /** The worker route serving the stream. Default `/api/session-stream`. */\n path?: string\n /** Viewer access check (session cookie → workspace membership). */\n authorize(\n request: Request,\n target: { workspaceId: string },\n ): Promise<TurnStreamUpgradeAuthorization>\n}\n\n/**\n * The worker-entry WebSocket forwarder — WORKSPACE channel only (the\n * per-thread variant went with the deprecated rebroadcast lane; a thread's\n * live turn replay is the sandbox session gateway's job). Call BEFORE the\n * app router (a router loader cannot return a 101); returns `null` for\n * requests that are not a WebSocket upgrade on the configured path.\n *\n * GET {path}?workspaceId=... → workspace channel (sidebar signals)\n *\n * After the 101, the client sends `{type:'sync'}` and receives the\n * current-activity + recent-threads snapshot, then live signals.\n *\n * Security: the product's `authorize` decides whether THIS caller may see the\n * workspace's signals; the channel-bound token this handler then mints is\n * what the DO itself verifies — two independent gates, and the browser never\n * learns the token (it rides the forwarded upgrade request only).\n */\nexport function createTurnStreamUpgradeHandler(\n options: CreateTurnStreamUpgradeHandlerOptions,\n): (request: Request) => Promise<Response | null> {\n const path = options.path ?? '/api/session-stream'\n if (!options.authSecret || options.authSecret.length < 32) {\n throw new Error('createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) — the DO fails closed without tokens')\n }\n return async (request) => {\n const url = new URL(request.url)\n if (url.pathname !== path || request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') return null\n\n if (url.searchParams.has('threadId')) {\n return new Response('Thread replay uses the sandbox session gateway or chat replay route', { status: 400 })\n }\n const workspaceId = url.searchParams.get('workspaceId')\n if (!workspaceId) return new Response('Missing workspaceId', { status: 400 })\n\n const auth = await options.authorize(request, { workspaceId })\n if (!auth.ok) return auth.response\n\n const key = workspaceChannelKey(workspaceId)\n const stub = options.namespace.get(options.namespace.idFromName(key))\n\n const forwardUrl = new URL(request.url)\n forwardUrl.searchParams.set('sessionId', workspaceId)\n forwardUrl.searchParams.set('scope', 'workspace')\n forwardUrl.searchParams.delete('token')\n const headers = new Headers(request.headers)\n headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret))\n return stub.fetch(new Request(new Request(forwardUrl, request), { headers }))\n }\n}\n"],"mappings":";;;;;;;AAiEO,IAAM,mCAAmC,IAAI,KAAK;AA0BlD,IAAM,sCAAsC,KAAK;AA+CxD,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AAQA,eAAsB,uBACpB,SACuC;AACvC,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,QAAQ,aAAa;AAAA,EACvC,SAAS,KAAK;AACZ,WAAO,wBAAwB,SAAS;AAAA,MACtC,mBAAmB;AAAA,MACnB,mBAAmB,UAAU,GAAG;AAAA,IAClC,CAAC;AAAA,EACH;AACA,M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