@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
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A new chat's first turn creates its thread from an id the browser minted
|
|
3
|
-
* (`mintThreadId` in `/web-react`), so the client skips the separate thread
|
|
4
|
-
* POST before its first turn. Lifted from Creative (creative-agent#709).
|
|
5
|
-
*
|
|
6
|
-
* The rules are the route's, not the product's:
|
|
7
|
-
* - the body's `newThread.id` equals the route's `threadId` and is 32 lowercase
|
|
8
|
-
* hex (the server's own id format), else the turn is the 404 it always was;
|
|
9
|
-
* - an id that exists anywhere, or that any turn ever used, is refused with
|
|
10
|
-
* 409 and never adopted, so a guessed or remembered id cannot reach another
|
|
11
|
-
* tenant's thread or a deleted thread's turns, and nothing is written (the
|
|
12
|
-
* product's insert does nothing on conflict and checks its turn records);
|
|
13
|
-
* - the title is trimmed and cut to 200 characters; blank is `null`;
|
|
14
|
-
* - `arm` admits members one by one, so a product can roll it out by percent.
|
|
15
|
-
*
|
|
16
|
-
* The product keeps its own thread read inside `authorize` and calls
|
|
17
|
-
* `args.createThread` only where that read missed, so a known thread is never
|
|
18
|
-
* created and its access check stays the product's.
|
|
19
|
-
*/
|
|
20
|
-
/** The body field a minted first turn carries. */
|
|
21
|
-
export interface ChatTurnNewThread {
|
|
22
|
-
id: string;
|
|
23
|
-
title?: string;
|
|
24
|
-
}
|
|
25
|
-
/** The `createThread` route option: who may create a thread from a minted id, and how the row is written. */
|
|
26
|
-
export interface ChatTurnCreateThreadOptions<TThread = unknown> {
|
|
27
|
-
/** Per-member arm. Omit → every member. */
|
|
28
|
-
arm?(owner: ChatTurnThreadOwner): boolean;
|
|
29
|
-
/**
|
|
30
|
-
* Insert the thread and return the written row, or `null`/`undefined` (409)
|
|
31
|
-
* when the id exists or was ever used:
|
|
32
|
-
* - the thread id column must be unique on its own, not per tenant, and the
|
|
33
|
-
* insert must do nothing on conflict (drizzle's
|
|
34
|
-
* `.onConflictDoNothing().returning()`);
|
|
35
|
-
* - refuse an id any turn ever used (for example a `turn_status` row whose
|
|
36
|
-
* `scopeId` is the id): turn records keyed by thread id outlive a deleted
|
|
37
|
-
* thread, and a re-created id would hand them to its new owner through
|
|
38
|
-
* replay and running-turn discovery.
|
|
39
|
-
* `title` is `null` when the client sent none; the product names the fallback.
|
|
40
|
-
*/
|
|
41
|
-
insert(thread: {
|
|
42
|
-
id: string;
|
|
43
|
-
title: string | null;
|
|
44
|
-
} & ChatTurnThreadOwner): Promise<TThread | null | undefined>;
|
|
45
|
-
}
|
|
46
|
-
/** Who a created thread belongs to: the tenant (workspace) and member `authorize` resolved. */
|
|
47
|
-
export interface ChatTurnThreadOwner {
|
|
48
|
-
tenantId: string;
|
|
49
|
-
userId: string;
|
|
50
|
-
}
|
|
51
|
-
/** What `args.createThread` answers: the created row, or the response refusing the turn (404 or 409). */
|
|
52
|
-
export type ChatTurnCreateThreadResult<TThread = unknown> = {
|
|
53
|
-
ok: true;
|
|
54
|
-
thread: TThread;
|
|
55
|
-
} | {
|
|
56
|
-
ok: false;
|
|
57
|
-
response: Response;
|
|
58
|
-
};
|
|
59
|
-
/** Bind the route option to one turn's body; `authorize` receives the result as `args.createThread`. */
|
|
60
|
-
export declare function bindTurnThreadCreation<TThread>(options: ChatTurnCreateThreadOptions<TThread>, body: {
|
|
61
|
-
threadId: string;
|
|
62
|
-
newThread?: unknown;
|
|
63
|
-
}): (owner: ChatTurnThreadOwner) => Promise<ChatTurnCreateThreadResult<TThread>>;
|
package/dist/chunk-6R73V3Y5.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// src/turn-trace/turn-facts.ts
|
|
2
|
-
var KEEP = 512;
|
|
3
|
-
var facts = /* @__PURE__ */ new Map();
|
|
4
|
-
function noteMeasuredTurnFacts(turnStreamId, measured) {
|
|
5
|
-
facts.delete(turnStreamId);
|
|
6
|
-
facts.set(turnStreamId, measured);
|
|
7
|
-
if (facts.size > KEEP) facts.delete(facts.keys().next().value);
|
|
8
|
-
}
|
|
9
|
-
function measuredTurnFacts(turnStreamId) {
|
|
10
|
-
return facts.get(turnStreamId);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export {
|
|
14
|
-
noteMeasuredTurnFacts,
|
|
15
|
-
measuredTurnFacts
|
|
16
|
-
};
|
|
17
|
-
//# sourceMappingURL=chunk-6R73V3Y5.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-trace/turn-facts.ts"],"sourcesContent":["/**\n * What `createChatTurnRoutes` measured for a settled turn, kept in this isolate\n * under the turn's stream id so the rollout timing store can fill the row the\n * product writes from its lifecycle hook. A product's writer that forgot\n * `firstVisibleMs` or `admissionMs` (Legal never wrote first_visible_ms) still\n * records them after a version bump, on every lane.\n *\n * Internal: not exported from a subpath. Values the product passes always win.\n */\nexport interface MeasuredTurnFacts {\n admissionMs?: number\n firstVisibleMs?: number\n firstTextMs?: number\n /** The model that served the turn. */\n model?: string\n /** The terminal event's readable code and explanation, before product serialization. */\n failureCode?: string\n}\n\n/** Turns kept; a lifecycle hook reads its turn's facts within the same request, so a small window is enough. */\nconst KEEP = 512\nconst facts = new Map<string, MeasuredTurnFacts>()\n\nexport function noteMeasuredTurnFacts(turnStreamId: string, measured: MeasuredTurnFacts): void {\n facts.delete(turnStreamId)\n facts.set(turnStreamId, measured)\n if (facts.size > KEEP) facts.delete(facts.keys().next().value!)\n}\n\nexport function measuredTurnFacts(turnStreamId: string): MeasuredTurnFacts | undefined {\n return facts.get(turnStreamId)\n}\n"],"mappings":";AAoBA,IAAM,OAAO;AACb,IAAM,QAAQ,oBAAI,IAA+B;AAE1C,SAAS,sBAAsB,cAAsB,UAAmC;AAC7F,QAAM,OAAO,YAAY;AACzB,QAAM,IAAI,cAAc,QAAQ;AAChC,MAAI,MAAM,OAAO,KAAM,OAAM,OAAO,MAAM,KAAK,EAAE,KAAK,EAAE,KAAM;AAChE;AAEO,SAAS,kBAAkB,cAAqD;AACrF,SAAO,MAAM,IAAI,YAAY;AAC/B;","names":[]}
|
package/dist/chunk-CCVWR33L.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
// src/chat-routes/stale-turn-lock.ts
|
|
2
|
-
var DEFAULT_STALE_TURN_LOCK_GRACE_MS = 5 * 60 * 1e3;
|
|
3
|
-
var DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS = 60 * 1e3;
|
|
4
|
-
function messageOf(err) {
|
|
5
|
-
return err instanceof Error ? err.message : String(err);
|
|
6
|
-
}
|
|
7
|
-
async function reconcileStaleTurnLock(options) {
|
|
8
|
-
let sandbox;
|
|
9
|
-
try {
|
|
10
|
-
sandbox = await options.probeSandbox();
|
|
11
|
-
} catch (err) {
|
|
12
|
-
return forceReleaseUnreachable(options, {
|
|
13
|
-
unreachableReason: "SANDBOX_PROBE_FAILED",
|
|
14
|
-
unreachableDetail: messageOf(err)
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
if (sandbox.status !== "running") {
|
|
18
|
-
return forceReleaseUnreachable(options, {
|
|
19
|
-
unreachableReason: sandbox.status === "absent" ? "SANDBOX_ABSENT" : "SANDBOX_NOT_RUNNING",
|
|
20
|
-
...sandbox.status === "not-running" && sandbox.state !== void 0 ? { sandboxState: sandbox.state } : {}
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
const observedAt = (options.now ?? Date.now)();
|
|
24
|
-
let session;
|
|
25
|
-
try {
|
|
26
|
-
session = await options.probeSession();
|
|
27
|
-
} catch (err) {
|
|
28
|
-
return forceReleaseUnreachable(options, {
|
|
29
|
-
unreachableReason: "SESSION_PROBE_FAILED",
|
|
30
|
-
unreachableDetail: messageOf(err)
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
if (!session.reachable) {
|
|
34
|
-
return forceReleaseUnreachable(options, {
|
|
35
|
-
unreachableReason: "SESSION_UNREACHABLE",
|
|
36
|
-
...session.reason !== void 0 ? { sessionProbeError: session.reason } : {}
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
const diagnostics = {
|
|
40
|
-
sandboxReachable: true,
|
|
41
|
-
sessionTerminal: session.terminal,
|
|
42
|
-
...session.diagnostics ?? {}
|
|
43
|
-
};
|
|
44
|
-
if (!session.terminal) return { released: false, diagnostics };
|
|
45
|
-
const terminalGraceMs = options.terminalGraceMs ?? DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS;
|
|
46
|
-
const lockAgeMs = observedAt - options.lockStartedAt;
|
|
47
|
-
if (lockAgeMs < terminalGraceMs) {
|
|
48
|
-
const log = options.log ?? ((message, meta) => console.warn(message, meta));
|
|
49
|
-
const withheld = {
|
|
50
|
-
...diagnostics,
|
|
51
|
-
lockAgeMs,
|
|
52
|
-
terminalReleaseGraceMs: terminalGraceMs,
|
|
53
|
-
terminalReleaseWithheld: "LOCK_WITHIN_TERMINAL_GRACE_PERIOD"
|
|
54
|
-
};
|
|
55
|
-
log("[chat-routes] stale turn lock held: terminal verdict but lock is younger than the registration window", {
|
|
56
|
-
...options.context ?? {},
|
|
57
|
-
...withheld
|
|
58
|
-
});
|
|
59
|
-
return { released: false, diagnostics: withheld };
|
|
60
|
-
}
|
|
61
|
-
const released = await options.release({ observedAt });
|
|
62
|
-
return {
|
|
63
|
-
released,
|
|
64
|
-
diagnostics: { ...diagnostics, lockAgeMs, terminalReleaseGraceMs: terminalGraceMs, released, observedAt }
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
async function forceReleaseUnreachable(options, reason) {
|
|
68
|
-
const log = options.log ?? ((message, meta) => console.warn(message, meta));
|
|
69
|
-
const graceMs = options.graceMs ?? DEFAULT_STALE_TURN_LOCK_GRACE_MS;
|
|
70
|
-
const at = (options.now ?? Date.now)();
|
|
71
|
-
const lockAgeMs = at - options.lockStartedAt;
|
|
72
|
-
const diagnostics = {
|
|
73
|
-
...reason,
|
|
74
|
-
sandboxReachable: false,
|
|
75
|
-
lockAgeMs,
|
|
76
|
-
forceReleaseGraceMs: graceMs
|
|
77
|
-
};
|
|
78
|
-
if (lockAgeMs < graceMs) {
|
|
79
|
-
log("[chat-routes] stale turn lock held: sandbox unreachable but lock is inside the grace period", {
|
|
80
|
-
...options.context ?? {},
|
|
81
|
-
...diagnostics
|
|
82
|
-
});
|
|
83
|
-
return { released: false, diagnostics: { ...diagnostics, forceReleaseWithheld: "LOCK_WITHIN_GRACE_PERIOD" } };
|
|
84
|
-
}
|
|
85
|
-
const released = await options.release({ observedAt: at });
|
|
86
|
-
log("[chat-routes] force-released stale turn lock: sandbox unreachable, no turn can be executing", {
|
|
87
|
-
...options.context ?? {},
|
|
88
|
-
...diagnostics,
|
|
89
|
-
released
|
|
90
|
-
});
|
|
91
|
-
return { released, diagnostics: { ...diagnostics, forceReleased: released } };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export {
|
|
95
|
-
DEFAULT_STALE_TURN_LOCK_GRACE_MS,
|
|
96
|
-
DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS,
|
|
97
|
-
reconcileStaleTurnLock
|
|
98
|
-
};
|
|
99
|
-
//# sourceMappingURL=chunk-CCVWR33L.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-routes/stale-turn-lock.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"],"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,MAAI,QAAQ,WAAW,WAAW;AAChC,WAAO,wBAAwB,SAAS;AAAA,MACtC,mBAAmB,QAAQ,WAAW,WAAW,mBAAmB;AAAA,MACpE,GAAI,QAAQ,WAAW,iBAAiB,QAAQ,UAAU,SACtD,EAAE,cAAc,QAAQ,MAAM,IAC9B,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AAQA,QAAM,cAAc,QAAQ,OAAO,KAAK,KAAK;AAC7C,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,MAAI,CAAC,QAAQ,WAAW;AACtB,WAAO,wBAAwB,SAAS;AAAA,MACtC,mBAAmB;AAAA,MACnB,GAAI,QAAQ,WAAW,SAAY,EAAE,mBAAmB,QAAQ,OAAO,IAAI,CAAC;AAAA,IAC9E,CAAC;AAAA,EACH;AAEA,QAAM,cAAuC;AAAA,IAC3C,kBAAkB;AAAA,IAClB,iBAAiB,QAAQ;AAAA,IACzB,GAAI,QAAQ,eAAe,CAAC;AAAA,EAC9B;AAGA,MAAI,CAAC,QAAQ,SAAU,QAAO,EAAE,UAAU,OAAO,YAAY;AAK7D,QAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAM,YAAY,aAAa,QAAQ;AACvC,MAAI,YAAY,iBAAiB;AAC/B,UAAM,MAAM,QAAQ,QAAQ,CAAC,SAAS,SAAS,QAAQ,KAAK,SAAS,IAAI;AACzE,UAAM,WAAW;AAAA,MACf,GAAG;AAAA,MACH;AAAA,MACA,wBAAwB;AAAA,MACxB,yBAAyB;AAAA,IAC3B;AACA,QAAI,yGAAyG;AAAA,MAC3G,GAAI,QAAQ,WAAW,CAAC;AAAA,MACxB,GAAG;AAAA,IACL,CAAC;AACD,WAAO,EAAE,UAAU,OAAO,aAAa,SAAS;AAAA,EAClD;AAEA,QAAM,WAAW,MAAM,QAAQ,QAAQ,EAAE,WAAW,CAAC;AACrD,SAAO;AAAA,IACL;AAAA,IACA,aAAa,EAAE,GAAG,aAAa,WAAW,wBAAwB,iBAAiB,UAAU,WAAW;AAAA,EAC1G;AACF;AAYA,eAAe,wBACb,SACA,QACuC;AACvC,QAAM,MAAM,QAAQ,QAAQ,CAAC,SAAS,SAAS,QAAQ,KAAK,SAAS,IAAI;AACzE,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,MAAM,QAAQ,OAAO,KAAK,KAAK;AACrC,QAAM,YAAY,KAAK,QAAQ;AAC/B,QAAM,cAAuC;AAAA,IAC3C,GAAG;AAAA,IACH,kBAAkB;AAAA,IAClB;AAAA,IACA,qBAAqB;AAAA,EACvB;AAEA,MAAI,YAAY,SAAS;AACvB,QAAI,+FAA+F;AAAA,MACjG,GAAI,QAAQ,WAAW,CAAC;AAAA,MACxB,GAAG;AAAA,IACL,CAAC;AACD,WAAO,EAAE,UAAU,OAAO,aAAa,EAAE,GAAG,aAAa,sBAAsB,2BAA2B,EAAE;AAAA,EAC9G;AAEA,QAAM,WAAW,MAAM,QAAQ,QAAQ,EAAE,YAAY,GAAG,CAAC;AACzD,MAAI,+FAA+F;AAAA,IACjG,GAAI,QAAQ,WAAW,CAAC;AAAA,IACxB,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACD,SAAO,EAAE,UAAU,aAAa,EAAE,GAAG,aAAa,eAAe,SAAS,EAAE;AAC9E;","names":[]}
|