@tangle-network/agent-app 0.63.3 → 0.63.4

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.
@@ -28,7 +28,7 @@ import {
28
28
  } from "../chunk-PK65B6HP.js";
29
29
  import {
30
30
  releaseDurableTurnLock
31
- } from "../chunk-464WRGJ3.js";
31
+ } from "../chunk-MT6ZTQGD.js";
32
32
  import {
33
33
  createD1TurnEventStore
34
34
  } from "../chunk-ISP6ZH3G.js";
@@ -121,9 +121,9 @@ export declare function createPublicConsultation(options: PublicConsultationOpti
121
121
  executionBudget?: ChatTurnExecutionLimits;
122
122
  maxOutputTokens?: number;
123
123
  }) => Promise<{
124
- start?: undefined;
125
124
  status: 'unsupported';
126
125
  reason: string;
126
+ start?: undefined;
127
127
  } | {
128
128
  reason?: undefined;
129
129
  status: 'prepared';
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createChatTurnRoutes,
3
3
  streamChatRouteAsSandboxEvents
4
- } from "../chunk-PGWKYLHC.js";
4
+ } from "../chunk-UXK5EBQT.js";
5
5
  import "../chunk-KH4QSBNI.js";
6
6
  import "../chunk-CQGEGPY7.js";
7
7
  import "../chunk-RN4WPTBH.js";
@@ -9,7 +9,7 @@ import "../chunk-WP2GYFZ4.js";
9
9
  import "../chunk-4DBHC63F.js";
10
10
  import "../chunk-MH74DY2I.js";
11
11
  import "../chunk-MM6RLOXF.js";
12
- import "../chunk-POIVNKYH.js";
12
+ import "../chunk-72ASTUPN.js";
13
13
  import "../chunk-F4TUZYMX.js";
14
14
  import "../chunk-N6URQ6DM.js";
15
15
  import "../chunk-Z4RD5UF7.js";
@@ -20,7 +20,7 @@ import "../chunk-5TSRFF5W.js";
20
20
  import "../chunk-VUBJZEZB.js";
21
21
  import "../chunk-6VQCFJWP.js";
22
22
  import "../chunk-PK65B6HP.js";
23
- import "../chunk-464WRGJ3.js";
23
+ import "../chunk-MT6ZTQGD.js";
24
24
  import "../chunk-ISP6ZH3G.js";
25
25
  import "../chunk-ZLX4BA27.js";
26
26
  import "../chunk-XELWWXJJ.js";
@@ -101,7 +101,7 @@ import {
101
101
  warmKey,
102
102
  warmReceiptId,
103
103
  warmWeekdayOf
104
- } from "../chunk-POIVNKYH.js";
104
+ } from "../chunk-72ASTUPN.js";
105
105
  import {
106
106
  createWarmCache
107
107
  } from "../chunk-F4TUZYMX.js";
@@ -145,7 +145,7 @@ import {
145
145
  workspaceSandboxRecoveryMessage,
146
146
  workspaceSandboxRecoveryRecommendedActions
147
147
  } from "../chunk-PK65B6HP.js";
148
- import "../chunk-464WRGJ3.js";
148
+ import "../chunk-MT6ZTQGD.js";
149
149
  import "../chunk-ISP6ZH3G.js";
150
150
  import "../chunk-DSMGS4IV.js";
151
151
  import "../chunk-ACB7KOQ6.js";
@@ -4,9 +4,10 @@
4
4
  * run the same authenticated request path.
5
5
  * Products provide workspace authorization and their binding's TURN_STREAM_AUTH_SECRET.
6
6
  */
7
- import { type ReconcileStaleTurnLockOptions } from '../chat-routes/stale-turn-lock';
7
+ import { type TurnCancellationConnection, type TurnCancellationIdentity } from './cancellation';
8
+ import { type ReconcileStaleTurnLockOptions, type StaleTurnLockOwnerProbeResult } from '../chat-routes/stale-turn-lock';
8
9
  import type { TurnEventStore } from '../stream/turn-buffer';
9
- import { type DurableTurnLock, type TurnLockAcquireResult, type TurnLockReleaseInput, type TurnLockScope } from './core';
10
+ import { type DurableTurnLock, type TurnLockAcquireResult, type TurnLockReleaseInput, type TurnLockInterruptedReleaseInput, type TurnLockScope } from './core';
10
11
  /** Resolve a stub interface for handling fetch requests with optional initialization parameters */
11
12
  export interface TurnStreamStubLike {
12
13
  fetch(input: Request | string, init?: RequestInit): Promise<Response>;
@@ -45,6 +46,9 @@ export interface AcquireDurableTurnLockInput {
45
46
  turnId?: string;
46
47
  /** Supply to reclaim/retry with a stable id; default mints a UUID. */
47
48
  lockId?: string;
49
+ cancellation?: {
50
+ turnStreamId: string;
51
+ };
48
52
  }
49
53
  /** Acquire a durable turn lock in the specified namespace with given input parameters */
50
54
  export declare function acquireDurableTurnLock(namespace: TurnStreamNamespaceLike, input: AcquireDurableTurnLockInput, auth: TurnStreamAuth): Promise<TurnLockAcquireResult>;
@@ -72,15 +76,7 @@ export declare function releaseDurableTurnLock(namespace: TurnStreamNamespaceLik
72
76
  deferred?: boolean;
73
77
  }>;
74
78
  /** Define input parameters to release an interrupted durable turn lock in a workspace or thread */
75
- export interface ReleaseInterruptedDurableTurnLockInput {
76
- workspaceId: string;
77
- threadId: string;
78
- /** Try only this scope; omit to try workspace then thread (a stop button
79
- * doesn't know which lane the wedged turn ran on). */
80
- scope?: TurnLockScope;
81
- interruptedAt: number;
82
- turnId?: string;
83
- }
79
+ export type ReleaseInterruptedDurableTurnLockInput = TurnLockInterruptedReleaseInput;
84
80
  /** Fenced out-of-band release — the DO refuses a successor lock (started
85
81
  * after `interruptedAt`) and a turnId mismatch. Returns whether any scope
86
82
  * released. */
@@ -93,6 +89,8 @@ export interface ReconcileStaleDurableTurnLockOptions extends Pick<ReconcileStal
93
89
  threadId: string;
94
90
  /** The lock the acquire attempt was refused on. */
95
91
  active: DurableTurnLock;
92
+ /** Cancellable Router locks require positive exact outer + child quiescence; native-only probes cannot attest it. */
93
+ probeOwner?(identity: TurnCancellationIdentity): Promise<StaleTurnLockOwnerProbeResult>;
96
94
  }
97
95
  /**
98
96
  * `/chat-routes`' `reconcileStaleTurnLock` policy wired to the DO: the
@@ -114,6 +112,7 @@ export interface TurnLockSeamArgs<TContext> {
114
112
  sessionId: string;
115
113
  };
116
114
  executionId: string;
115
+ turnStreamId?: string;
117
116
  context: TContext;
118
117
  body: {
119
118
  turnId?: string;
@@ -123,6 +122,7 @@ export interface TurnLockSeamArgs<TContext> {
123
122
  export type TurnLockSeamResult = {
124
123
  acquired: true;
125
124
  handle?: unknown;
125
+ cancellation?: TurnCancellationConnection;
126
126
  } | {
127
127
  acquired: false;
128
128
  response: Response;
@@ -138,6 +138,8 @@ export interface CreateDurableTurnLockOptions<TContext> {
138
138
  /** Which lane serializes this turn: `'workspace'` (shared sandbox — one
139
139
  * turn per workspace) or `'thread'` (router lane — one turn per thread). */
140
140
  scopeOf(args: TurnLockSeamArgs<TContext>): TurnLockScope;
141
+ /** Opt the existing lock into durable Stop. Leave native/durable completion lanes on their existing owner. */
142
+ cancellationOf?(args: TurnLockSeamArgs<TContext>): boolean;
141
143
  /** Override the execution id the lock records (e.g. a follow-up reclaiming
142
144
  * the execution it already dispatched). Default: the turn's own. */
143
145
  lockExecutionIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined;
@@ -0,0 +1,31 @@
1
+ import type { DurableTurnLock, TurnLockReleaseInput } from './core';
2
+ import type { TurnStreamDOState, TurnStreamSocket } from './do';
3
+ /** One cancellable turn, including the lock generation that grants its producer authority. */
4
+ export interface TurnCancellationIdentity extends TurnLockReleaseInput {
5
+ turnStreamId: string;
6
+ }
7
+ export interface TurnCancellationSocketMeta {
8
+ sessionId: string;
9
+ scope: 'thread' | 'workspace';
10
+ synced: boolean;
11
+ cancellation?: TurnCancellationIdentity;
12
+ }
13
+ export declare function readTurnCancellationIdentity(value: Record<string, unknown>): TurnCancellationIdentity | null;
14
+ /** Storage and hibernatable sockets belong to the existing lock DO; this helper never schedules or releases work. */
15
+ export declare class DurableTurnCancellation {
16
+ private readonly state;
17
+ private readonly readLock;
18
+ private readonly writeLock;
19
+ constructor(state: TurnStreamDOState, readLock: (input: TurnCancellationIdentity) => Promise<DurableTurnLock | null>, writeLock: (lock: DurableTurnLock) => Promise<void>);
20
+ owns(input: TurnCancellationIdentity): Promise<boolean>;
21
+ permitsRecovery(lock: DurableTurnLock, input: TurnCancellationIdentity): boolean;
22
+ request(input: TurnCancellationIdentity): Promise<{
23
+ requested: boolean;
24
+ reason?: 'stale-owner';
25
+ }>;
26
+ sync(socket: TurnStreamSocket, meta: TurnCancellationSocketMeta): Promise<void>;
27
+ released(lock: DurableTurnLock): void;
28
+ expired(lock: DurableTurnLock): void;
29
+ private close;
30
+ private send;
31
+ }
@@ -0,0 +1,23 @@
1
+ import type { TurnStreamAuth, TurnStreamNamespaceLike } from './adapters';
2
+ import type { TurnCancellationIdentity } from './cancellation-do';
3
+ export type { TurnCancellationIdentity } from './cancellation-do';
4
+ /** Per-owner observation only. Closing it never changes or releases the durable lock. */
5
+ export interface TurnCancellationConnection {
6
+ signal: AbortSignal;
7
+ close(): void;
8
+ }
9
+ export declare class TurnCancellationRequestedError extends Error {
10
+ readonly code = "turn_cancel_requested";
11
+ constructor();
12
+ }
13
+ export declare class TurnControlUnavailableError extends Error {
14
+ readonly code = "turn_control_unavailable";
15
+ constructor(message?: string);
16
+ }
17
+ /** The product authorizes Stop first. This exact fenced request records intent; it never claims work stopped. */
18
+ export declare function requestDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity, auth: TurnStreamAuth): Promise<{
19
+ requested: boolean;
20
+ reason?: 'stale-owner';
21
+ }>;
22
+ /** One server-owned connection on the existing authenticated DO transport, with retained cancellation replay. */
23
+ export declare function connectDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity, auth: TurnStreamAuth): Promise<TurnCancellationConnection>;
@@ -20,13 +20,20 @@ export declare const TURN_STREAM_TOKEN_TTL_MS = 60000;
20
20
  /** Request header the adapters attach (and the DO accepts). The worker also
21
21
  * attaches it when forwarding an authorized browser WebSocket handshake. */
22
22
  export declare const TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
23
- /** `v1.<base64url-channel>.<exp-ms-36>.<base64url-mac>` — the expiry is inside the signed payload so
24
- * it cannot be extended by editing the token. */
25
- export declare function mintTurnStreamToken(channelName: string, secret: string, now?: () => number, ttlMs?: number): Promise<string>;
23
+ /** Server control authority is separate from the channel capabilities used by existing viewer forwarders. */
24
+ export interface TurnStreamTokenClaims {
25
+ purpose: 'turn-control' | 'turn-cancel' | 'turn-recovery';
26
+ identity: TurnLockReleaseInput & {
27
+ turnStreamId: string;
28
+ };
29
+ }
30
+ /** Legacy v1 channel capabilities remain unchanged. Optional v2 claims bind
31
+ * server-only purpose and exact owner identity inside the same signed payload. */
32
+ export declare function mintTurnStreamToken(channelName: string, secret: string, now?: () => number, ttlMs?: number, claims?: TurnStreamTokenClaims): Promise<string>;
26
33
  /** Verify a token for `channelName`: constant-time MAC compare with the
27
34
  * exact channel name embedded in the signed payload, plus freshness. A
28
35
  * token minted for any other channel — or a tampered expiry — is false. */
29
- export declare function verifyTurnStreamToken(channelName: string, token: string, secret: string, now?: () => number): Promise<boolean>;
36
+ export declare function verifyTurnStreamToken(channelName: string, token: string, secret: string, now?: () => number, claims?: TurnStreamTokenClaims): Promise<boolean>;
30
37
  /** Define the scope level for acquiring a turn lock within thread or workspace contexts */
31
38
  export type TurnLockScope = 'thread' | 'workspace';
32
39
  /** Channel for a thread's viewer signals. */
@@ -75,6 +82,11 @@ export interface DurableTurnLock {
75
82
  * parked on the lock until the task settles. Written only through the DO's
76
83
  * defer seam — the base package never sets it on its own. */
77
84
  releasePending?: boolean;
85
+ /** Optional Router control, owned by this exact lock generation. Stop never releases the lock. */
86
+ cancellation?: {
87
+ turnStreamId: string;
88
+ requestedAt?: number;
89
+ };
78
90
  }
79
91
  /** Define input parameters required to acquire a turn-based lock in a workspace thread */
80
92
  export interface TurnLockAcquireInput {
@@ -84,6 +96,9 @@ export interface TurnLockAcquireInput {
84
96
  executionId: string;
85
97
  lockId: string;
86
98
  turnId?: string;
99
+ cancellation?: {
100
+ turnStreamId: string;
101
+ };
87
102
  }
88
103
  /** Resolve the result of attempting to acquire a turn lock indicating success or active lock status */
89
104
  export type TurnLockAcquireResult = {
@@ -112,6 +127,10 @@ export interface TurnLockInterruptedReleaseInput {
112
127
  scope?: TurnLockScope;
113
128
  interruptedAt: number;
114
129
  turnId?: string;
130
+ /** Only after the existing stale policy positively proves this exact Router owner and its children abandoned. */
131
+ recovery?: TurnLockReleaseInput & {
132
+ turnStreamId: string;
133
+ };
115
134
  }
116
135
  /** `stored` is what the DO read from storage; expired locks are dead. */
117
136
  export declare function activeTurnLock(stored: DurableTurnLock | undefined, now: number): DurableTurnLock | null;
@@ -67,6 +67,7 @@ export declare class TurnStreamDO {
67
67
  protected readonly state: TurnStreamDOState;
68
68
  protected readonly env: unknown;
69
69
  protected readonly options: TurnStreamDOOptions;
70
+ private readonly cancellation;
70
71
  private recentCreated;
71
72
  private activeThreads;
72
73
  constructor(state: TurnStreamDOState, env?: unknown, options?: TurnStreamDOOptions);
@@ -84,6 +85,7 @@ export declare class TurnStreamDO {
84
85
  * secret fails closed with a 500 that names the fix (issue #746).
85
86
  */
86
87
  private authorizeRequest;
88
+ private authorizeControl;
87
89
  fetch(request: Request): Promise<Response>;
88
90
  /** Called for any request no base endpoint claimed (before the 404), so a
89
91
  * subclass adds product endpoints without touching base routing. Return
@@ -120,8 +122,8 @@ export declare class TurnStreamDO {
120
122
  private handleBroadcast;
121
123
  private loadActiveThreads;
122
124
  private persistActiveThreads;
123
- /** The live lock under `key` (default: the workspace-scope lock); an
124
- * expired one is deleted and reads as none. */
125
+ /** The live lock under `key`. Cancellation never extends TTL; an actual
126
+ * product child/persistence obligation still vetoes expiry deletion. */
125
127
  protected loadActiveLock(now?: number, key?: string): Promise<DurableTurnLock | null>;
126
128
  private releaseActiveLock;
127
129
  /** Park a release on the lock itself; {@link completeDeferredLockRelease}
@@ -13,3 +13,4 @@ export * from './core';
13
13
  export * from './do';
14
14
  export * from './adapters';
15
15
  export * from './memory';
16
+ export * from './cancellation';
@@ -7,10 +7,13 @@ import {
7
7
  TURN_STREAM_STORAGE_KEYS,
8
8
  TURN_STREAM_TOKEN_HEADER,
9
9
  TURN_STREAM_TOKEN_TTL_MS,
10
+ TurnCancellationRequestedError,
11
+ TurnControlUnavailableError,
10
12
  acquireDurableTurnLock,
11
13
  activeTurnLock,
12
14
  broadcastThreadCreated,
13
15
  broadcastWorkspaceActivity,
16
+ connectDurableTurnCancellation,
14
17
  createDurableObjectTurnEventStore,
15
18
  createDurableTurnLock,
16
19
  createTurnLock,
@@ -22,6 +25,7 @@ import {
22
25
  reconcileStaleDurableTurnLock,
23
26
  releaseDurableTurnLock,
24
27
  releaseInterruptedDurableTurnLock,
28
+ requestDurableTurnCancellation,
25
29
  scopeIndexChannelKey,
26
30
  threadChannelKey,
27
31
  turnEventStorageKey,
@@ -31,12 +35,97 @@ import {
31
35
  turnStorageChannelKey,
32
36
  verifyTurnStreamToken,
33
37
  workspaceChannelKey
34
- } from "../chunk-464WRGJ3.js";
38
+ } from "../chunk-MT6ZTQGD.js";
35
39
  import {
36
40
  DEFAULT_RUNNING_TURN_LEASE_MS
37
41
  } from "../chunk-ISP6ZH3G.js";
38
42
  import "../chunk-S5SRJJQG.js";
39
43
 
44
+ // src/turn-stream/cancellation-do.ts
45
+ function readTurnCancellationIdentity(value) {
46
+ const keys = ["workspaceId", "threadId", "executionId", "lockId", "turnStreamId"];
47
+ if (keys.some((key) => typeof value[key] !== "string" || !String(value[key]).trim())) return null;
48
+ if (value.scope !== "thread" && value.scope !== "workspace") return null;
49
+ return {
50
+ workspaceId: String(value.workspaceId),
51
+ threadId: String(value.threadId),
52
+ executionId: String(value.executionId),
53
+ lockId: String(value.lockId),
54
+ turnStreamId: String(value.turnStreamId),
55
+ scope: value.scope
56
+ };
57
+ }
58
+ function matches(lock, input) {
59
+ return Boolean(lock && lock.workspaceId === input.workspaceId && lock.threadId === input.threadId && lock.scope === input.scope && lock.executionId === input.executionId && lock.lockId === input.lockId && lock.cancellation?.turnStreamId === input.turnStreamId);
60
+ }
61
+ var DurableTurnCancellation = class {
62
+ constructor(state, readLock, writeLock) {
63
+ this.state = state;
64
+ this.readLock = readLock;
65
+ this.writeLock = writeLock;
66
+ }
67
+ state;
68
+ readLock;
69
+ writeLock;
70
+ async owns(input) {
71
+ return matches(await this.readLock(input), input);
72
+ }
73
+ permitsRecovery(lock, input) {
74
+ if (!matches(lock, input)) return false;
75
+ return !this.state.getWebSockets().some((socket) => {
76
+ const meta = socket.deserializeAttachment();
77
+ const state = socket.readyState;
78
+ return meta?.cancellation && matches(lock, meta.cancellation) && (state === void 0 || state === 0 || state === 1);
79
+ });
80
+ }
81
+ async request(input) {
82
+ const lock = await this.readLock(input);
83
+ if (!matches(lock, input)) return { requested: false, reason: "stale-owner" };
84
+ if (lock.cancellation.requestedAt === void 0) {
85
+ lock.cancellation = { turnStreamId: input.turnStreamId, requestedAt: Date.now() };
86
+ await this.writeLock(lock);
87
+ }
88
+ for (const socket of this.state.getWebSockets()) {
89
+ const meta = socket.deserializeAttachment();
90
+ if (meta?.synced && meta.cancellation && matches(lock, meta.cancellation)) this.send(socket, lock);
91
+ }
92
+ return { requested: true };
93
+ }
94
+ async sync(socket, meta) {
95
+ const identity = meta.cancellation;
96
+ socket.serializeAttachment({ ...meta, synced: true });
97
+ const lock = await this.readLock(identity);
98
+ if (!matches(lock, identity)) {
99
+ socket.close(1008, "Turn ownership changed");
100
+ return;
101
+ }
102
+ this.send(socket, lock);
103
+ }
104
+ released(lock) {
105
+ this.close(lock, false);
106
+ }
107
+ expired(lock) {
108
+ this.close(lock, true);
109
+ }
110
+ close(lock, ownershipLost) {
111
+ for (const socket of this.state.getWebSockets()) {
112
+ const meta = socket.deserializeAttachment();
113
+ if (!meta?.cancellation || !matches(lock, meta.cancellation)) continue;
114
+ try {
115
+ socket.send(JSON.stringify({ type: ownershipLost ? "turn.control.ownership-lost" : "turn.control.released" }));
116
+ socket.close(1e3, "Turn settled");
117
+ } catch {
118
+ }
119
+ }
120
+ }
121
+ send(socket, lock) {
122
+ try {
123
+ socket.send(JSON.stringify({ type: "turn.control", cancellationRequested: lock.cancellation.requestedAt !== void 0 }));
124
+ } catch {
125
+ }
126
+ }
127
+ };
128
+
40
129
  // src/turn-stream/do.ts
41
130
  function jsonResponse(body, status = 200) {
42
131
  return new Response(JSON.stringify(body), {
@@ -60,6 +149,7 @@ var TurnStreamDO = class {
60
149
  state;
61
150
  env;
62
151
  options;
152
+ cancellation;
63
153
  // Workspace channel: recent thread.created markers (in-memory, best-effort)
64
154
  // + durable responding set (threadId → startedAt) that survives eviction.
65
155
  recentCreated = [];
@@ -68,6 +158,11 @@ var TurnStreamDO = class {
68
158
  this.state = state;
69
159
  this.env = env;
70
160
  this.options = options;
161
+ this.cancellation = new DurableTurnCancellation(
162
+ state,
163
+ (input) => this.loadActiveLock(Date.now(), turnLockStorageKey(input.scope, input.threadId)),
164
+ (lock) => this.state.storage.put(turnLockStorageKey(lock.scope, lock.threadId), lock)
165
+ );
71
166
  }
72
167
  /** The token-verification secret: explicit option first, then the
73
168
  * `TURN_STREAM_AUTH_SECRET` env binding. Protected so a product subclass
@@ -103,9 +198,33 @@ var TurnStreamDO = class {
103
198
  );
104
199
  }
105
200
  const token = request.headers.get(TURN_STREAM_TOKEN_HEADER) ?? "";
106
- if (await verifyTurnStreamToken(name, token, secret)) return null;
201
+ let claims;
202
+ if (token.startsWith("v2.")) {
203
+ const url = new URL(request.url);
204
+ if (request.headers.get("Upgrade")?.toLowerCase() === "websocket" && url.searchParams.get("cancellation") === "1") {
205
+ const identity = readTurnCancellationIdentity(Object.fromEntries(url.searchParams));
206
+ if (identity) claims = { purpose: "turn-control", identity };
207
+ } else if (request.method === "POST" && url.pathname === TURN_STREAM_PATHS.lockReleaseInterrupted) {
208
+ const body = await jsonBody(request.clone());
209
+ if (body?.cancel === true) {
210
+ const identity = readTurnCancellationIdentity(body);
211
+ if (identity) claims = { purpose: "turn-cancel", identity };
212
+ } else if (body?.recovery && typeof body.recovery === "object") {
213
+ const identity = readTurnCancellationIdentity(body.recovery);
214
+ if (identity) claims = { purpose: "turn-recovery", identity };
215
+ }
216
+ }
217
+ if (!claims) return Response.json({ error: "turn-stream capability does not authorize this operation" }, { status: 401 });
218
+ }
219
+ if (await verifyTurnStreamToken(name, token, secret, void 0, claims)) return null;
107
220
  return Response.json({ error: "invalid or missing turn-stream capability token" }, { status: 401 });
108
221
  }
222
+ async authorizeControl(request, purpose, identity) {
223
+ const name = this.state.id?.name;
224
+ const secret = this.resolveAuthSecret();
225
+ if (typeof name !== "string" || !secret) return false;
226
+ return verifyTurnStreamToken(name, request.headers.get(TURN_STREAM_TOKEN_HEADER) ?? "", secret, void 0, { purpose, identity });
227
+ }
109
228
  async fetch(request) {
110
229
  const url = new URL(request.url);
111
230
  const unauthorized = await this.authorizeRequest(request);
@@ -166,6 +285,7 @@ var TurnStreamDO = class {
166
285
  const active = await this.loadActiveLock(Date.now(), key);
167
286
  if (!active?.releasePending || active.executionId !== executionId) continue;
168
287
  await this.state.storage.delete(key);
288
+ this.cancellation.released(active);
169
289
  return true;
170
290
  }
171
291
  return false;
@@ -177,7 +297,11 @@ var TurnStreamDO = class {
177
297
  return [];
178
298
  }
179
299
  // ── WebSocket channel ─────────────────────────────────────────────────────
180
- handleWebSocketUpgrade(_request, url) {
300
+ async handleWebSocketUpgrade(request, url) {
301
+ const control = url.searchParams.get("cancellation") === "1" ? readTurnCancellationIdentity(Object.fromEntries(url.searchParams)) : null;
302
+ if (url.searchParams.has("cancellation") && !control) return jsonResponse({ error: "Missing exact cancellation identity" }, 400);
303
+ if (control && !await this.authorizeControl(request, "turn-control", control)) return jsonResponse({ error: "Invalid owner control capability" }, 401);
304
+ if (control && !await this.cancellation.owns(control)) return jsonResponse({ error: "Turn ownership changed" }, 409);
181
305
  const sessionId = url.searchParams.get("sessionId");
182
306
  if (!sessionId) return new Response("Missing sessionId", { status: 400 });
183
307
  const scope = url.searchParams.get("scope") === "workspace" ? "workspace" : "thread";
@@ -189,7 +313,7 @@ var TurnStreamDO = class {
189
313
  const client = pair[0];
190
314
  const server = pair[1];
191
315
  this.state.acceptWebSocket(server);
192
- server.serializeAttachment({ sessionId, scope, synced: false });
316
+ server.serializeAttachment({ sessionId, scope, synced: false, ...control ? { cancellation: control } : {} });
193
317
  return new Response(null, { status: 101, webSocket: client });
194
318
  }
195
319
  /**
@@ -209,6 +333,10 @@ var TurnStreamDO = class {
209
333
  } catch {
210
334
  return;
211
335
  }
336
+ if (meta.cancellation) {
337
+ await this.cancellation.sync(ws, meta);
338
+ return;
339
+ }
212
340
  {
213
341
  const active = await this.loadActiveThreads();
214
342
  const removed = pruneStaleThreads(active, Date.now(), this.options.activityTtlMs ?? ACTIVITY_TTL_MS);
@@ -284,18 +412,32 @@ var TurnStreamDO = class {
284
412
  await this.state.storage.put(TURN_STREAM_STORAGE_KEYS.activeThreads, Object.fromEntries(map));
285
413
  }
286
414
  // ── chat-turn lock ────────────────────────────────────────────────────────
287
- /** The live lock under `key` (default: the workspace-scope lock); an
288
- * expired one is deleted and reads as none. */
415
+ /** The live lock under `key`. Cancellation never extends TTL; an actual
416
+ * product child/persistence obligation still vetoes expiry deletion. */
289
417
  async loadActiveLock(now = Date.now(), key = TURN_STREAM_STORAGE_KEYS.lock) {
290
418
  const stored = await this.state.storage.get(key);
291
419
  const lock = activeTurnLock(stored, now);
292
- if (stored && !lock) await this.state.storage.delete(key);
420
+ if (stored && !lock) {
421
+ const deferred = await this.shouldDeferLockRelease(stored.executionId);
422
+ const current = await this.state.storage.get(key);
423
+ if (!current) return null;
424
+ const live = activeTurnLock(current, Date.now());
425
+ if (live) return live;
426
+ const sameGeneration = current.workspaceId === stored.workspaceId && current.threadId === stored.threadId && current.scope === stored.scope && current.executionId === stored.executionId && current.lockId === stored.lockId && current.startedAt === stored.startedAt && current.expiresAt === stored.expiresAt && current.cancellation?.turnStreamId === stored.cancellation?.turnStreamId;
427
+ if (deferred || !sameGeneration) {
428
+ return current.scope ? current : { ...current, scope: "thread" };
429
+ }
430
+ await this.state.storage.delete(key);
431
+ this.cancellation.expired(current);
432
+ }
293
433
  return lock;
294
434
  }
295
- async releaseActiveLock(key, input) {
435
+ async releaseActiveLock(key, input, recovery) {
296
436
  const active = await this.loadActiveLock(Date.now(), key);
297
437
  if (!active || !turnLockMatchesRelease(active, input)) return false;
438
+ if (recovery && !this.cancellation.permitsRecovery(active, recovery)) return false;
298
439
  await this.state.storage.delete(key);
440
+ this.cancellation.released(active);
299
441
  return true;
300
442
  }
301
443
  /** Park a release on the lock itself; {@link completeDeferredLockRelease}
@@ -312,7 +454,7 @@ var TurnStreamDO = class {
312
454
  async pruneExpiredThreadLocks(now) {
313
455
  const threadLocks = await this.state.storage.list({ prefix: TURN_STREAM_STORAGE_KEYS.threadLockPrefix });
314
456
  for (const [key, stored] of threadLocks) {
315
- if (!activeTurnLock(stored, now)) await this.state.storage.delete(key);
457
+ if (!activeTurnLock(stored, now)) await this.loadActiveLock(now, key);
316
458
  }
317
459
  }
318
460
  async handleLockAcquire(request) {
@@ -323,6 +465,8 @@ var TurnStreamDO = class {
323
465
  const lockId = stringValue(body?.lockId);
324
466
  const scope = body?.scope === "workspace" ? "workspace" : body?.scope === "thread" ? "thread" : null;
325
467
  const turnId = stringValue(body?.turnId) ?? void 0;
468
+ const cancellation = body?.cancellation && typeof body.cancellation === "object" ? stringValue(body.cancellation.turnStreamId) : null;
469
+ if (body?.cancellation !== void 0 && !cancellation) return jsonResponse({ error: "Missing cancellation turnStreamId" }, 400);
326
470
  if (!workspaceId || !threadId || !executionId || !lockId || !scope) {
327
471
  return jsonResponse({ error: "Missing workspaceId, threadId, executionId, lockId, or scope" }, 400);
328
472
  }
@@ -332,10 +476,22 @@ var TurnStreamDO = class {
332
476
  if (active) {
333
477
  return jsonResponse({ acquired: false, active }, 409);
334
478
  }
335
- if (scope === "thread") await this.pruneExpiredThreadLocks(now);
479
+ if (scope === "thread") {
480
+ await this.pruneExpiredThreadLocks(now);
481
+ const current = await this.loadActiveLock(Date.now(), key);
482
+ if (current) return jsonResponse({ acquired: false, active: current }, 409);
483
+ }
336
484
  const lock = createTurnLock(
337
- { workspaceId, threadId, scope, executionId, lockId, ...turnId ? { turnId } : {} },
338
- now,
485
+ {
486
+ workspaceId,
487
+ threadId,
488
+ scope,
489
+ executionId,
490
+ lockId,
491
+ ...turnId ? { turnId } : {},
492
+ ...cancellation ? { cancellation: { turnStreamId: cancellation } } : {}
493
+ },
494
+ Date.now(),
339
495
  this.options.lockTtlMs ?? TURN_LOCK_TTL_MS
340
496
  );
341
497
  await this.state.storage.put(key, lock);
@@ -358,6 +514,12 @@ var TurnStreamDO = class {
358
514
  }
359
515
  async handleLockReleaseInterrupted(request) {
360
516
  const body = await jsonBody(request);
517
+ if (body?.cancel === true) {
518
+ const identity = readTurnCancellationIdentity(body);
519
+ if (!identity) return jsonResponse({ error: "Missing exact cancellation identity" }, 400);
520
+ if (!await this.authorizeControl(request, "turn-cancel", identity)) return jsonResponse({ error: "Invalid cancellation capability" }, 401);
521
+ return jsonResponse(await this.cancellation.request(identity));
522
+ }
361
523
  const threadId = stringValue(body?.threadId);
362
524
  const interruptedAt = typeof body?.interruptedAt === "number" && Number.isFinite(body.interruptedAt) ? body.interruptedAt : void 0;
363
525
  if (!threadId || interruptedAt === void 0) {
@@ -367,14 +529,20 @@ var TurnStreamDO = class {
367
529
  const key = lockStorageKeyOf(body);
368
530
  const active = await this.loadActiveLock(Date.now(), key);
369
531
  if (!active) return jsonResponse({ released: false });
532
+ const recovery = body?.recovery && typeof body.recovery === "object" ? readTurnCancellationIdentity(body.recovery) : null;
533
+ if (body?.recovery !== void 0 && (!recovery || !await this.authorizeControl(request, "turn-recovery", recovery))) {
534
+ return jsonResponse({ error: "Invalid owner recovery capability" }, 401);
535
+ }
536
+ if (active.cancellation) {
537
+ if (!recovery || !this.cancellation.permitsRecovery(active, recovery)) return jsonResponse({ released: false });
538
+ }
370
539
  if (await this.shouldDeferLockRelease(active.executionId)) {
371
540
  return jsonResponse({ released: false });
372
541
  }
373
542
  if (!interruptedReleaseApplies(active, { threadId, interruptedAt, ...turnId ? { turnId } : {} })) {
374
543
  return jsonResponse({ released: false });
375
544
  }
376
- await this.state.storage.delete(key);
377
- return jsonResponse({ released: true });
545
+ return jsonResponse({ released: await this.releaseActiveLock(key, { executionId: active.executionId, lockId: active.lockId }, recovery ?? void 0) });
378
546
  }
379
547
  // ── durable turn-event storage (TurnEventStore backing) ───────────────────
380
548
  async handleTurnEventsAppend(request) {
@@ -551,11 +719,14 @@ export {
551
719
  TURN_STREAM_STORAGE_KEYS,
552
720
  TURN_STREAM_TOKEN_HEADER,
553
721
  TURN_STREAM_TOKEN_TTL_MS,
722
+ TurnCancellationRequestedError,
723
+ TurnControlUnavailableError,
554
724
  TurnStreamDO,
555
725
  acquireDurableTurnLock,
556
726
  activeTurnLock,
557
727
  broadcastThreadCreated,
558
728
  broadcastWorkspaceActivity,
729
+ connectDurableTurnCancellation,
559
730
  createDurableObjectTurnEventStore,
560
731
  createDurableTurnLock,
561
732
  createMemoryTurnStreamHarness,
@@ -568,6 +739,7 @@ export {
568
739
  reconcileStaleDurableTurnLock,
569
740
  releaseDurableTurnLock,
570
741
  releaseInterruptedDurableTurnLock,
742
+ requestDurableTurnCancellation,
571
743
  scopeIndexChannelKey,
572
744
  threadChannelKey,
573
745
  turnEventStorageKey,