@tangle-network/agent-app 0.62.4 → 0.63.1

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 (136) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-profiles/d1.js +1 -1
  3. package/dist/agent-profiles/index.d.ts +4 -1
  4. package/dist/agent-profiles/index.js +1 -1
  5. package/dist/app-auth/index.js +2 -2
  6. package/dist/assistant/index.js +7 -7
  7. package/dist/chat-react/index.js +3 -3
  8. package/dist/chat-routes/cancellation.d.ts +61 -0
  9. package/dist/chat-routes/dispatch-first.d.ts +14 -25
  10. package/dist/chat-routes/early-turn-work.d.ts +10 -0
  11. package/dist/chat-routes/hybrid-producer.d.ts +4 -3
  12. package/dist/chat-routes/index.d.ts +2 -1
  13. package/dist/chat-routes/index.js +86 -1874
  14. package/dist/chat-routes/index.js.map +1 -1
  15. package/dist/chat-routes/native-turn-timing.d.ts +15 -0
  16. package/dist/chat-routes/producer-stream.d.ts +5 -0
  17. package/dist/chat-routes/route-producer.d.ts +3 -0
  18. package/dist/chat-routes/route-storage.d.ts +7 -0
  19. package/dist/chat-routes/router-producer.d.ts +31 -5
  20. package/dist/chat-routes/turn-admission.d.ts +2 -1
  21. package/dist/chat-routes/turn-execution.d.ts +6 -11
  22. package/dist/chat-routes/turn-ownership.d.ts +22 -0
  23. package/dist/chat-routes/turn-route-contracts.d.ts +112 -105
  24. package/dist/chat-routes/turn-routes.d.ts +4 -4
  25. package/dist/chat-routes/wire.d.ts +0 -7
  26. package/dist/chat-store/index.d.ts +1 -1
  27. package/dist/chat-store/index.js +21 -3
  28. package/dist/chat-store/index.js.map +1 -1
  29. package/dist/chat-store/schema.d.ts +3 -2
  30. package/dist/chat-store/store.d.ts +8 -0
  31. package/dist/{chunk-GIEUZBQQ.js → chunk-4CALWPN5.js} +3 -7
  32. package/dist/chunk-4CALWPN5.js.map +1 -0
  33. package/dist/chunk-4DBHC63F.js +54 -0
  34. package/dist/chunk-4DBHC63F.js.map +1 -0
  35. package/dist/{chunk-G7M2C72Q.js → chunk-5TSRFF5W.js} +1 -1
  36. package/dist/chunk-5TSRFF5W.js.map +1 -0
  37. package/dist/chunk-A2NQMVMF.js +485 -0
  38. package/dist/chunk-A2NQMVMF.js.map +1 -0
  39. package/dist/{chunk-PCAY23GS.js → chunk-AVBNS64P.js} +172 -2
  40. package/dist/chunk-AVBNS64P.js.map +1 -0
  41. package/dist/{chunk-4P5NFBWX.js → chunk-BI5AZAOO.js} +4 -4
  42. package/dist/chunk-BV3VZEKB.js +483 -0
  43. package/dist/chunk-BV3VZEKB.js.map +1 -0
  44. package/dist/{chunk-UW2DKTEM.js → chunk-IDG2XR5O.js} +20 -10
  45. package/dist/chunk-IDG2XR5O.js.map +1 -0
  46. package/dist/{chunk-KS4I7KVC.js → chunk-JRTWTADT.js} +184 -123
  47. package/dist/chunk-JRTWTADT.js.map +1 -0
  48. package/dist/chunk-KG2Y44XT.js +1 -0
  49. package/dist/chunk-KG2Y44XT.js.map +1 -0
  50. package/dist/chunk-MM3GOLHO.js +3365 -0
  51. package/dist/chunk-MM3GOLHO.js.map +1 -0
  52. package/dist/chunk-N6URQ6DM.js +225 -0
  53. package/dist/chunk-N6URQ6DM.js.map +1 -0
  54. package/dist/{chunk-ISRPOPMM.js → chunk-ND5XWLRU.js} +21 -18
  55. package/dist/chunk-ND5XWLRU.js.map +1 -0
  56. package/dist/{chunk-IUVDR3KJ.js → chunk-NHVSO47Q.js} +2 -2
  57. package/dist/{chunk-FAXSYC2C.js → chunk-RZLCBWGG.js} +2 -2
  58. package/dist/{chunk-MRZP65DZ.js → chunk-SRWQCWLR.js} +14 -3
  59. package/dist/chunk-SRWQCWLR.js.map +1 -0
  60. package/dist/{chunk-JRW6LCIA.js → chunk-V6YGLAQC.js} +2 -2
  61. package/dist/{chunk-54YIL7WM.js → chunk-WPPDNS63.js} +4 -4
  62. package/dist/{chunk-CQZVJVME.js → chunk-YCMVNXAX.js} +2 -2
  63. package/dist/design-canvas/index.js +3 -3
  64. package/dist/openui/index.js +3 -3
  65. package/dist/operator/index.js +2 -2
  66. package/dist/platform/billable-turn-admission.d.ts +13 -9
  67. package/dist/platform/delegated-keys.d.ts +4 -3
  68. package/dist/platform/delegated-turn-keys.d.ts +17 -6
  69. package/dist/platform/index.js +80 -23
  70. package/dist/platform/index.js.map +1 -1
  71. package/dist/preset-cloudflare/index.d.ts +2 -0
  72. package/dist/preset-cloudflare/index.js +344 -0
  73. package/dist/preset-cloudflare/index.js.map +1 -1
  74. package/dist/preset-cloudflare/native-completion-owner.d.ts +90 -0
  75. package/dist/preset-cloudflare/native-completion-store.d.ts +56 -0
  76. package/dist/preset-cloudflare/native-completion-workflow.d.ts +10 -0
  77. package/dist/public-consultation/index.js +28 -7
  78. package/dist/public-consultation/index.js.map +1 -1
  79. package/dist/rollout/d1.d.ts +103 -3
  80. package/dist/rollout/d1.js +152 -5
  81. package/dist/rollout/d1.js.map +1 -1
  82. package/dist/runtime/index.js +3 -4
  83. package/dist/runtime/index.js.map +1 -1
  84. package/dist/runtime/router-turn.d.ts +4 -0
  85. package/dist/runtime/router-turn.js +2 -3
  86. package/dist/sandbox/index.js +3 -4
  87. package/dist/sandbox/sandbox-run-tool.d.ts +5 -0
  88. package/dist/sequences/index.js +5 -5
  89. package/dist/signoff/cli.js +6 -1
  90. package/dist/signoff/cli.js.map +1 -1
  91. package/dist/signoff/config.d.ts +3 -1
  92. package/dist/signoff/index.d.ts +2 -1
  93. package/dist/signoff/index.js +3 -1
  94. package/dist/signoff/phases.d.ts +3 -0
  95. package/dist/signoff/proof.js +3 -0
  96. package/dist/signoff/proof.js.map +1 -1
  97. package/dist/signoff/run.d.ts +3 -1
  98. package/dist/signoff/types.d.ts +13 -0
  99. package/dist/skills-placement/box.js +5 -5
  100. package/dist/skills-placement/index.js +2 -2
  101. package/dist/tools/index.js +1 -1
  102. package/dist/turn-stream/adapters.d.ts +10 -4
  103. package/dist/turn-stream/index.js +33 -356
  104. package/dist/turn-stream/index.js.map +1 -1
  105. package/dist/turn-trace/index.d.ts +1 -0
  106. package/dist/turn-trace/index.js +4 -5
  107. package/dist/turn-trace/phase-timing.d.ts +20 -0
  108. package/dist/turn-trace/recorder.d.ts +3 -0
  109. package/dist/turn-trace/turn-facts.d.ts +17 -0
  110. package/dist/web-react/agent-profile-editor.js +1 -1
  111. package/dist/web-react/chat-stream.d.ts +0 -7
  112. package/dist/web-react/index.js +7 -9
  113. package/dist/work-product/index.js +7 -7
  114. package/package.json +1 -1
  115. package/dist/chat-routes/minted-thread.d.ts +0 -63
  116. package/dist/chunk-6R73V3Y5.js +0 -17
  117. package/dist/chunk-6R73V3Y5.js.map +0 -1
  118. package/dist/chunk-CCVWR33L.js +0 -99
  119. package/dist/chunk-CCVWR33L.js.map +0 -1
  120. package/dist/chunk-EFQUAWWF.js +0 -1749
  121. package/dist/chunk-EFQUAWWF.js.map +0 -1
  122. package/dist/chunk-G7M2C72Q.js.map +0 -1
  123. package/dist/chunk-GIEUZBQQ.js.map +0 -1
  124. package/dist/chunk-ISRPOPMM.js.map +0 -1
  125. package/dist/chunk-KS4I7KVC.js.map +0 -1
  126. package/dist/chunk-MRZP65DZ.js.map +0 -1
  127. package/dist/chunk-PCAY23GS.js.map +0 -1
  128. package/dist/chunk-UW2DKTEM.js.map +0 -1
  129. package/dist/chunk-VK3F4N4U.js +0 -133
  130. package/dist/chunk-VK3F4N4U.js.map +0 -1
  131. /package/dist/{chunk-4P5NFBWX.js.map → chunk-BI5AZAOO.js.map} +0 -0
  132. /package/dist/{chunk-IUVDR3KJ.js.map → chunk-NHVSO47Q.js.map} +0 -0
  133. /package/dist/{chunk-FAXSYC2C.js.map → chunk-RZLCBWGG.js.map} +0 -0
  134. /package/dist/{chunk-JRW6LCIA.js.map → chunk-V6YGLAQC.js.map} +0 -0
  135. /package/dist/{chunk-54YIL7WM.js.map → chunk-WPPDNS63.js.map} +0 -0
  136. /package/dist/{chunk-CQZVJVME.js.map → chunk-YCMVNXAX.js.map} +0 -0
@@ -1,124 +1,40 @@
1
1
  import {
2
- reconcileStaleTurnLock
3
- } from "../chunk-CCVWR33L.js";
4
- import {
5
- base64UrlEncodeText,
6
- constantTimeEqual,
7
- hmacSha256Base64Url
8
- } from "../chunk-S5SRJJQG.js";
2
+ ACTIVITY_TTL_MS,
3
+ MAX_RECENT_CREATED,
4
+ TURN_LOCK_TTL_MS,
5
+ TURN_STREAM_PATHS,
6
+ TURN_STREAM_STORAGE_KEYS,
7
+ TURN_STREAM_TOKEN_HEADER,
8
+ TURN_STREAM_TOKEN_TTL_MS,
9
+ acquireDurableTurnLock,
10
+ activeTurnLock,
11
+ broadcastThreadCreated,
12
+ broadcastWorkspaceActivity,
13
+ createDurableObjectTurnEventStore,
14
+ createDurableTurnLock,
15
+ createTurnLock,
16
+ createTurnStreamUpgradeHandler,
17
+ interruptedReleaseApplies,
18
+ mintTurnStreamToken,
19
+ peekDurableTurnLock,
20
+ pruneStaleThreads,
21
+ reconcileStaleDurableTurnLock,
22
+ releaseDurableTurnLock,
23
+ releaseInterruptedDurableTurnLock,
24
+ scopeIndexChannelKey,
25
+ threadChannelKey,
26
+ turnEventStorageKey,
27
+ turnLockChannelKey,
28
+ turnLockMatchesRelease,
29
+ turnLockStorageKey,
30
+ turnStorageChannelKey,
31
+ verifyTurnStreamToken,
32
+ workspaceChannelKey
33
+ } from "../chunk-A2NQMVMF.js";
9
34
  import {
10
35
  DEFAULT_RUNNING_TURN_LEASE_MS
11
36
  } from "../chunk-ISP6ZH3G.js";
12
-
13
- // src/turn-stream/core.ts
14
- var TURN_STREAM_TOKEN_TTL_MS = 6e4;
15
- var TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
16
- async function mintTurnStreamToken(channelName, secret, now = Date.now, ttlMs = TURN_STREAM_TOKEN_TTL_MS) {
17
- if (!secret || secret.length < 32) throw new Error("turn-stream token secret must be at least 32 characters");
18
- const expiresAt = now() + ttlMs;
19
- const payload = `v1.${base64UrlEncodeText(channelName)}.${expiresAt.toString(36)}`;
20
- return `${payload}.${await hmacSha256Base64Url(payload, secret)}`;
21
- }
22
- async function verifyTurnStreamToken(channelName, token, secret, now = Date.now) {
23
- if (!secret || secret.length < 32) return false;
24
- const parts = token.split(".");
25
- if (parts.length !== 4 || parts[0] !== "v1") return false;
26
- const [, name, expires36, mac] = parts;
27
- if (name !== base64UrlEncodeText(channelName)) return false;
28
- if (!/^[0-9a-z]+$/.test(expires36)) return false;
29
- const expiresAt = parseInt(expires36, 36);
30
- if (!Number.isSafeInteger(expiresAt) || expiresAt <= now()) return false;
31
- const expected = await hmacSha256Base64Url(`v1.${name}.${expires36}`, secret);
32
- return constantTimeEqual(mac, expected);
33
- }
34
- function threadChannelKey(workspaceId, threadId) {
35
- return `${workspaceId}:${threadId}`;
36
- }
37
- function workspaceChannelKey(workspaceId) {
38
- return workspaceId;
39
- }
40
- function turnLockChannelKey(workspaceId, _threadId, _scope) {
41
- return workspaceChannelKey(workspaceId);
42
- }
43
- function turnLockStorageKey(scope, threadId) {
44
- return scope === "workspace" ? TURN_STREAM_STORAGE_KEYS.lock : `${TURN_STREAM_STORAGE_KEYS.threadLockPrefix}${threadId}`;
45
- }
46
- function turnStorageChannelKey(turnId) {
47
- return `turn:${turnId}`;
48
- }
49
- function scopeIndexChannelKey(scopeId) {
50
- return `scope:${scopeId}`;
51
- }
52
- var MAX_RECENT_CREATED = 50;
53
- var ACTIVITY_TTL_MS = 15 * 60 * 1e3;
54
- function pruneStaleThreads(active, now, ttlMs) {
55
- const removed = [];
56
- for (const [threadId, startedAt] of active) {
57
- if (now - startedAt > ttlMs) {
58
- active.delete(threadId);
59
- removed.push(threadId);
60
- }
61
- }
62
- return removed;
63
- }
64
- var TURN_LOCK_TTL_MS = 30 * 60 * 1e3;
65
- function activeTurnLock(stored, now) {
66
- if (!stored) return null;
67
- const lock = stored.scope ? stored : { ...stored, scope: "thread" };
68
- return lock.expiresAt > now ? lock : null;
69
- }
70
- function createTurnLock(input, now, ttlMs = TURN_LOCK_TTL_MS) {
71
- return {
72
- workspaceId: input.workspaceId,
73
- threadId: input.threadId,
74
- scope: input.scope,
75
- executionId: input.executionId,
76
- lockId: input.lockId,
77
- startedAt: now,
78
- expiresAt: now + ttlMs,
79
- ...input.turnId ? { turnId: input.turnId } : {}
80
- };
81
- }
82
- function turnLockMatchesRelease(active, input) {
83
- if (active.executionId !== input.executionId) return false;
84
- if (input.lockId && active.lockId !== input.lockId) return false;
85
- return true;
86
- }
87
- function interruptedReleaseApplies(active, input) {
88
- if (active.threadId !== input.threadId) return false;
89
- if (active.startedAt > input.interruptedAt) return false;
90
- if (active.turnId) {
91
- if (active.turnId !== input.turnId) return false;
92
- } else if (input.turnId) {
93
- return false;
94
- }
95
- return true;
96
- }
97
- var TURN_STREAM_PATHS = {
98
- broadcast: "/broadcast",
99
- lockAcquire: "/chat-turn-lock/acquire",
100
- /** Read the active lock without changing it; also brings the object up before a turn needs it. */
101
- lockPeek: "/chat-turn-lock/peek",
102
- lockRelease: "/chat-turn-lock/release",
103
- lockReleaseInterrupted: "/chat-turn-lock/release-interrupted",
104
- turnEventsAppend: "/turn-events/append",
105
- turnEventsRead: "/turn-events/read",
106
- turnStatusSet: "/turn-status/set",
107
- turnStatusGet: "/turn-status/get",
108
- scopeStatusSet: "/turn-scope/set",
109
- scopeRunningList: "/turn-scope/running"
110
- };
111
- var TURN_STREAM_STORAGE_KEYS = {
112
- lock: "chatTurnLock",
113
- threadLockPrefix: "chatTurnLock:thread:",
114
- activeThreads: "activeThreads",
115
- turnStatus: "turnStatus",
116
- turnScope: "turnScopeIndex",
117
- turnEventPrefix: "turnEvent:"
118
- };
119
- function turnEventStorageKey(seq) {
120
- return `${TURN_STREAM_STORAGE_KEYS.turnEventPrefix}${String(seq).padStart(10, "0")}`;
121
- }
37
+ import "../chunk-S5SRJJQG.js";
122
38
 
123
39
  // src/turn-stream/do.ts
124
40
  function jsonResponse(body, status = 200) {
@@ -536,245 +452,6 @@ var TurnStreamDO = class {
536
452
  }
537
453
  };
538
454
 
539
- // src/turn-stream/adapters.ts
540
- var INTERNAL_ORIGIN = "https://turn-stream.internal";
541
- async function postJson(namespace, channelKey, path, body, auth) {
542
- const stub = namespace.get(namespace.idFromName(channelKey));
543
- const response = await stub.fetch(`${INTERNAL_ORIGIN}${path}`, {
544
- method: "POST",
545
- headers: {
546
- "Content-Type": "application/json",
547
- [TURN_STREAM_TOKEN_HEADER]: await mintTurnStreamToken(channelKey, auth.secret)
548
- },
549
- body: JSON.stringify(body)
550
- });
551
- return { status: response.status, body: await response.json() };
552
- }
553
- async function postJsonOk(namespace, channelKey, path, body, auth) {
554
- const result = await postJson(namespace, channelKey, path, body, auth);
555
- if (result.status !== 200) {
556
- throw new Error(`turn-stream ${path} failed with status ${result.status}`);
557
- }
558
- return result.body;
559
- }
560
- function createDurableObjectTurnEventStore(namespace, auth) {
561
- return {
562
- async append(turnId, events) {
563
- if (!events.length) return;
564
- await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnEventsAppend, { events }, auth);
565
- },
566
- async read(turnId, fromSeq) {
567
- const body = await postJsonOk(
568
- namespace,
569
- turnStorageChannelKey(turnId),
570
- TURN_STREAM_PATHS.turnEventsRead,
571
- { fromSeq },
572
- auth
573
- );
574
- return body.events;
575
- },
576
- async setStatus(turnId, status, scopeId, options) {
577
- if (options?.preserveUpdatedAt || options?.onlyIfRunningBefore !== void 0) {
578
- throw new Error("The turn-stream Durable Object store does not support guarded or time-preserving status writes");
579
- }
580
- await postJsonOk(namespace, turnStorageChannelKey(turnId), TURN_STREAM_PATHS.turnStatusSet, { status }, auth);
581
- if (scopeId) {
582
- await postJsonOk(namespace, scopeIndexChannelKey(scopeId), TURN_STREAM_PATHS.scopeStatusSet, {
583
- turnId,
584
- status
585
- }, auth);
586
- }
587
- },
588
- async getStatus(turnId) {
589
- const body = await postJsonOk(
590
- namespace,
591
- turnStorageChannelKey(turnId),
592
- TURN_STREAM_PATHS.turnStatusGet,
593
- {},
594
- auth
595
- );
596
- return body.status;
597
- },
598
- async listRunning(scopeId) {
599
- const body = await postJsonOk(
600
- namespace,
601
- scopeIndexChannelKey(scopeId),
602
- TURN_STREAM_PATHS.scopeRunningList,
603
- {},
604
- auth
605
- );
606
- return body.running;
607
- }
608
- };
609
- }
610
- async function acquireDurableTurnLock(namespace, input, auth) {
611
- const lockId = input.lockId ?? crypto.randomUUID();
612
- const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
613
- const result = await postJson(namespace, key, TURN_STREAM_PATHS.lockAcquire, {
614
- ...input,
615
- lockId
616
- }, auth);
617
- if (result.status !== 200 && result.status !== 409) {
618
- throw new Error(`turn-stream lock acquire failed with status ${result.status}`);
619
- }
620
- return result.body;
621
- }
622
- async function peekDurableTurnLock(namespace, input, auth) {
623
- const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
624
- const result = await postJson(namespace, key, TURN_STREAM_PATHS.lockPeek, {
625
- scope: input.scope,
626
- threadId: input.threadId
627
- }, auth);
628
- if (result.status !== 200) throw new Error(`turn-stream lock peek failed with status ${result.status}`);
629
- return result.body.active ?? null;
630
- }
631
- async function releaseDurableTurnLock(namespace, input, auth) {
632
- const key = turnLockChannelKey(input.workspaceId, input.threadId, input.scope);
633
- return postJsonOk(namespace, key, TURN_STREAM_PATHS.lockRelease, input, auth);
634
- }
635
- async function releaseInterruptedDurableTurnLock(namespace, input, auth) {
636
- const scopes = input.scope ? [input.scope] : ["workspace", "thread"];
637
- for (const scope of scopes) {
638
- const key = turnLockChannelKey(input.workspaceId, input.threadId, scope);
639
- const result = await postJsonOk(namespace, key, TURN_STREAM_PATHS.lockReleaseInterrupted, {
640
- scope,
641
- threadId: input.threadId,
642
- interruptedAt: input.interruptedAt,
643
- ...input.turnId ? { turnId: input.turnId } : {}
644
- }, auth);
645
- if (result.released) return true;
646
- }
647
- return false;
648
- }
649
- async function reconcileStaleDurableTurnLock(options) {
650
- const { namespace, auth, workspaceId, threadId, active, ...policy } = options;
651
- return reconcileStaleTurnLock({
652
- ...policy,
653
- lockStartedAt: active.startedAt,
654
- release: (fence) => releaseInterruptedDurableTurnLock(namespace, {
655
- workspaceId,
656
- threadId: active.threadId,
657
- scope: active.scope,
658
- interruptedAt: fence.observedAt,
659
- ...active.turnId ? { turnId: active.turnId } : {}
660
- }, auth)
661
- });
662
- }
663
- function defaultRefusalResponse(active, diagnostics) {
664
- const workspaceConflict = active.scope === "workspace";
665
- return Response.json(
666
- {
667
- error: {
668
- code: workspaceConflict ? "workspace_turn_in_flight" : "chat_turn_in_flight",
669
- 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.",
670
- threadId: active.threadId,
671
- executionId: active.executionId,
672
- ...active.turnId ? { turnId: active.turnId } : {},
673
- lockStartedAt: active.startedAt,
674
- lockAgeMs: Date.now() - active.startedAt,
675
- ...diagnostics ? { diagnostics } : {}
676
- }
677
- },
678
- { status: 409 }
679
- );
680
- }
681
- function createDurableTurnLock(options) {
682
- return {
683
- // Every lock lives on the workspace channel, so this wakes that object
684
- // (evicted after idle) before the turn's acquire reaches it.
685
- async warm(target) {
686
- await peekDurableTurnLock(options.namespace, { workspaceId: target.tenantId, threadId: target.threadId, scope: "thread" }, options.auth);
687
- },
688
- async acquire(args) {
689
- const workspaceId = args.identity.tenantId;
690
- const threadId = args.identity.sessionId;
691
- const scope = options.scopeOf(args);
692
- const executionId = options.lockExecutionIdOf?.(args) ?? args.executionId;
693
- const turnId = options.clientTurnIdOf ? options.clientTurnIdOf(args) : args.body.turnId;
694
- const input = {
695
- workspaceId,
696
- threadId,
697
- scope,
698
- executionId,
699
- ...turnId ? { turnId } : {}
700
- };
701
- let acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
702
- let diagnostics;
703
- if (!acquired.acquired && options.reconcile) {
704
- const reconciled = await options.reconcile(args, acquired.active);
705
- diagnostics = reconciled.diagnostics;
706
- if (reconciled.released) {
707
- acquired = await acquireDurableTurnLock(options.namespace, input, options.auth);
708
- }
709
- }
710
- if (!acquired.acquired) {
711
- return {
712
- acquired: false,
713
- response: (options.onRefused ?? defaultRefusalResponse)(acquired.active, diagnostics)
714
- };
715
- }
716
- const handle = {
717
- workspaceId,
718
- threadId,
719
- scope,
720
- executionId,
721
- lockId: acquired.lock.lockId
722
- };
723
- return { acquired: true, handle };
724
- },
725
- async release(handle) {
726
- if (!handle) return;
727
- await releaseDurableTurnLock(options.namespace, handle, options.auth);
728
- }
729
- };
730
- }
731
- async function broadcastWorkspaceActivity(namespace, workspaceId, threadId, phase, auth) {
732
- try {
733
- await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
734
- type: "thread.activity",
735
- timestamp: Date.now(),
736
- data: { threadId, phase, workspaceId, sessionId: workspaceId }
737
- }, auth);
738
- } catch {
739
- }
740
- }
741
- async function broadcastThreadCreated(namespace, workspaceId, thread, auth) {
742
- try {
743
- await postJson(namespace, workspaceChannelKey(workspaceId), TURN_STREAM_PATHS.broadcast, {
744
- type: "thread.created",
745
- timestamp: Date.now(),
746
- data: { threadId: thread.threadId, title: thread.title, workspaceId, sessionId: workspaceId }
747
- }, auth);
748
- } catch {
749
- }
750
- }
751
- function createTurnStreamUpgradeHandler(options) {
752
- const path = options.path ?? "/api/session-stream";
753
- if (!options.authSecret || options.authSecret.length < 32) {
754
- throw new Error("createTurnStreamUpgradeHandler requires authSecret (>= 32 chars) \u2014 the DO fails closed without tokens");
755
- }
756
- return async (request) => {
757
- const url = new URL(request.url);
758
- if (url.pathname !== path || request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return null;
759
- if (url.searchParams.has("threadId")) {
760
- return new Response("Thread replay uses the sandbox session gateway or chat replay route", { status: 400 });
761
- }
762
- const workspaceId = url.searchParams.get("workspaceId");
763
- if (!workspaceId) return new Response("Missing workspaceId", { status: 400 });
764
- const auth = await options.authorize(request, { workspaceId });
765
- if (!auth.ok) return auth.response;
766
- const key = workspaceChannelKey(workspaceId);
767
- const stub = options.namespace.get(options.namespace.idFromName(key));
768
- const forwardUrl = new URL(request.url);
769
- forwardUrl.searchParams.set("sessionId", workspaceId);
770
- forwardUrl.searchParams.set("scope", "workspace");
771
- forwardUrl.searchParams.delete("token");
772
- const headers = new Headers(request.headers);
773
- headers.set(TURN_STREAM_TOKEN_HEADER, await mintTurnStreamToken(key, options.authSecret));
774
- return stub.fetch(new Request(new Request(forwardUrl, request), { headers }));
775
- };
776
- }
777
-
778
455
  // src/turn-stream/memory.ts
779
456
  function createMemoryStorage() {
780
457
  const map = /* @__PURE__ */ new Map();