nanocodex 0.5.0 → 0.6.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.
Files changed (196) hide show
  1. package/README.md +944 -78
  2. package/actions/events.mjs +14 -25
  3. package/actions/index.d.mts +1 -0
  4. package/actions/index.mjs +11 -1
  5. package/actions/session.d.mts +29 -1
  6. package/actions/session.mjs +22 -0
  7. package/actions/turn.d.mts +15 -6
  8. package/actions/turn.mjs +10 -0
  9. package/actions/voice.d.mts +26 -0
  10. package/actions/voice.mjs +54 -0
  11. package/browser/Agent.d.mts +41 -24
  12. package/browser/Agent.mjs +7 -84
  13. package/browser/ChatGptSubscription.d.mts +7 -0
  14. package/browser/ChatGptSubscription.mjs +19 -0
  15. package/browser/InlineAgent.mjs +267 -0
  16. package/browser/Transport.d.mts +80 -0
  17. package/browser/Transport.mjs +63 -0
  18. package/browser/Voice.d.mts +86 -0
  19. package/browser/Voice.mjs +316 -0
  20. package/browser/VoiceSession.mjs +763 -0
  21. package/browser/WorkerAgent.d.mts +65 -0
  22. package/browser/WorkerAgent.mjs +1467 -0
  23. package/browser/agent.worker.mjs +3 -0
  24. package/browser/config.d.mts +36 -0
  25. package/browser/config.mjs +439 -0
  26. package/browser/engine.mjs +13 -0
  27. package/browser/harness.mjs +55 -0
  28. package/browser/host.d.mts +33 -5
  29. package/browser/host.mjs +320 -26
  30. package/browser/hostManagedWebSocket.d.mts +14 -0
  31. package/browser/hostManagedWebSocket.mjs +110 -0
  32. package/browser/index.d.mts +64 -1
  33. package/browser/index.mjs +22 -1
  34. package/browser/indexeddb-durability-store.mjs +210 -0
  35. package/browser/workspace.d.mts +16 -0
  36. package/browser/workspace.mjs +107 -0
  37. package/cloud/Client.d.mts +83 -0
  38. package/cloud/Client.mjs +231 -0
  39. package/cloud/Decorator.d.mts +31 -0
  40. package/cloud/Decorator.mjs +37 -0
  41. package/cloud/Dialog.d.mts +113 -0
  42. package/cloud/Dialog.mjs +366 -0
  43. package/cloud/Errors.d.mts +22 -0
  44. package/cloud/Errors.mjs +39 -0
  45. package/cloud/Principal.d.mts +26 -0
  46. package/cloud/Principal.mjs +88 -0
  47. package/cloud/RemoteProvider.mjs +88 -0
  48. package/cloud/Transport.d.mts +47 -0
  49. package/cloud/Transport.mjs +454 -0
  50. package/cloud/actions/account.d.mts +9 -0
  51. package/cloud/actions/account.mjs +19 -0
  52. package/cloud/actions/agent.d.mts +18 -0
  53. package/cloud/actions/agent.mjs +429 -0
  54. package/cloud/actions/connection.d.mts +133 -0
  55. package/cloud/actions/connection.mjs +580 -0
  56. package/cloud/actions/grant.d.mts +10 -0
  57. package/cloud/actions/grant.mjs +12 -0
  58. package/cloud/actions/index.d.mts +7 -0
  59. package/cloud/actions/index.mjs +7 -0
  60. package/cloud/actions/machineUsd.d.mts +23 -0
  61. package/cloud/actions/machineUsd.mjs +37 -0
  62. package/cloud/actions/model.d.mts +12 -0
  63. package/cloud/actions/model.mjs +50 -0
  64. package/cloud/actions/mpp.d.mts +28 -0
  65. package/cloud/actions/mpp.mjs +39 -0
  66. package/cloud/index.d.mts +30 -0
  67. package/cloud/index.mjs +9 -0
  68. package/cloud/internal.mjs +533 -0
  69. package/cloud/mercator.mjs +108 -0
  70. package/cloud/server/HostPrincipal.d.mts +34 -0
  71. package/cloud/server/HostPrincipal.mjs +202 -0
  72. package/cloud/server/index.d.mts +1 -0
  73. package/cloud/server/index.mjs +1 -0
  74. package/cloud/types.d.mts +212 -0
  75. package/cloudflare/Agent.d.mts +136 -0
  76. package/cloudflare/Agent.mjs +784 -0
  77. package/cloudflare/egress-subject.mjs +19 -0
  78. package/cloudflare/egress.d.mts +41 -0
  79. package/cloudflare/egress.mjs +119 -0
  80. package/cloudflare/event-socket.mjs +316 -0
  81. package/cloudflare/index.d.mts +7 -0
  82. package/cloudflare/index.mjs +6 -0
  83. package/host/Agent.d.mts +55 -0
  84. package/host/Agent.mjs +1 -0
  85. package/host/index.d.mts +71 -0
  86. package/host/index.mjs +10 -0
  87. package/index.d.mts +46 -0
  88. package/index.mjs +11 -0
  89. package/internal.mjs +673 -61
  90. package/managed/Agent.d.mts +459 -0
  91. package/managed/Agent.mjs +1824 -0
  92. package/managed/ManagedError.d.mts +9 -0
  93. package/managed/ManagedError.mjs +8 -0
  94. package/managed/README.md +244 -0
  95. package/managed/Voice.mjs +209 -0
  96. package/managed/index.d.mts +22 -0
  97. package/managed/index.mjs +2 -0
  98. package/managed/internal.mjs +119 -0
  99. package/node/Agent.d.mts +35 -8
  100. package/node/Agent.mjs +116 -25
  101. package/node/ChatGptSubscription.d.mts +9 -0
  102. package/node/ChatGptSubscription.mjs +17 -0
  103. package/node/Transport.d.mts +41 -0
  104. package/node/Transport.mjs +46 -0
  105. package/node/host.mjs +99 -17
  106. package/node/index.d.mts +45 -1
  107. package/node/index.mjs +16 -1
  108. package/node/workspace.d.mts +10 -0
  109. package/node/workspace.mjs +198 -0
  110. package/package.json +145 -11
  111. package/pkg-node/nanocodex.d.ts +523 -11
  112. package/pkg-node/nanocodex.js +2038 -179
  113. package/pkg-node/nanocodex_bg.wasm.d.ts +100 -29
  114. package/pkg-web/.nanocodex-bindgen-stamp +6 -0
  115. package/pkg-web/nanocodex-build.json +1 -0
  116. package/pkg-web/nanocodex.d.ts +623 -40
  117. package/pkg-web/nanocodex.js +2031 -178
  118. package/pkg-web/nanocodex_bg.js +2667 -0
  119. package/pkg-web/nanocodex_bg.wasm +0 -0
  120. package/pkg-web/nanocodex_bg.wasm.d.ts +100 -29
  121. package/pkg-web/nanocodex_worker.js +9 -0
  122. package/runtime/chatgpt-subscription.mjs +212 -0
  123. package/runtime/cloudflare-durability-store.d.mts +26 -0
  124. package/runtime/cloudflare-durability-store.mjs +14 -0
  125. package/runtime/code-evaluator.worker.mjs +137 -0
  126. package/runtime/code-runtime.mjs +1 -250
  127. package/runtime/durability-store.d.mts +85 -0
  128. package/runtime/durability-store.mjs +752 -0
  129. package/runtime/durability.mjs +174 -0
  130. package/runtime/managed-transport.mjs +461 -0
  131. package/runtime/mcp-runtime.mjs +534 -0
  132. package/runtime/postgres-durability-store.d.mts +64 -0
  133. package/runtime/postgres-durability-store.mjs +581 -0
  134. package/runtime/quickjs-evaluator.d.mts +17 -0
  135. package/runtime/quickjs-evaluator.mjs +236 -0
  136. package/runtime/response-controls.mjs +42 -0
  137. package/runtime/response-lanes.mjs +72 -0
  138. package/runtime/responses-transport.mjs +22 -0
  139. package/runtime/subagents.d.mts +107 -0
  140. package/runtime/subagents.mjs +54 -0
  141. package/runtime/subscription-store.d.mts +8 -0
  142. package/runtime/subscription-store.mjs +42 -0
  143. package/runtime/tempo-provider.d.mts +125 -0
  144. package/runtime/tempo-provider.mjs +264 -0
  145. package/runtime/tool-configuration.mjs +1 -0
  146. package/runtime/tool-router.mjs +1 -0
  147. package/runtime/utf8.mjs +1 -0
  148. package/runtime/worker-evaluator.mjs +162 -0
  149. package/runtime/workspace.d.mts +1 -0
  150. package/runtime/workspace.mjs +1 -0
  151. package/tools/Tools.d.mts +56 -0
  152. package/tools/Tools.mjs +136 -0
  153. package/tools/artifact.d.mts +1 -0
  154. package/tools/artifact.mjs +1 -0
  155. package/tools/attachment.mjs +1 -0
  156. package/tools/bash.d.mts +1 -0
  157. package/tools/bash.mjs +1 -0
  158. package/tools/browser/accountInfo.mjs +795 -0
  159. package/tools/browser/browserBuffer.mjs +18 -0
  160. package/tools/browser/browserCompiler.mjs +155 -0
  161. package/tools/browser/browserEgress.mjs +161 -0
  162. package/tools/browser/browserPython.mjs +133 -0
  163. package/tools/browser/browserShell.mjs +1075 -0
  164. package/tools/browser/browserSprintf.mjs +4 -0
  165. package/tools/browser/browserSsh.mjs +201 -0
  166. package/tools/browser/browserZlib.mjs +136 -0
  167. package/tools/browser/compiler.worker.mjs +160 -0
  168. package/tools/browser/devTunnelsSshBrowser.mjs +13 -0
  169. package/tools/browser/index.d.mts +209 -0
  170. package/tools/browser/index.mjs +174 -0
  171. package/tools/browser/opfsGit.mjs +248 -0
  172. package/tools/browser/python.worker.mjs +114 -0
  173. package/tools/browser/threadGit.mjs +197 -0
  174. package/tools/browser/unsupportedNodeRsa.mjs +5 -0
  175. package/tools/browser/workspace.mjs +83 -0
  176. package/tools/dataset.d.mts +1 -0
  177. package/tools/dataset.mjs +1 -0
  178. package/tools/datasetContract.mjs +1 -0
  179. package/tools/datasetEngine.mjs +1 -0
  180. package/tools/hostedCatalog.d.mts +1 -0
  181. package/tools/hostedCatalog.mjs +1 -0
  182. package/tools/index.d.mts +49 -0
  183. package/tools/index.mjs +19 -0
  184. package/tools/namedTool.mjs +1 -0
  185. package/tools/repository-workspace.d.mts +1 -0
  186. package/tools/repository-workspace.mjs +1 -0
  187. package/tools/ssh.d.mts +1 -0
  188. package/tools/ssh.mjs +1 -0
  189. package/tools/standard.mjs +1 -0
  190. package/tools/standardDescriptions.mjs +1 -0
  191. package/types.d.mts +431 -16
  192. package/worker/ChatGptSubscription.d.mts +9 -0
  193. package/worker/ChatGptSubscription.mjs +29 -0
  194. package/worker/index.d.mts +18 -0
  195. package/worker/index.mjs +5 -0
  196. package/pkg-node/nanocodex_bg.wasm +0 -0
@@ -0,0 +1,784 @@
1
+ import { responseControlsSocket } from "../runtime/response-controls.mjs";
2
+ import * as HostAgent from "../host/Agent.mjs";
3
+ import {
4
+ CLOUDFLARE_SESSION_RESERVATION,
5
+ commitCloudflareAgentSession,
6
+ installHostBridge,
7
+ loadDurabilityRuntime,
8
+ mayBindCloudflareSubagentSession,
9
+ mayReleaseCloudflareSubagentSession,
10
+ observeAgentRelease,
11
+ prepareCloudflareAgentSession,
12
+ releaseAgentSession,
13
+ routePrompt,
14
+ } from "../internal.mjs";
15
+ import { pruneDurableReceipts as pruneWasmDurableReceipts, managedBootstrapPlan } from "../pkg-web/nanocodex.js";
16
+ import * as Transport from "../browser/Transport.mjs";
17
+ import { initializeBrowserEngine } from "../browser/engine.mjs";
18
+ import { createCloudflareDurabilityStore } from "../runtime/cloudflare-durability-store.mjs";
19
+ import {
20
+ createMemoryDurabilityStore,
21
+ durabilityRevision,
22
+ exportDurabilityState as exportPortableState,
23
+ exportDurabilityStatePage as exportPortableStatePage,
24
+ importDurabilityState as importPortableState,
25
+ } from "../runtime/durability-store.mjs";
26
+ import { cloudflareEgress } from "./egress.mjs";
27
+ import { scopeCloudflareEgress } from "./egress-subject.mjs";
28
+ import {
29
+ clearCloudflareEventSocket,
30
+ createCloudflareEventSocket,
31
+ } from "./event-socket.mjs";
32
+
33
+ const STARTUP_TIMEOUT_MS = 10_000;
34
+ const INTERNAL_RUNTIME = Symbol.for("nanocodex.cloudflare.internalRuntime");
35
+ const INTERNAL_CONFIGURATION = Symbol.for("nanocodex.cloudflare.internalConfiguration");
36
+ const EPHEMERAL_APPLICATION_OPTIONS = new Set([
37
+ "additionalInstructions",
38
+ "fastMode",
39
+ "instructions",
40
+ "model",
41
+ "reasoningMode",
42
+ "resume",
43
+ "sessionId",
44
+ "thinking",
45
+ "tools",
46
+ "workspace",
47
+ ]);
48
+ const APPLICATION_OPTIONS = new Set([
49
+ "additionalInstructions",
50
+ "durabilityId",
51
+ "eventPersistence",
52
+ "instructions",
53
+ "terminalReceiptRetention",
54
+ "tools",
55
+ ]);
56
+ const lifecycles = new WeakMap();
57
+
58
+ /** @internal Binds the package-owned module to the public Cloudflare namespace. */
59
+ export function bindAgent(module, hostAgent = HostAgent) {
60
+ return Object.freeze({
61
+ bootstrapPlan: async (input) => {
62
+ await initializeBrowserEngine({ module });
63
+ return JSON.parse(managedBootstrapPlan(input));
64
+ },
65
+ pruneDurableReceipts: (owner, options) => pruneDurableReceipts(module, owner, options),
66
+ create: (owner, options) => create(module, owner, options, hostAgent),
67
+ createEphemeral: (owner, options) => createEphemeral(module, owner, options),
68
+ destroy,
69
+ exportDurabilityState,
70
+ exportDurabilityHead,
71
+ importDurabilityState: (owner, archive) => importDurabilityState(owner, archive, module),
72
+ route,
73
+ });
74
+ }
75
+
76
+ /** Atomically steers an active Cloudflare Agent turn or starts a new turn. */
77
+ export function route(agent, options) {
78
+ return routePrompt(agent, options);
79
+ }
80
+
81
+ /** Removes the package-owned durable history for one Cloudflare Agent. */
82
+ export function destroy(owner) {
83
+ const context = resolveContext(owner);
84
+ const lifecycle = lifecycles.get(context);
85
+ if (lifecycle?.creating) {
86
+ throw new Error("Cloudflare Agent creation must settle before destroy");
87
+ }
88
+ if (lifecycle?.active !== undefined) {
89
+ throw new Error("Cloudflare Agent shutdown must complete before destroy");
90
+ }
91
+ const storage = context.storage;
92
+ createCloudflareDurabilityStore(storage);
93
+ initializeAgentStorage(storage);
94
+ const stateId = storedStateId(storage) ?? legacyStateId(storage);
95
+ storage.transactionSync(() => {
96
+ if (stateId !== undefined) {
97
+ const retained = storage.sql.exec(
98
+ "SELECT fence FROM nanocodex_durable_owners WHERE state_id = ?",
99
+ stateId,
100
+ ).toArray();
101
+ const fence = durabilityRevision(
102
+ BigInt(durabilityRevision(retained[0]?.fence ?? "0")) + 1n,
103
+ );
104
+ storage.sql.exec(
105
+ `INSERT INTO nanocodex_durable_owners (state_id, owner_id, fence) VALUES (?, ?, ?)
106
+ ON CONFLICT (state_id) DO UPDATE SET owner_id = excluded.owner_id, fence = excluded.fence`,
107
+ stateId,
108
+ `destroy:${globalThis.crypto.randomUUID()}`,
109
+ fence,
110
+ );
111
+ storage.sql.exec(
112
+ "DELETE FROM nanocodex_durable_records WHERE state_id = ?",
113
+ stateId,
114
+ );
115
+ storage.sql.exec(
116
+ "DELETE FROM nanocodex_durable_states WHERE state_id = ?",
117
+ stateId,
118
+ );
119
+ }
120
+ storage.sql.exec("DELETE FROM nanocodex_cloudflare_subagents");
121
+ clearCloudflareEventSocket(context);
122
+ });
123
+ }
124
+
125
+ /** Fences and exports this inactive Cloudflare Agent's provider-neutral state. */
126
+ export async function exportDurabilityState(owner, request, headOnly = false) {
127
+ const context = reserveInactiveLifecycle(owner, "exporting durability state");
128
+ try {
129
+ const storage = context.storage;
130
+ const durability = createCloudflareDurabilityStore(storage);
131
+ initializeAgentStorage(storage);
132
+ const stateId = storedStateId(storage) ?? legacyStateId(storage);
133
+ if (stateId === undefined) {
134
+ throw new Error("Cloudflare Agent has no durability state to export");
135
+ }
136
+ return request === undefined
137
+ ? await exportPortableState(durability, stateId, { headOnly })
138
+ : await exportPortableStatePage(durability, stateId, request);
139
+ } finally {
140
+ lifecycleFor(context).creating = false;
141
+ }
142
+ }
143
+
144
+ /** Internal managed cutover: records are transferred through its bounded archive. */
145
+ export function exportDurabilityHead(owner) { return exportDurabilityState(owner, undefined, true); }
146
+
147
+ /** Imports provider-neutral state into a pristine Cloudflare Agent owner. */
148
+ export async function importDurabilityState(owner, archive, module) {
149
+ const context = reserveInactiveLifecycle(owner, "importing durability state");
150
+ try {
151
+ const storage = context.storage;
152
+ const durability = createCloudflareDurabilityStore(storage);
153
+ initializeAgentStorage(storage);
154
+ const validationStateId = typeof archive?.stateId === "string" && archive.stateId
155
+ ? archive.stateId
156
+ : "nanocodex-invalid-import";
157
+ const validationStore = createMemoryDurabilityStore(validationStateId);
158
+ const validated = await importPortableState(validationStore, archive);
159
+ if (module !== undefined) {
160
+ const routeHost = {};
161
+ const route = (await loadDurabilityRuntime()).own(
162
+ routeHost,
163
+ validationStore,
164
+ validationStateId,
165
+ );
166
+ try {
167
+ installHostBridge();
168
+ await initializeBrowserEngine({ module });
169
+ // Opening the Rust durability session validates the complete canonical
170
+ // state. Pruning happens only in this throwaway memory copy.
171
+ await pruneWasmDurableReceipts(route.id, validationStateId, 4_096);
172
+ } finally {
173
+ route.abandon();
174
+ }
175
+ }
176
+ const retainedSessionId = storedSessionId(storage);
177
+ const retainedStateId = storedStateId(storage);
178
+ if (retainedSessionId !== undefined || retainedStateId !== undefined) {
179
+ if (retainedSessionId !== undefined
180
+ && retainedStateId === archive?.stateId
181
+ && archive?.format === "nanocodex-durability-state-v2") {
182
+ const retained = await durability.load(retainedStateId);
183
+ if (retained.revision === validated.revision
184
+ && retained.payload === validated.payload) {
185
+ return retained;
186
+ }
187
+ }
188
+ throw new Error("Cloudflare Agent durability import requires a pristine Durable Object");
189
+ }
190
+ const sessionId = uuidV7();
191
+ // Publish identity and the imported head together. Records staged by a
192
+ // bounded host transfer survive rollback and can be reused on retry.
193
+ return storage.transactionSync(() => {
194
+ const imported = durability.importState(archive.stateId, validated, { records: archive.records });
195
+ storage.sql.exec(
196
+ "INSERT INTO nanocodex_cloudflare_agent (singleton, session_id) VALUES (1, ?)", sessionId,
197
+ );
198
+ storage.sql.exec(
199
+ "INSERT INTO nanocodex_cloudflare_durability (singleton, state_id) VALUES (1, ?)", archive.stateId,
200
+ );
201
+ return imported;
202
+ });
203
+ } finally {
204
+ lifecycleFor(context).creating = false;
205
+ }
206
+ }
207
+
208
+ function reserveInactiveLifecycle(owner, operation) {
209
+ const context = resolveContext(owner);
210
+ const lifecycle = lifecycleFor(context);
211
+ if (lifecycle.creating) {
212
+ throw new Error("Cloudflare Agent lifecycle operation is already in progress");
213
+ }
214
+ if (lifecycle.active !== undefined) {
215
+ throw new Error(`Cloudflare Agent shutdown must complete before ${operation}`);
216
+ }
217
+ lifecycle.creating = true;
218
+ return context;
219
+ }
220
+
221
+ /** Prunes old terminal receipts before constructing the full Agent runtime. */
222
+ export async function pruneDurableReceipts(module, owner, options = {}) {
223
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
224
+ throw new TypeError("Cloudflare durability receipt-pruning options must be an object");
225
+ }
226
+ const terminalReceiptRetention = options.terminalReceiptRetention ?? 512;
227
+ if (!Number.isSafeInteger(terminalReceiptRetention)
228
+ || terminalReceiptRetention < 0
229
+ || terminalReceiptRetention > 4_096) {
230
+ throw new TypeError("terminalReceiptRetention must be an integer from 0 through 4096");
231
+ }
232
+ const context = resolveContext(owner);
233
+ const lifecycle = lifecycleFor(context);
234
+ if (lifecycle.creating) {
235
+ throw new Error("Cloudflare Agent lifecycle operation is already in progress");
236
+ }
237
+ if (lifecycle.active !== undefined) {
238
+ throw new Error("Cloudflare Agent shutdown must complete before pruning durability receipts");
239
+ }
240
+ lifecycle.creating = true;
241
+ try {
242
+ const storage = context.storage;
243
+ const durability = createCloudflareDurabilityStore(storage);
244
+ initializeAgentStorage(storage);
245
+ const stateId = storedStateId(storage) ?? legacyStateId(storage);
246
+ if (stateId === undefined) return;
247
+ const routeHost = {};
248
+ const route = (await loadDurabilityRuntime()).own(
249
+ routeHost,
250
+ durability,
251
+ stateId,
252
+ );
253
+ try {
254
+ installHostBridge();
255
+ await initializeBrowserEngine({ module });
256
+ await pruneWasmDurableReceipts(route.id, stateId, terminalReceiptRetention);
257
+ } finally {
258
+ route.abandon();
259
+ }
260
+ } finally {
261
+ lifecycle.creating = false;
262
+ }
263
+ }
264
+
265
+ /** @internal Creates one Agent with an explicitly supplied package module. */
266
+ export async function create(module, owner, options = {}, hostAgent = HostAgent) {
267
+ const resolved = resolveOwner(owner);
268
+ const lifecycle = lifecycleFor(resolved.context);
269
+ if (lifecycle.creating) {
270
+ throw new Error("Cloudflare Agent creation is already in progress for this Durable Object");
271
+ }
272
+ if (lifecycle.active !== undefined) {
273
+ throw new Error("Cloudflare Agent shutdown must complete before create");
274
+ }
275
+ lifecycle.creating = true;
276
+ try {
277
+ return await createOwned(module, resolved, options, hostAgent, lifecycle);
278
+ } finally {
279
+ lifecycle.creating = false;
280
+ }
281
+ }
282
+
283
+ async function createOwned(module, resolved, options, hostAgent, lifecycle) {
284
+ const { context, egress, subject } = resolved;
285
+ const configured = applicationOptions(options);
286
+ const {
287
+ durabilityId,
288
+ eventPersistence = "durable",
289
+ [INTERNAL_RUNTIME]: internalRuntime,
290
+ [INTERNAL_CONFIGURATION]: internalConfiguration,
291
+ ...agentOptions
292
+ } = configured;
293
+ if (internalRuntime !== undefined
294
+ && (!internalRuntime || typeof internalRuntime !== "object" || Array.isArray(internalRuntime))) {
295
+ throw new TypeError("Cloudflare Agent internal runtime options must be an object");
296
+ }
297
+ if (internalRuntime?.subagentLifecycle !== undefined
298
+ && typeof internalRuntime.subagentLifecycle !== "function") {
299
+ throw new TypeError("Cloudflare Agent subagent lifecycle hook must be a function");
300
+ }
301
+ if (internalRuntime?.waitForPreconnect !== undefined
302
+ && typeof internalRuntime.waitForPreconnect !== "boolean") {
303
+ throw new TypeError("Cloudflare Agent internal waitForPreconnect must be a boolean");
304
+ }
305
+ validateInternalConfiguration(internalConfiguration);
306
+ const eventSocket = eventPersistence === "durable"
307
+ ? createCloudflareEventSocket(context)
308
+ : undefined;
309
+ if (eventPersistence === "caller") clearCloudflareEventSocket(context);
310
+ const durability = createCloudflareDurabilityStore(context.storage);
311
+ const { sessionId, stateId } = durableIdentity(context.storage, durabilityId);
312
+ const endpoint = cloudflareEgress({
313
+ binding: scopeCloudflareEgress(egress, subject),
314
+ });
315
+ const startup = deferred();
316
+ const transport = Transport.hostManaged({
317
+ ...endpoint,
318
+ websocketPreconnect: true,
319
+ async createWebSocket(url, id, request) {
320
+ try {
321
+ const opened = await endpoint.createWebSocket(url, id, request);
322
+ if (request.authorization === "preconnect") startup.resolve();
323
+ return { ...opened, socket: responseControlsSocket(opened.socket, internalRuntime?.responseControls) };
324
+ } catch (error) {
325
+ if (request.authorization === "preconnect") startup.reject(error);
326
+ throw error;
327
+ }
328
+ },
329
+ });
330
+
331
+ const sessionReservation = prepareCloudflareAgentSession(sessionId, subject);
332
+ const subagentSessions = cloudflareSubagentSessions(
333
+ context.storage,
334
+ sessionReservation,
335
+ internalRuntime?.subagentLifecycle,
336
+ );
337
+ let agent;
338
+ let watcher;
339
+ let unwatch;
340
+ try {
341
+ agent = await hostAgent.create({
342
+ ...agentOptions,
343
+ ...(internalConfiguration === undefined ? {} : {
344
+ model: internalConfiguration.model,
345
+ thinking: internalConfiguration.thinking,
346
+ reasoningMode: internalConfiguration.reasoning_mode,
347
+ fastMode: internalConfiguration.fast_mode,
348
+ }),
349
+ module,
350
+ toolMode: internalRuntime?.toolMode ?? "direct",
351
+ codeEvaluator: internalRuntime?.codeEvaluator,
352
+ [Symbol.for("nanocodex.browser.internalRuntime")]: {
353
+ toolProviders: internalRuntime?.toolProviders,
354
+ subagentsEnabled: internalRuntime?.subagentsEnabled,
355
+ subagentMaxConcurrency: internalRuntime?.subagentMaxConcurrency,
356
+ subagentSessions,
357
+ [CLOUDFLARE_SESSION_RESERVATION]: sessionReservation,
358
+ },
359
+ transport,
360
+ sessionId,
361
+ durability,
362
+ durabilityId: stateId,
363
+ });
364
+ // Managed voice needs the durable session before the separate Responses
365
+ // relay is ready. Its preconnection remains owned by the host and a later
366
+ // text turn consumes it through the same credential-checked transport.
367
+ if (internalRuntime?.waitForPreconnect !== false) {
368
+ await withTimeout(
369
+ startup.promise,
370
+ STARTUP_TIMEOUT_MS,
371
+ "Cloudflare Agent EGRESS startup validation timed out",
372
+ );
373
+ }
374
+
375
+ if (eventSocket !== undefined) {
376
+ watcher = agent.events.watch();
377
+ unwatch = watcher.onEvent((event) => {
378
+ try {
379
+ eventSocket.publish(event);
380
+ } catch (error) {
381
+ unwatch?.();
382
+ eventSocket.fail(error);
383
+ console.error("Nanocodex Cloudflare event projection failed", error);
384
+ }
385
+ });
386
+ }
387
+ const exposed = agent.extend((owned) => ({
388
+ events: {
389
+ connect: (request) => eventSocket?.connect(request) ?? Response.json(
390
+ { error: "event_persistence_caller_owned" },
391
+ { status: 409 },
392
+ ),
393
+ },
394
+ turn: {
395
+ ...owned.turn,
396
+ route: (options) => routePrompt(owned, options),
397
+ },
398
+ }));
399
+ const active = {};
400
+ lifecycle.active = active;
401
+ observeAgentRelease(exposed, () => {
402
+ if (lifecycle.active === active) lifecycle.active = undefined;
403
+ });
404
+ commitCloudflareAgentSession(sessionReservation);
405
+ return exposed;
406
+ } catch (error) {
407
+ const cleanupErrors = [];
408
+ try { unwatch?.(); } catch (cleanupError) { cleanupErrors.push(cleanupError); }
409
+ try { watcher?.off(); } catch (cleanupError) { cleanupErrors.push(cleanupError); }
410
+ if (agent) {
411
+ try { await agent.session.shutdown(); } catch (cleanupError) { cleanupErrors.push(cleanupError); }
412
+ }
413
+ releaseAgentSession(sessionReservation);
414
+ if (cleanupErrors.length > 0) {
415
+ const cause = new AggregateError(
416
+ [error, ...cleanupErrors],
417
+ "Cloudflare Agent creation and resource rollback both failed",
418
+ );
419
+ throw Object.assign(
420
+ new Error(
421
+ `Cloudflare Agent creation failed and rollback requires reopen: ${errorMessage(error)}`,
422
+ { cause },
423
+ ),
424
+ { code: "reopen_required" },
425
+ );
426
+ }
427
+ throw error;
428
+ }
429
+ }
430
+
431
+ function lifecycleFor(context) {
432
+ let lifecycle = lifecycles.get(context);
433
+ if (lifecycle === undefined) {
434
+ lifecycle = { active: undefined, creating: false };
435
+ lifecycles.set(context, lifecycle);
436
+ }
437
+ return lifecycle;
438
+ }
439
+
440
+ function errorMessage(error) {
441
+ return error instanceof Error ? error.message : String(error);
442
+ }
443
+
444
+ /** @internal Creates one non-durable Agent in the current Cloudflare isolate. */
445
+ export async function createEphemeral(module, owner, options = {}) {
446
+ const { egress, subject } = resolveOwner(owner);
447
+ const agentOptions = ephemeralApplicationOptions(options);
448
+ const endpoint = cloudflareEgress({
449
+ binding: scopeCloudflareEgress(egress, subject),
450
+ });
451
+ const startup = deferred();
452
+ const transport = Transport.hostManaged({
453
+ ...endpoint,
454
+ websocketPreconnect: true,
455
+ async createWebSocket(url, id, request) {
456
+ try {
457
+ const opened = await endpoint.createWebSocket(url, id, request);
458
+ if (request.authorization === "preconnect") startup.resolve();
459
+ return opened;
460
+ } catch (error) {
461
+ if (request.authorization === "preconnect") startup.reject(error);
462
+ throw error;
463
+ }
464
+ },
465
+ });
466
+
467
+ let agent;
468
+ try {
469
+ agent = await HostAgent.create({
470
+ ...agentOptions,
471
+ module,
472
+ toolMode: "direct",
473
+ transport,
474
+ });
475
+ await withTimeout(
476
+ startup.promise,
477
+ STARTUP_TIMEOUT_MS,
478
+ "Cloudflare ephemeral Agent EGRESS startup validation timed out",
479
+ );
480
+ return agent;
481
+ } catch (error) {
482
+ if (agent) await agent.session.shutdown().catch(() => {});
483
+ throw error;
484
+ }
485
+ }
486
+
487
+ function resolveOwner(owner) {
488
+ const context = resolveContext(owner);
489
+ const egress = owner.env?.NANOCODEX;
490
+ if (!egress || typeof egress.fetch !== "function") {
491
+ throw new TypeError(
492
+ "Cloudflare Agent.create requires the private owner.env.NANOCODEX Service Binding",
493
+ );
494
+ }
495
+ const subject = context.id?.toString?.();
496
+ if (typeof subject !== "string" || !subject) {
497
+ throw new TypeError("Cloudflare Agent.create requires owner.ctx.id");
498
+ }
499
+ return { context, egress, subject };
500
+ }
501
+
502
+ function resolveContext(owner) {
503
+ if (!owner || (typeof owner !== "object" && typeof owner !== "function")) {
504
+ throw new TypeError("Cloudflare Agent.create requires a Durable Object instance");
505
+ }
506
+ const context = owner.ctx;
507
+ if (!context || typeof context !== "object") {
508
+ throw new TypeError("Cloudflare Agent.create requires owner.ctx");
509
+ }
510
+ return context;
511
+ }
512
+
513
+ function applicationOptions(options) {
514
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
515
+ throw new TypeError("Cloudflare Agent.create options must be an object");
516
+ }
517
+ for (const name of Object.keys(options)) {
518
+ if (!APPLICATION_OPTIONS.has(name)) {
519
+ throw new TypeError(
520
+ `Cloudflare Agent.create does not accept ${name}; only durabilityId, eventPersistence, instructions, additionalInstructions, terminalReceiptRetention, and tools are configurable`,
521
+ );
522
+ }
523
+ }
524
+ if (options.eventPersistence !== undefined
525
+ && options.eventPersistence !== "durable"
526
+ && options.eventPersistence !== "caller") {
527
+ throw new TypeError(
528
+ "Cloudflare Agent.create eventPersistence must be durable or caller",
529
+ );
530
+ }
531
+ if (options.terminalReceiptRetention !== undefined
532
+ && (!Number.isSafeInteger(options.terminalReceiptRetention)
533
+ || options.terminalReceiptRetention < 0
534
+ || options.terminalReceiptRetention > 4_096)) {
535
+ throw new TypeError(
536
+ "Cloudflare Agent.create terminalReceiptRetention must be an integer from 0 through 4096",
537
+ );
538
+ }
539
+ return options;
540
+ }
541
+
542
+ function validateInternalConfiguration(configuration) {
543
+ if (configuration === undefined) return;
544
+ if (!configuration || typeof configuration !== "object" || Array.isArray(configuration)
545
+ || Reflect.ownKeys(configuration).some((key) => ![
546
+ "model",
547
+ "thinking",
548
+ "reasoning_mode",
549
+ "fast_mode",
550
+ ].includes(key))
551
+ || !["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-6-astra"]
552
+ .includes(configuration.model)
553
+ || !["none", "low", "medium", "high", "xhigh", "max"].includes(configuration.thinking)
554
+ || !["standard", "pro"].includes(configuration.reasoning_mode)
555
+ || typeof configuration.fast_mode !== "boolean"
556
+ || (configuration.model === "gpt-6-astra" && configuration.thinking === "none")) {
557
+ throw new TypeError("Cloudflare Agent internal configuration is invalid");
558
+ }
559
+ }
560
+
561
+ function ephemeralApplicationOptions(options) {
562
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
563
+ throw new TypeError("Cloudflare Agent.createEphemeral options must be an object");
564
+ }
565
+ for (const name of Object.keys(options)) {
566
+ if (!EPHEMERAL_APPLICATION_OPTIONS.has(name)) {
567
+ throw new TypeError(
568
+ `Cloudflare Agent.createEphemeral does not accept ${name}; transport and runtime policy are owned by the adapter`,
569
+ );
570
+ }
571
+ }
572
+ return options;
573
+ }
574
+
575
+ function durableIdentity(storage, configuredStateId) {
576
+ initializeAgentStorage(storage);
577
+ if (configuredStateId !== undefined
578
+ && (typeof configuredStateId !== "string" || !configuredStateId.trim())) {
579
+ throw new TypeError("Cloudflare Agent durabilityId must be a non-empty string");
580
+ }
581
+ const previousSessionId = storedSessionId(storage);
582
+ const previousStateId = storedStateId(storage);
583
+ if (previousStateId !== undefined
584
+ && configuredStateId !== undefined
585
+ && previousStateId !== configuredStateId) {
586
+ throw new Error("Cloudflare Agent durabilityId does not match the retained state identity");
587
+ }
588
+ const generated = previousSessionId ?? uuidV7();
589
+ const generatedStateId = previousStateId
590
+ ?? configuredStateId
591
+ ?? (previousSessionId === undefined ? generated : `cloudflare:${previousSessionId}`);
592
+ storage.transactionSync(() => {
593
+ storage.sql.exec(
594
+ "INSERT OR IGNORE INTO nanocodex_cloudflare_agent (singleton, session_id) VALUES (1, ?)",
595
+ generated,
596
+ );
597
+ storage.sql.exec(
598
+ "INSERT OR IGNORE INTO nanocodex_cloudflare_durability (singleton, state_id) VALUES (1, ?)",
599
+ generatedStateId,
600
+ );
601
+ });
602
+ const sessionId = storedSessionId(storage);
603
+ const stateId = storedStateId(storage);
604
+ if (typeof sessionId !== "string" || !sessionId) {
605
+ throw new Error("Cloudflare Agent failed to persist its runtime session ID");
606
+ }
607
+ if (typeof stateId !== "string" || !stateId) {
608
+ throw new Error("Cloudflare Agent failed to persist its durability state ID");
609
+ }
610
+ return { sessionId, stateId };
611
+ }
612
+
613
+ function initializeAgentStorage(storage) {
614
+ storage.sql.exec(`
615
+ CREATE TABLE IF NOT EXISTS nanocodex_cloudflare_agent (
616
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
617
+ session_id TEXT NOT NULL UNIQUE
618
+ )
619
+ `);
620
+ storage.sql.exec(`
621
+ CREATE TABLE IF NOT EXISTS nanocodex_cloudflare_durability (
622
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
623
+ state_id TEXT NOT NULL UNIQUE
624
+ )
625
+ `);
626
+ storage.sql.exec(`
627
+ CREATE TABLE IF NOT EXISTS nanocodex_cloudflare_subagents (
628
+ session_id TEXT PRIMARY KEY,
629
+ agent_id TEXT NOT NULL UNIQUE,
630
+ descriptor_json TEXT NOT NULL,
631
+ host_context_ref TEXT
632
+ )
633
+ `);
634
+ const subagentColumns = storage.sql.exec(
635
+ "PRAGMA table_info('nanocodex_cloudflare_subagents')",
636
+ ).toArray();
637
+ if (!subagentColumns.some(({ name }) => name === "host_context_ref")) {
638
+ storage.sql.exec(
639
+ "ALTER TABLE nanocodex_cloudflare_subagents ADD COLUMN host_context_ref TEXT",
640
+ );
641
+ }
642
+ }
643
+
644
+ function cloudflareSubagentSessions(storage, reservation, lifecycle) {
645
+ const restoredHostContextRefs = new Map();
646
+ return Object.freeze({
647
+ restore() {
648
+ const restored = storage.sql.exec(
649
+ "SELECT descriptor_json, host_context_ref FROM nanocodex_cloudflare_subagents",
650
+ ).toArray().map(({ descriptor_json, host_context_ref }) => {
651
+ const descriptor = Object.freeze(JSON.parse(descriptor_json));
652
+ restoredHostContextRefs.set(
653
+ descriptor.sessionId,
654
+ host_context_ref === null ? undefined : host_context_ref,
655
+ );
656
+ return descriptor;
657
+ });
658
+ return Object.freeze(restored);
659
+ },
660
+ hostContextRef(sessionId) {
661
+ return restoredHostContextRefs.get(sessionId);
662
+ },
663
+ bind(sessionId, descriptor, hostContextRef) {
664
+ if (!mayBindCloudflareSubagentSession(reservation)) return;
665
+ if (hostContextRef !== undefined
666
+ && (typeof hostContextRef !== "string" || hostContextRef.length === 0)) {
667
+ throw new TypeError("subagent host context ref must be a non-empty string when supplied");
668
+ }
669
+ const type = restoredHostContextRefs.has(sessionId) ? "reconstruct" : "bind";
670
+ storage.transactionSync(() => {
671
+ storage.sql.exec(
672
+ `INSERT INTO nanocodex_cloudflare_subagents
673
+ (session_id, agent_id, descriptor_json, host_context_ref) VALUES (?, ?, ?, ?)
674
+ ON CONFLICT (session_id) DO UPDATE SET
675
+ agent_id = excluded.agent_id,
676
+ descriptor_json = excluded.descriptor_json,
677
+ host_context_ref = excluded.host_context_ref`,
678
+ sessionId,
679
+ descriptor.agentId,
680
+ JSON.stringify(descriptor),
681
+ hostContextRef ?? null,
682
+ );
683
+ notifySubagentLifecycle(lifecycle, {
684
+ type,
685
+ rootSessionId: reservation.sessionId,
686
+ sessionId,
687
+ descriptor,
688
+ hostContextRef,
689
+ });
690
+ });
691
+ restoredHostContextRefs.delete(sessionId);
692
+ },
693
+ release(sessionId, hostContextRef) {
694
+ if (!mayReleaseCloudflareSubagentSession(reservation)) return;
695
+ storage.transactionSync(() => {
696
+ const retained = storage.sql.exec(
697
+ `SELECT 1 AS retained FROM nanocodex_cloudflare_subagents
698
+ WHERE session_id = ? AND host_context_ref IS ?`,
699
+ sessionId,
700
+ hostContextRef ?? null,
701
+ ).toArray();
702
+ if (retained.length === 0) return;
703
+ notifySubagentLifecycle(lifecycle, {
704
+ type: "release",
705
+ rootSessionId: reservation.sessionId,
706
+ sessionId,
707
+ hostContextRef,
708
+ });
709
+ storage.sql.exec(
710
+ `DELETE FROM nanocodex_cloudflare_subagents
711
+ WHERE session_id = ? AND host_context_ref IS ?`,
712
+ sessionId,
713
+ hostContextRef ?? null,
714
+ );
715
+ });
716
+ },
717
+ });
718
+ }
719
+
720
+ function notifySubagentLifecycle(lifecycle, event) {
721
+ if (lifecycle === undefined) return;
722
+ lifecycle(Object.freeze(event));
723
+ }
724
+
725
+ function storedSessionId(storage) {
726
+ return storage.sql.exec(
727
+ "SELECT session_id FROM nanocodex_cloudflare_agent WHERE singleton = 1",
728
+ ).toArray()[0]?.session_id;
729
+ }
730
+
731
+ function storedStateId(storage) {
732
+ return storage.sql.exec(
733
+ "SELECT state_id FROM nanocodex_cloudflare_durability WHERE singleton = 1",
734
+ ).toArray()[0]?.state_id;
735
+ }
736
+
737
+ function legacyStateId(storage) {
738
+ const sessionId = storedSessionId(storage);
739
+ return sessionId === undefined ? undefined : `cloudflare:${sessionId}`;
740
+ }
741
+
742
+ function uuidV7() {
743
+ if (typeof globalThis.crypto?.getRandomValues !== "function") {
744
+ throw new Error("Cloudflare Agent requires crypto.getRandomValues()");
745
+ }
746
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
747
+ let timestamp = Date.now();
748
+ for (let index = 5; index >= 0; index -= 1) {
749
+ bytes[index] = timestamp % 256;
750
+ timestamp = Math.floor(timestamp / 256);
751
+ }
752
+ bytes[6] = (bytes[6] & 0x0f) | 0x70;
753
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
754
+ const encoded = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));
755
+ return `${encoded.slice(0, 4).join("")}-${encoded.slice(4, 6).join("")}-${encoded.slice(6, 8).join("")}-${encoded.slice(8, 10).join("")}-${encoded.slice(10).join("")}`;
756
+ }
757
+
758
+ function deferred() {
759
+ let resolve;
760
+ let reject;
761
+ const promise = new Promise((onResolve, onReject) => {
762
+ resolve = onResolve;
763
+ reject = onReject;
764
+ });
765
+ // Preconnect may fail before HostAgent.create returns and installs the
766
+ // startup waiter. Mark the original promise handled without changing what
767
+ // the later await observes.
768
+ void promise.catch(() => {});
769
+ return { promise, resolve, reject };
770
+ }
771
+
772
+ async function withTimeout(promise, timeoutMs, message) {
773
+ let timer;
774
+ try {
775
+ await Promise.race([
776
+ promise,
777
+ new Promise((_, reject) => {
778
+ timer = setTimeout(() => reject(new Error(message)), timeoutMs);
779
+ }),
780
+ ]);
781
+ } finally {
782
+ clearTimeout(timer);
783
+ }
784
+ }