@tangle-network/agent-app 4.0.36 → 4.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +16 -8
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-23YED7HQ.js → chunk-77UNTK66.js} +355 -288
  17. package/dist/chunk-77UNTK66.js.map +1 -0
  18. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  19. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  20. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  21. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  22. package/dist/chunk-DPD7LY3T.js.map +1 -0
  23. package/dist/{chunk-MQCAO5VW.js → chunk-MGW25KMR.js} +3 -3
  24. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  25. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  26. package/dist/{chunk-E633CJFH.js → chunk-WAOZF4EL.js} +14 -9
  27. package/dist/chunk-WAOZF4EL.js.map +1 -0
  28. package/dist/operator/index.js +2 -2
  29. package/dist/preset-cloudflare/index.js +5 -5
  30. package/dist/public-consultation/index.d.ts +1 -1
  31. package/dist/public-consultation/index.js +6 -6
  32. package/dist/sandbox/index.js +3 -3
  33. package/dist/turn-stream/cancellation.d.ts +16 -0
  34. package/dist/turn-stream/core.d.ts +4 -0
  35. package/dist/turn-stream/do.d.ts +4 -2
  36. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  37. package/dist/turn-stream/index.js +122 -5
  38. package/dist/turn-stream/index.js.map +1 -1
  39. package/dist/web-react/chat-composer-types.d.ts +10 -6
  40. package/dist/web-react/chat-composer.d.ts +3 -2
  41. package/dist/web-react/chat-stream.d.ts +4 -2
  42. package/dist/web-react/index.js +13 -5
  43. package/dist/web-react/use-composer-send.d.ts +3 -3
  44. package/package.json +1 -1
  45. package/dist/chunk-23YED7HQ.js.map +0 -1
  46. package/dist/chunk-7VJCMEEE.js.map +0 -1
  47. package/dist/chunk-E633CJFH.js.map +0 -1
  48. package/dist/chunk-K2JPSXKI.js.map +0 -1
  49. package/dist/chunk-NAMSFODC.js.map +0 -1
  50. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  51. /package/dist/{chunk-MQCAO5VW.js.map → chunk-MGW25KMR.js.map} +0 -0
  52. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  53. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -1,30 +1,30 @@
1
1
  import {
2
2
  createChatTurnRoutes,
3
3
  streamChatRouteAsSandboxEvents
4
- } from "../chunk-23YED7HQ.js";
4
+ } from "../chunk-77UNTK66.js";
5
5
  import "../chunk-SBHFMDR7.js";
6
6
  import "../chunk-H6BRJU5M.js";
7
7
  import "../chunk-4DBHC63F.js";
8
8
  import "../chunk-RN4WPTBH.js";
9
9
  import "../chunk-MM6RLOXF.js";
10
10
  import "../chunk-M4QITAQV.js";
11
- import "../chunk-MQCAO5VW.js";
11
+ import "../chunk-MGW25KMR.js";
12
12
  import "../chunk-F4TUZYMX.js";
13
13
  import "../chunk-MH74DY2I.js";
14
- import "../chunk-NAMSFODC.js";
14
+ import "../chunk-4YBNKXUE.js";
15
15
  import "../chunk-QUV5M7SZ.js";
16
16
  import "../chunk-QM5TPZQY.js";
17
17
  import "../chunk-WGT32NQ4.js";
18
18
  import "../chunk-YG66IHDU.js";
19
- import "../chunk-4YZKDWMB.js";
19
+ import "../chunk-SADNHPAY.js";
20
20
  import "../chunk-ZVEEWGDK.js";
21
21
  import "../chunk-JM6ANMOA.js";
22
22
  import "../chunk-TB6KNPFI.js";
23
23
  import "../chunk-2IGXFHUO.js";
24
24
  import "../chunk-ALIWB2P3.js";
25
- import "../chunk-KPCNNFBO.js";
25
+ import "../chunk-AOSQ5JCO.js";
26
26
  import "../chunk-YQE2CGIO.js";
27
- import "../chunk-K2JPSXKI.js";
27
+ import "../chunk-6YLVFV3F.js";
28
28
  import "../chunk-L3QR274L.js";
29
29
  import "../chunk-XELWWXJJ.js";
30
30
  import "../chunk-DSMGS4IV.js";
@@ -114,7 +114,7 @@ import {
114
114
  warmKey,
115
115
  warmReceiptId,
116
116
  warmWeekdayOf
117
- } from "../chunk-MQCAO5VW.js";
117
+ } from "../chunk-MGW25KMR.js";
118
118
  import {
119
119
  createWarmCache
120
120
  } from "../chunk-F4TUZYMX.js";
@@ -162,9 +162,9 @@ import {
162
162
  workspaceSandboxRecoveryRecommendedActions
163
163
  } from "../chunk-2IGXFHUO.js";
164
164
  import "../chunk-ALIWB2P3.js";
165
- import "../chunk-KPCNNFBO.js";
165
+ import "../chunk-AOSQ5JCO.js";
166
166
  import "../chunk-YQE2CGIO.js";
167
- import "../chunk-K2JPSXKI.js";
167
+ import "../chunk-6YLVFV3F.js";
168
168
  import "../chunk-L3QR274L.js";
169
169
  import "../chunk-XELWWXJJ.js";
170
170
  import "../chunk-DSMGS4IV.js";
@@ -1,4 +1,6 @@
1
1
  import type { TurnStreamAuth, TurnStreamNamespaceLike } from './adapters.js';
2
+ import type { TurnHostControlTarget } from '../chat-routes/turn-progress.js';
3
+ export type { TurnHostControlTarget } from '../chat-routes/turn-progress.js';
2
4
  import type { TurnCancellationIdentity } from './cancellation-do.js';
3
5
  export type { TurnCancellationIdentity } from './cancellation-do.js';
4
6
  /** Per-owner observation only. Closing it never changes or releases the durable lock. */
@@ -14,6 +16,20 @@ export declare class TurnControlUnavailableError extends Error {
14
16
  readonly code = "turn_control_unavailable";
15
17
  constructor(message?: string);
16
18
  }
19
+ /** Unique-id reconstruction is required; idFromName(hostId) addresses a different object. */
20
+ export interface TurnHostControlNamespace extends TurnStreamNamespaceLike {
21
+ idFromString(id: string): unknown;
22
+ }
23
+ /** Call only after product identity/editor/actual-thread authorization. A positive
24
+ * result accepts intent for this live invocation, not settlement or future replay
25
+ * suppression. A stale/unknown host is never started and cannot select a successor. */
26
+ export declare function requestHostedTurnCancellation(namespace: TurnHostControlNamespace, target: TurnHostControlTarget, auth: TurnStreamAuth): Promise<{
27
+ requested: boolean;
28
+ reason?: 'stale-host';
29
+ }>;
30
+ /** Owned by the original hosted request, never its browser. Socket loss revokes
31
+ * permission even when an old storage-free HTTP invocation survives a DO reset. */
32
+ export declare function connectHostedTurnCancellation(namespace: TurnHostControlNamespace, target: TurnHostControlTarget, auth: TurnStreamAuth): Promise<TurnCancellationConnection>;
17
33
  /** The product authorizes Stop first. This exact fenced request records intent; it never claims work stopped. */
18
34
  export declare function requestDurableTurnCancellation(namespace: TurnStreamNamespaceLike, identity: TurnCancellationIdentity, auth: TurnStreamAuth): Promise<{
19
35
  requested: boolean;
@@ -20,6 +20,10 @@ 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
+ /** Server-only control on an existing unnamed host; never a turn start endpoint. */
24
+ export declare const TURN_HOST_CANCEL_PATH = "/turn-host/cancel";
25
+ /** The same host's server-owned connection revokes execution permission on reset. */
26
+ export declare const TURN_HOST_CONTROL_PATH = "/turn-host/control";
23
27
  /** Server control authority is separate from the channel capabilities used by existing viewer forwarders. */
24
28
  export interface TurnStreamTokenClaims {
25
29
  purpose: 'turn-control' | 'turn-cancel' | 'turn-recovery';
@@ -9,6 +9,7 @@
9
9
  * Product storage keys must avoid TURN_STREAM_STORAGE_KEYS.
10
10
  * With `turnRoutes`, an unnamed per-turn object runs one forwarded chat turn.
11
11
  */
12
+ import type { ChatTurnRequestContext } from '../chat-routes/turn-route-contracts.js';
12
13
  import { type DurableTurnLock, type TurnStreamEvent } from './core.js';
13
14
  /** The socket surface the DO touches. Cloudflare's hibernatable `WebSocket`
14
15
  * satisfies it. */
@@ -70,8 +71,7 @@ export interface TurnStreamDOOptions {
70
71
  * CPU limit and the code update strategy this class needs are in `createChatTurnRoutes`' `turnHost`.
71
72
  */
72
73
  turnRoutes?(env: unknown): {
73
- turn(request: Request, ctx: {
74
- waitUntil?(promise: Promise<unknown>): void;
74
+ turn(request: Request, ctx: ChatTurnRequestContext & {
75
75
  hosted: true;
76
76
  }): Promise<Response>;
77
77
  };
@@ -85,6 +85,7 @@ export declare class TurnStreamDO {
85
85
  protected readonly env: unknown;
86
86
  protected readonly options: TurnStreamDOOptions;
87
87
  private readonly cancellation;
88
+ private readonly hostedTurn;
88
89
  private recentCreated;
89
90
  private activeThreads;
90
91
  constructor(state: TurnStreamDOState, env?: unknown, options?: TurnStreamDOOptions);
@@ -124,6 +125,7 @@ export declare class TurnStreamDO {
124
125
  sessionId: string;
125
126
  }): Promise<TurnStreamEvent[]>;
126
127
  private handleWebSocketUpgrade;
128
+ private acceptSocket;
127
129
  /**
128
130
  * First (and only) client message after open: `{ type: 'sync', afterSeq }`.
129
131
  * Replays the current state for the socket's scope, then marks it `synced`
@@ -0,0 +1,20 @@
1
+ /** Control of one live host invocation, including its detached drain and disposal. */
2
+ import type { ChatTurnRequestContext } from '../chat-routes/turn-route-contracts.js';
3
+ import type { TurnHostControlTarget } from '../chat-routes/turn-progress.js';
4
+ import type { TurnStreamDOState, TurnStreamSocket } from './do.js';
5
+ /** No admission ledger or restart: the DO still authenticates requests and owns its sockets/storage. */
6
+ export declare class HostedTurn {
7
+ private readonly state;
8
+ private started;
9
+ private invocation?;
10
+ constructor(state: TurnStreamDOState);
11
+ run(request: Request, turn: (request: Request, ctx: ChatTurnRequestContext & {
12
+ hosted: true;
13
+ }) => Promise<Response>): Promise<Response>;
14
+ requestCancellation(input: Record<string, unknown> | null): {
15
+ requested: boolean;
16
+ reason?: 'stale-host';
17
+ };
18
+ controlTarget(url: URL): TurnHostControlTarget | undefined;
19
+ sync(ws: TurnStreamSocket, message: string | ArrayBuffer, host: TurnHostControlTarget): void;
20
+ }
@@ -2,6 +2,8 @@ import {
2
2
  ACTIVITY_TTL_MS,
3
3
  DEFAULT_TURN_LOCK_LOCATION_HINT,
4
4
  MAX_RECENT_CREATED,
5
+ TURN_HOST_CANCEL_PATH,
6
+ TURN_HOST_CONTROL_PATH,
5
7
  TURN_LOCK_TTL_MS,
6
8
  TURN_STREAM_PATHS,
7
9
  TURN_STREAM_STORAGE_KEYS,
@@ -14,6 +16,7 @@ import {
14
16
  broadcastThreadCreated,
15
17
  broadcastWorkspaceActivity,
16
18
  connectDurableTurnCancellation,
19
+ connectHostedTurnCancellation,
17
20
  createDurableObjectTurnEventStore,
18
21
  createDurableTurnLock,
19
22
  createTurnLock,
@@ -29,6 +32,7 @@ import {
29
32
  releaseDurableTurnLock,
30
33
  releaseInterruptedDurableTurnLock,
31
34
  requestDurableTurnCancellation,
35
+ requestHostedTurnCancellation,
32
36
  scopeIndexChannelKey,
33
37
  threadChannelKey,
34
38
  turnEventStorageKey,
@@ -39,7 +43,7 @@ import {
39
43
  turnStorageChannelKey,
40
44
  verifyTurnStreamToken,
41
45
  workspaceChannelKey
42
- } from "../chunk-KPCNNFBO.js";
46
+ } from "../chunk-AOSQ5JCO.js";
43
47
  import {
44
48
  DEFAULT_RUNNING_TURN_LEASE_MS
45
49
  } from "../chunk-YQE2CGIO.js";
@@ -130,6 +134,98 @@ var DurableTurnCancellation = class {
130
134
  }
131
135
  };
132
136
 
137
+ // src/turn-stream/hosted-turn.ts
138
+ var HOST_CONTROL_KEYS = ["hostId", "workspaceId", "threadId", "clientTurnId", "retryAttemptId"];
139
+ var HostedTurn = class {
140
+ constructor(state) {
141
+ this.state = state;
142
+ }
143
+ state;
144
+ started = false;
145
+ invocation;
146
+ async run(request, turn) {
147
+ if (this.started) return Response.json({ error: "This host invocation already started" }, { status: 409 });
148
+ this.started = true;
149
+ const invocation = { controller: new AbortController(), pending: 1 };
150
+ this.invocation = invocation;
151
+ const finish = () => {
152
+ if (--invocation.pending !== 0) return;
153
+ this.invocation = void 0;
154
+ invocation.connection?.close();
155
+ invocation.controller.abort(new TurnControlUnavailableError("The host invocation ended"));
156
+ try {
157
+ for (const socket of this.state.getWebSockets()) socket.close(1e3, "Host invocation ended");
158
+ } catch {
159
+ }
160
+ };
161
+ const waitUntil = (promise) => {
162
+ invocation.pending++;
163
+ const tracked = promise.finally(finish);
164
+ this.state.waitUntil?.(tracked);
165
+ void tracked.catch(() => {
166
+ });
167
+ };
168
+ const headers = new Headers(request.headers);
169
+ headers.delete(TURN_STREAM_TOKEN_HEADER);
170
+ try {
171
+ return await turn(new Request(request, { headers }), {
172
+ waitUntil,
173
+ hosted: true,
174
+ hostControl: {
175
+ hostId: String(this.state.id),
176
+ signal: invocation.controller.signal,
177
+ bind: async (target, owner) => {
178
+ if (invocation.target || target.hostId !== String(this.state.id) || invocation.controller.signal.aborted) {
179
+ throw new TurnControlUnavailableError("The host identity cannot be rebound");
180
+ }
181
+ invocation.target = { ...target };
182
+ const connection = await connectHostedTurnCancellation(owner.namespace, target, owner.auth);
183
+ invocation.connection = connection;
184
+ const lost = () => invocation.controller.abort(connection.signal.reason);
185
+ if (connection.signal.aborted) lost();
186
+ else connection.signal.addEventListener("abort", lost, { once: true });
187
+ }
188
+ }
189
+ });
190
+ } finally {
191
+ finish();
192
+ }
193
+ }
194
+ requestCancellation(input) {
195
+ const invocation = this.invocation;
196
+ const target = invocation?.target;
197
+ if (!input || !invocation || !target || HOST_CONTROL_KEYS.some((key) => input[key] !== target[key])) return { requested: false, reason: "stale-host" };
198
+ invocation.controller.abort(new TurnCancellationRequestedError());
199
+ for (const socket of this.state.getWebSockets()) {
200
+ try {
201
+ socket.send(JSON.stringify({ type: "turn.control", cancellationRequested: true }));
202
+ } catch {
203
+ }
204
+ }
205
+ return { requested: true };
206
+ }
207
+ controlTarget(url) {
208
+ const target = this.invocation?.target;
209
+ return target && !HOST_CONTROL_KEYS.some((key) => (url.searchParams.get(key) ?? void 0) !== target[key]) ? target : void 0;
210
+ }
211
+ sync(ws, message, host) {
212
+ let type;
213
+ try {
214
+ type = JSON.parse(typeof message === "string" ? message : "").type;
215
+ } catch {
216
+ ws.close(1008, "Invalid host control sync");
217
+ return;
218
+ }
219
+ if (type !== "sync") return;
220
+ const invocation = this.invocation;
221
+ if (!invocation?.target || HOST_CONTROL_KEYS.some((key) => invocation.target[key] !== host[key])) {
222
+ ws.close(1008, "Host invocation changed");
223
+ return;
224
+ }
225
+ ws.send(JSON.stringify({ type: "turn.control", cancellationRequested: invocation.controller.signal.aborted }));
226
+ }
227
+ };
228
+
133
229
  // src/turn-stream/do.ts
134
230
  function jsonResponse(body, status = 200) {
135
231
  return new Response(JSON.stringify(body), {
@@ -154,6 +250,7 @@ var TurnStreamDO = class {
154
250
  env;
155
251
  options;
156
252
  cancellation;
253
+ hostedTurn;
157
254
  // Workspace channel: recent thread.created markers (in-memory, best-effort)
158
255
  // + durable responding set (threadId → startedAt) that survives eviction.
159
256
  recentCreated = [];
@@ -162,6 +259,7 @@ var TurnStreamDO = class {
162
259
  this.state = state;
163
260
  this.env = env;
164
261
  this.options = options;
262
+ this.hostedTurn = new HostedTurn(state);
165
263
  this.cancellation = new DurableTurnCancellation(
166
264
  state,
167
265
  (input) => this.loadActiveLock(Date.now(), turnLockStorageKey(input.scope, input.threadId)),
@@ -234,9 +332,16 @@ var TurnStreamDO = class {
234
332
  const unauthorized = await this.authorizeRequest(request);
235
333
  if (unauthorized) return unauthorized;
236
334
  if (this.options.turnRoutes && !this.state.id?.name) {
237
- const headers = new Headers(request.headers);
238
- headers.delete(TURN_STREAM_TOKEN_HEADER);
239
- return this.options.turnRoutes(this.env).turn(new Request(request, { headers }), { waitUntil: this.state.waitUntil?.bind(this.state), hosted: true });
335
+ if (url.pathname === TURN_HOST_CANCEL_PATH) {
336
+ if (request.method !== "POST") return jsonResponse({ error: "Method not allowed" }, 405);
337
+ return jsonResponse(this.hostedTurn.requestCancellation(await jsonBody(request)));
338
+ }
339
+ if (url.pathname === TURN_HOST_CONTROL_PATH) {
340
+ if (request.method !== "GET" || request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return jsonResponse({ error: "Upgrade required" }, 400);
341
+ const target = this.hostedTurn.controlTarget(url);
342
+ return target ? this.acceptSocket({ host: target }) : jsonResponse({ error: "Host invocation changed" }, 409);
343
+ }
344
+ return this.hostedTurn.run(request, (forwarded, ctx) => this.options.turnRoutes(this.env).turn(forwarded, ctx));
240
345
  }
241
346
  if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") {
242
347
  return this.handleWebSocketUpgrade(request, url);
@@ -316,6 +421,9 @@ var TurnStreamDO = class {
316
421
  const sessionId = url.searchParams.get("sessionId");
317
422
  if (!sessionId) return new Response("Missing sessionId", { status: 400 });
318
423
  const scope = url.searchParams.get("scope") === "workspace" ? "workspace" : "thread";
424
+ return this.acceptSocket({ sessionId, scope, synced: false, ...control ? { cancellation: control } : {} });
425
+ }
426
+ acceptSocket(metadata) {
319
427
  const PairCtor = globalThis.WebSocketPair;
320
428
  if (!PairCtor) {
321
429
  return new Response("WebSocket upgrades require the Cloudflare runtime", { status: 501 });
@@ -324,7 +432,7 @@ var TurnStreamDO = class {
324
432
  const client = pair[0];
325
433
  const server = pair[1];
326
434
  this.state.acceptWebSocket(server);
327
- server.serializeAttachment({ sessionId, scope, synced: false, ...control ? { cancellation: control } : {} });
435
+ server.serializeAttachment(metadata);
328
436
  return new Response(null, { status: 101, webSocket: client });
329
437
  }
330
438
  /**
@@ -336,6 +444,11 @@ var TurnStreamDO = class {
336
444
  * fan-out.
337
445
  */
338
446
  async webSocketMessage(ws, message) {
447
+ const host = ws.deserializeAttachment()?.host;
448
+ if (host) {
449
+ this.hostedTurn.sync(ws, message, host);
450
+ return;
451
+ }
339
452
  const meta = ws.deserializeAttachment();
340
453
  if (!meta || meta.synced) return;
341
454
  try {
@@ -725,6 +838,8 @@ export {
725
838
  DEFAULT_TURN_LOCK_LOCATION_HINT,
726
839
  MAX_RECENT_CREATED,
727
840
  MEMORY_TURN_STREAM_AUTH_SECRET,
841
+ TURN_HOST_CANCEL_PATH,
842
+ TURN_HOST_CONTROL_PATH,
728
843
  TURN_LOCK_TTL_MS,
729
844
  TURN_STREAM_PATHS,
730
845
  TURN_STREAM_STORAGE_KEYS,
@@ -738,6 +853,7 @@ export {
738
853
  broadcastThreadCreated,
739
854
  broadcastWorkspaceActivity,
740
855
  connectDurableTurnCancellation,
856
+ connectHostedTurnCancellation,
741
857
  createDurableObjectTurnEventStore,
742
858
  createDurableTurnLock,
743
859
  createMemoryTurnStreamHarness,
@@ -754,6 +870,7 @@ export {
754
870
  releaseDurableTurnLock,
755
871
  releaseInterruptedDurableTurnLock,
756
872
  requestDurableTurnCancellation,
873
+ requestHostedTurnCancellation,
757
874
  scopeIndexChannelKey,
758
875
  threadChannelKey,
759
876
  turnEventStorageKey,