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,9 @@
1
+ export declare class ManagedError extends Error {
2
+ readonly code: string;
3
+ readonly status: number | undefined;
4
+ constructor(
5
+ code: string,
6
+ message: string,
7
+ options?: { status?: number | undefined; cause?: unknown },
8
+ );
9
+ }
@@ -0,0 +1,8 @@
1
+ export class ManagedError extends Error {
2
+ constructor(code, message, options = {}) {
3
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
4
+ this.name = "ManagedError";
5
+ this.code = code;
6
+ this.status = options.status;
7
+ }
8
+ }
@@ -0,0 +1,244 @@
1
+ # Managed Nanocodex agents
2
+
3
+ `nanocodex/managed` is the administration and extended control-plane client for
4
+ account-owned Nanocodex agents. Application turns normally use
5
+ `Agent.create({ transport: Transport.managed(...), tools })` from
6
+ `nanocodex/node`, `nanocodex/browser`, or `nanocodex/host`, which returns the
7
+ same lifecycle shape as local OpenAI and host-managed transports.
8
+
9
+ In a browser, authentication uses the current origin's HttpOnly account cookie:
10
+
11
+ ```js
12
+ import { Agent } from "nanocodex/managed";
13
+
14
+ const { agent, turn } = await Agent.createAndPrompt({
15
+ idempotencyKey: `run:${job.id}`,
16
+ input: "Inspect the repository and summarize it.",
17
+ });
18
+ const result = await turn.result();
19
+ console.log(result.finalMessage);
20
+ ```
21
+
22
+ `createAndPrompt` sends one client mutation. Its required key identifies both
23
+ the new session and the admitted first turn across retries or a lost response.
24
+ Later turns still use `agent.turn.prompt(...)`.
25
+
26
+ New managed agents may be created with an atomic settings object. Existing
27
+ agents retain their model and reasoning mode after their first accepted turn.
28
+
29
+ ```js
30
+ const astra = await Agent.create({
31
+ settings: {
32
+ model: "gpt-6-astra",
33
+ thinking: "high",
34
+ reasoningMode: "standard",
35
+ fastMode: false,
36
+ },
37
+ });
38
+ ```
39
+
40
+ GPT-6 Astra accepts `low`, `medium`, `high`, `xhigh`, or `max` thinking; it
41
+ rejects `none`. Fast mode is deliberately opt-in and is unavailable for Astra
42
+ when the OpenAI project uses EU data residency.
43
+
44
+ On a server, provide the managed origin and an `ncx_live_...` account API key:
45
+
46
+ ```js
47
+ const agent = await Agent.get(process.env.NANOCODEX_AGENT_ID, {
48
+ baseUrl: "https://nanocodex.example",
49
+ apiKey: process.env.NANOCODEX_API_KEY,
50
+ });
51
+ ```
52
+
53
+ The transport-facing constructor requires an explicit identity and never
54
+ infers creation from a missing ID:
55
+
56
+ ```js
57
+ import { Agent, Transport } from "nanocodex/node";
58
+
59
+ const created = await Agent.create({
60
+ transport: Transport.managed({
61
+ agent: { create: true },
62
+ baseUrl: "https://nanocodex.example",
63
+ apiKey: process.env.NANOCODEX_API_KEY,
64
+ }),
65
+ });
66
+ const existing = await Agent.create({
67
+ transport: Transport.managed({
68
+ agent: { id: process.env.NANOCODEX_AGENT_ID },
69
+ baseUrl: "https://nanocodex.example",
70
+ apiKey: process.env.NANOCODEX_API_KEY,
71
+ }),
72
+ });
73
+ await existing.session.shutdown(); // closes the client; never deletes the Agent
74
+ ```
75
+
76
+ The same account client can search all completed managed conversations without
77
+ opening an agent turn:
78
+
79
+ ```js
80
+ const found = await Agent.findSessions(
81
+ { query: "what did we decide about memory?", limit: 8 },
82
+ { baseUrl: process.env.NANOCODEX_MANAGED_URL, apiKey: process.env.NANOCODEX_API_KEY },
83
+ );
84
+ const session = await Agent.readSession(
85
+ {
86
+ session_id: found.results[0].session_id,
87
+ turn_ids: [found.results[0].turn_id],
88
+ },
89
+ { baseUrl: process.env.NANOCODEX_MANAGED_URL, apiKey: process.env.NANOCODEX_API_KEY },
90
+ );
91
+ ```
92
+
93
+ Both methods derive the account scope from the cookie or API key; no scope or user
94
+ identifier is accepted from the caller.
95
+
96
+ Hosted durable memory is account-owned and independent from session history. The
97
+ memory panel can list records and compare-and-swap delete one current key:
98
+
99
+ ```js
100
+ const memories = await Agent.listMemories({
101
+ baseUrl: process.env.NANOCODEX_MANAGED_URL,
102
+ apiKey: process.env.NANOCODEX_API_KEY,
103
+ });
104
+ await Agent.deleteMemory(memories[0].key, {
105
+ baseUrl: process.env.NANOCODEX_MANAGED_URL,
106
+ apiKey: process.env.NANOCODEX_API_KEY,
107
+ });
108
+ ```
109
+
110
+ Managed agents access this same hosted store through their `memory` tool. It is
111
+ never mirrored into a browser, TUI, or other local persistence layer.
112
+
113
+ Account memory uses the same derived organization scope and supports scan, read,
114
+ put, and delete operations. Scan before writing so the service can reject
115
+ duplicates, and retain returned `{ id, version }` keys for compare-and-swap
116
+ updates:
117
+
118
+ ```js
119
+ const scanned = await Agent.memory(
120
+ { operation: "scan", query: "production deploy schedule" },
121
+ { baseUrl: process.env.NANOCODEX_MANAGED_URL, apiKey: process.env.NANOCODEX_API_KEY },
122
+ );
123
+ const stored = await Agent.memory(
124
+ { operation: "put", content: "Production deploys happen on Tuesdays." },
125
+ { baseUrl: process.env.NANOCODEX_MANAGED_URL, apiKey: process.env.NANOCODEX_API_KEY },
126
+ );
127
+ ```
128
+
129
+ Browser account owners can read and rename their organization:
130
+
131
+ ```js
132
+ const organization = await Agent.getOrganization();
133
+ await Agent.updateOrganization({ name: `${organization.name ?? "Personal"} workspace` });
134
+ ```
135
+
136
+ Memory accepts either account-cookie or API-key authentication. Organization
137
+ metadata and mutation remain subject to the server's principal and owner policy;
138
+ the client sends supplied credentials without weakening that policy.
139
+
140
+ `Agent.list()` returns agent handles, `agent.state()` reads current state, and
141
+ `agent.delete()` removes the agent and its retained state. `agent.events.watch`
142
+ is an async iterator over durable events. Pass its last decimal `cursor` to a
143
+ later watcher to resume strictly after the acknowledged event. Network endings
144
+ reconnect automatically from that cursor. Watchers and independently awaitable
145
+ turn results on one agent handle share one replayable event connection; each
146
+ subscriber keeps its own cursor, so consuming one never steals another's events.
147
+ Rapid `turn.steer()` calls on one turn handle are sent in invocation order.
148
+ `turn.cancel()` bypasses pending steering requests, so Stop can interrupt them.
149
+ Pass `cursor: "latest"` to attach atomically at the durable head without
150
+ replaying retained history; a history page can then hydrate independently.
151
+
152
+ Returning browser clients may use `Agent.open(id)` to construct a retained
153
+ handle without a preliminary state request. The first operation on that handle
154
+ still verifies account ownership at the managed service boundary. Use
155
+ `Agent.get(id)` when an eager existence check is part of the caller's workflow.
156
+
157
+ The managed API never accepts model-provider credentials, egress bindings,
158
+ runtime environment objects, credential grants, or arbitrary request headers.
159
+
160
+ ## Cron triggers
161
+
162
+ Schedules belong to an existing managed agent and run without an open client.
163
+ Use a stable trigger ID to create or replace a schedule idempotently:
164
+
165
+ ```js
166
+ const agent = await Agent.get(agentId, { baseUrl, apiKey });
167
+ const morning = {
168
+ cron: "0 7 * * MON-FRI",
169
+ timezone: "Europe/Athens",
170
+ input: "Review my running agents and summarize anything that needs attention.",
171
+ };
172
+ await agent.triggers.put("morning-review", morning);
173
+ await agent.triggers.list();
174
+ await agent.triggers.get("morning-review");
175
+ await agent.triggers.put("morning-review", { ...morning, enabled: false }); // pause
176
+ await agent.triggers.put("morning-review", morning); // resume
177
+ await agent.triggers.delete("morning-review");
178
+ ```
179
+
180
+ | Method | Route | Result |
181
+ | --- | --- | --- |
182
+ | GET | `/v1/agents/:agent/triggers` | `{ data: [...] }` |
183
+ | GET | `/v1/agents/:agent/triggers/:id` | Trigger or 404 |
184
+ | PUT | `/v1/agents/:agent/triggers/:id` | Create (201) or replace (200) |
185
+ | DELETE | `/v1/agents/:agent/triggers/:id` | Idempotent deletion (204) |
186
+
187
+ The managed-agent web composer also has a **Schedules** button. It opens the
188
+ same account-authenticated API: create or edit a prompt and cron expression,
189
+ choose an IANA time zone, inspect the next dispatch time, pause/resume, or
190
+ delete a schedule. The last-dispatched time is not a completion receipt; read
191
+ the conversation for the result. The ephemeral homepage agent has no schedules.
192
+
193
+ PUT takes `{ cron, input, timezone?, enabled?, session_mode? }`. Expressions have five fields
194
+ (minute, hour, day of month, month, day of week), supporting numeric values,
195
+ lists, ranges, steps, and month/day names. The time zone defaults to UTC and
196
+ accepts IANA names. Local times follow daylight saving transitions. Seconds,
197
+ macros, and random `H` fields are rejected. Inputs are text up to 64 KiB;
198
+ there can be at most 32 triggers per agent. IDs use 1–64 letters, digits,
199
+ underscores, or hyphens. PUT is a full replacement; an identical retry preserves
200
+ the next occurrence. A changed configuration starts from the next matching time.
201
+
202
+ `session_mode: "new"` (the default for new configurations) creates a fresh managed
203
+ session for every occurrence. It copies the source agent's model settings at
204
+ dispatch time, but no conversation history or schedules. Account permissions,
205
+ connectors, and account memory still belong to the same account. Fresh sessions
206
+ run independently even when the source conversation is busy, and appear in the
207
+ normal agent list. Choose **New session each time** in the Schedules dialog.
208
+
209
+ `session_mode: "continue"` submits a turn to the existing conversation, retaining
210
+ its history. Choose **Continue this conversation** in the dialog. Schedules saved
211
+ before modes were introduced retain this behavior. Omitting the mode when
212
+ updating an existing schedule preserves its mode, including for older clients.
213
+ Set `session_mode` explicitly to switch modes.
214
+
215
+ Durable Object alarms dispatch occurrences. Continued turns advance the schedule
216
+ atomically with turn admission. Fresh runs use a durable outbox and deterministic
217
+ session/turn IDs: delivery retries reuse the same session without duplicating
218
+ its turn. Only one undelivered occurrence per schedule is retained. Inspect
219
+ `last_turn_id` on `last_agent_id` through the normal turn and event APIs, or use
220
+ **Open run** in the UI. Times are Unix milliseconds; `last_run_at` is the scheduled
221
+ time of the last accepted occurrence, and `next_run_at` is null while paused.
222
+ Last dispatched does not mean the model response has completed.
223
+
224
+ Missed ticks coalesce; they are not replayed individually. In continue mode,
225
+ unfinished work or a failed event stream causes an occurrence to be skipped and
226
+ recorded in `last_skipped_at`. New-session mode does not skip because the source
227
+ is busy. Pausing or deleting prevents future dispatches; a turn already accepted
228
+ or a fresh session already claimed for delivery still completes. Resume does
229
+ not backfill. Deleting the source removes its schedules and pending deliveries;
230
+ sessions already created remain independent conversations.
231
+
232
+ Read requests require `agents:read`; writes require `agents:write`, and PUT also
233
+ requires `tools:use`. The usual ownership and browser-origin checks apply.
234
+ Triggers are account-owned standing instructions with the creator's capability
235
+ scope, and persist after the creating API key or browser session ends. Connect
236
+ grants and multiplayer rooms cannot create schedules. Delete the trigger to
237
+ revoke its standing instruction. Provider credentials are resolved by the usual
238
+ managed execution path and are never stored in trigger definitions or returned
239
+ by these endpoints.
240
+
241
+ Deleting an agent removes its triggers. Portable durability export currently
242
+ returns `409 cron_triggers_present` while any trigger or pending delivery exists: delete
243
+ triggers and let claimed deliveries finish before transfer, then recreate schedules at the destination. This avoids
244
+ silently dropping schedules or running the same schedule on two agents.
@@ -0,0 +1,209 @@
1
+ import { ManagedBrowserVoice } from "../pkg-web/nanocodex.js";
2
+ import { initializeBrowserEngine } from "../browser/engine.mjs";
3
+ import {
4
+ cancelManagedTurn,
5
+ prefetchManagedRealtime,
6
+ routeManagedRealtime,
7
+ startManagedRealtime,
8
+ stopManagedRealtime,
9
+ } from "./internal.mjs";
10
+
11
+ /** @internal Adapts the Rust-owned protocol core to one remote managed Agent. */
12
+ export async function createManagedBrowserVoice(agent, voice, options = {}) {
13
+ await initializeBrowserEngine(options);
14
+ const raw = new ManagedBrowserVoice(voice);
15
+ const voiceSessionId = uuidV7();
16
+ const startOperationId = crypto.randomUUID();
17
+ const stopOperationId = crypto.randomUUID();
18
+ const tailOperationId = crypto.randomUUID();
19
+ const delegationOperations = new Map();
20
+ let startedTurnId;
21
+ let activeTurnId;
22
+ let routePending = false;
23
+ let pendingEvents = [];
24
+ let prefetchTimer;
25
+ const prefetchAbort = new AbortController();
26
+
27
+ function observe(value) {
28
+ if (activeTurnId === undefined || value?.turnId !== activeTurnId) return undefined;
29
+ const effects = raw.agentEvent(JSON.stringify(value.event));
30
+ if (isTerminalAgentEvent(value.event)) {
31
+ if (startedTurnId === activeTurnId) startedTurnId = undefined;
32
+ activeTurnId = undefined;
33
+ }
34
+ return effects;
35
+ }
36
+
37
+ function adoptRoute(routed) {
38
+ if (typeof routed.turn_id !== "string") return [];
39
+ activeTurnId = routed.turn_id;
40
+ if (routed.route === "started") startedTurnId = routed.turn_id;
41
+ const buffered = pendingEvents;
42
+ pendingEvents = [];
43
+ return buffered.map(observe).filter((effects) => effects !== undefined);
44
+ }
45
+
46
+ return {
47
+ configure: (settings) => raw.configure(settings),
48
+ noteTypedInput: () => raw.noteTypedInput(),
49
+ appendSpeech: (text) => raw.appendSpeech(text),
50
+ appendText: (role, text) => raw.appendText(role, text),
51
+ appendContext: (text) => raw.appendContext(text),
52
+ parallelStartup: true,
53
+ async start() {
54
+ const started = await startManagedRealtime(agent, voiceSessionId, startOperationId);
55
+ raw.start(JSON.stringify(started.context));
56
+ },
57
+ callBody(sdp) {
58
+ const envelope = JSON.parse(raw.callBody(sdp, voiceSessionId));
59
+ envelope.managed_agent_id = agent.id;
60
+ return JSON.stringify(envelope);
61
+ },
62
+ completeCall: (body, location) => raw.completeCall(body, location),
63
+ sidebandUrl(callId) {
64
+ const path = raw.sidebandUrl(callId, voiceSessionId);
65
+ const url = new URL(path, globalThis.location?.href ?? "http://localhost");
66
+ url.searchParams.set("managed_agent_id", agent.id);
67
+ return `${url.pathname}${url.search}`;
68
+ },
69
+ sidebandOpened: () => raw.sidebandOpened(),
70
+ sidebandClosed: (connectedMs) => raw.sidebandClosed(connectedMs),
71
+ framesSent: (count) => raw.framesSent(count),
72
+ requiresAgentAdmission: (payload) => raw.requiresAgentAdmission(payload),
73
+ async realtimeMessage(payload) {
74
+ const update = JSON.parse(raw.realtimeMessage(payload));
75
+ if (update.prefetch) {
76
+ clearTimeout(prefetchTimer);
77
+ prefetchTimer = setTimeout(() => {
78
+ void prefetchManagedRealtime(agent, voiceSessionId, update.prefetch.query,
79
+ AbortSignal.any([prefetchAbort.signal, AbortSignal.timeout(10_000)])).catch(() => {});
80
+ }, update.prefetch.debounce_ms);
81
+ }
82
+ if (typeof update.delegation === "string" && update.delegation.trim()) {
83
+ clearTimeout(prefetchTimer);
84
+ const delegationId = managedDelegationId(payload);
85
+ let operationId = delegationId && delegationOperations.get(delegationId);
86
+ if (!operationId) {
87
+ operationId = crypto.randomUUID();
88
+ if (delegationId) delegationOperations.set(delegationId, operationId);
89
+ }
90
+ routePending = true;
91
+ try {
92
+ const bufferedEffects = adoptRoute(await routeManagedRealtime(
93
+ agent,
94
+ voiceSessionId,
95
+ operationId,
96
+ update.delegation,
97
+ ));
98
+ update.effects = mergeVoiceEffects(update.effects, bufferedEffects);
99
+ } finally {
100
+ routePending = false;
101
+ if (activeTurnId === undefined) pendingEvents = [];
102
+ }
103
+ }
104
+ return JSON.stringify(update.effects);
105
+ },
106
+ agentEvent(envelope) {
107
+ const value = typeof envelope === "string" ? JSON.parse(envelope) : envelope;
108
+ if (value?.event?.type === "managed.voice.context") {
109
+ return raw.managedEvent(JSON.stringify(value));
110
+ }
111
+ if (routePending && value?.turnId !== activeTurnId) {
112
+ if (pendingEvents.length >= 256) throw new Error("Voice event backlog is full. Please reconnect.");
113
+ pendingEvents.push(value);
114
+ return undefined;
115
+ }
116
+ return observe(value);
117
+ },
118
+ flush: (finalChunk) => raw.flush(finalChunk),
119
+ async stop() {
120
+ clearTimeout(prefetchTimer);
121
+ prefetchAbort.abort();
122
+ const update = JSON.parse(raw.stop());
123
+ let routeFailure;
124
+ if (typeof update.delegation === "string" && update.delegation.trim()) {
125
+ try {
126
+ await routeManagedRealtime(
127
+ agent,
128
+ voiceSessionId,
129
+ tailOperationId,
130
+ update.delegation,
131
+ );
132
+ } catch (error) {
133
+ routeFailure = error;
134
+ }
135
+ }
136
+ let stopFailure;
137
+ try {
138
+ await stopManagedRealtime(agent, voiceSessionId, stopOperationId);
139
+ } catch (error) {
140
+ stopFailure = error;
141
+ }
142
+ startedTurnId = undefined;
143
+ activeTurnId = undefined;
144
+ pendingEvents = [];
145
+ if (routeFailure !== undefined) throw routeFailure;
146
+ if (stopFailure !== undefined) throw stopFailure;
147
+ return JSON.stringify(update.effects);
148
+ },
149
+ async cancel() {
150
+ if (!startedTurnId) return false;
151
+ const turnId = startedTurnId;
152
+ await cancelManagedTurn(agent, turnId);
153
+ if (startedTurnId === turnId) startedTurnId = undefined;
154
+ return true;
155
+ },
156
+ preferredPhysicalInput: (current, labels) => raw.preferredPhysicalInput(current, labels),
157
+ free: () => { clearTimeout(prefetchTimer); prefetchAbort.abort(); raw.free(); },
158
+ };
159
+ }
160
+
161
+ function uuidV7() {
162
+ if (typeof globalThis.crypto?.getRandomValues !== "function") {
163
+ throw new Error("managed browser voice requires crypto.getRandomValues()");
164
+ }
165
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
166
+ let timestamp = Date.now();
167
+ for (let index = 5; index >= 0; index -= 1) {
168
+ bytes[index] = timestamp % 256;
169
+ timestamp = Math.floor(timestamp / 256);
170
+ }
171
+ bytes[6] = (bytes[6] & 0x0f) | 0x70;
172
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
173
+ const encoded = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));
174
+ 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("")}`;
175
+ }
176
+
177
+ function managedDelegationId(payload) {
178
+ try {
179
+ const event = typeof payload === "string" ? JSON.parse(payload) : payload;
180
+ return typeof event?.item?.id === "string" ? event.item.id : undefined;
181
+ } catch {
182
+ return undefined;
183
+ }
184
+ }
185
+
186
+ function isTerminalAgentEvent(event) {
187
+ return event?.type === "run.completed" || event?.type === "run.failed"
188
+ || event?.type === "run.cancelled" || event?.type === "turn_failed";
189
+ }
190
+
191
+ function mergeVoiceEffects(base, encoded) {
192
+ const allEffects = [base, ...encoded.map((value) => (
193
+ typeof value === "string" ? JSON.parse(value) : value
194
+ ))].filter((value) => value && typeof value === "object");
195
+ if (allEffects.length === 0) return base;
196
+ const generation = Math.max(...allEffects.map((value) => value.input_generation ?? 0));
197
+ const effects = allEffects.filter((value) => value.input_generation === undefined || value.input_generation === generation);
198
+ return {
199
+ ...effects[0],
200
+ input_generation: generation,
201
+ playback_enabled: effects.findLast((value) => value.playback_enabled !== undefined)?.playback_enabled,
202
+ acknowledge_frames: effects.some((value) => value.acknowledge_frames),
203
+ frames: effects.flatMap((value) => value.frames ?? []),
204
+ transcripts: effects.flatMap((value) => value.transcripts ?? []),
205
+ undelivered_answers: allEffects.flatMap((value) => value.undelivered_answers ?? []),
206
+ ready: effects.some((value) => value.ready === true) || undefined,
207
+ schedule_flush: effects.some((value) => value.schedule_flush),
208
+ };
209
+ }
@@ -0,0 +1,22 @@
1
+ export * as Agent from "./Agent.mjs";
2
+ export { ManagedError } from "./ManagedError.mjs";
3
+ export type {
4
+ Agent as ManagedAgent,
5
+ CronTrigger as ManagedCronTrigger,
6
+ CronTriggerConfig as ManagedCronTriggerConfig,
7
+ CreateOptions as ManagedCreateOptions,
8
+ CreateAndPromptOptions as ManagedCreateAndPromptOptions,
9
+ CreateAndPromptResult as ManagedCreateAndPromptResult,
10
+ CreateSettings as ManagedCreateSettings,
11
+ Event as ManagedEvent,
12
+ EventData as ManagedEventData,
13
+ HistoryCitation as ManagedHistoryCitation,
14
+ FindSessionsResponse as ManagedFindSessionsResponse,
15
+ ReadSessionResponse as ManagedReadSessionResponse,
16
+ MemoryKey as ManagedMemoryKey,
17
+ MemoryRecord as ManagedMemoryRecord,
18
+ MemoryResult as ManagedMemoryResult,
19
+ Organization as ManagedOrganization,
20
+ Turn as ManagedTurn,
21
+ TurnResult as ManagedTurnResult,
22
+ } from "./Agent.mjs";
@@ -0,0 +1,2 @@
1
+ export * as Agent from "./Agent.mjs";
2
+ export { ManagedError } from "./ManagedError.mjs";
@@ -0,0 +1,119 @@
1
+ const managedAgents = new WeakMap();
2
+
3
+ /** @internal Retains the authenticated client without exposing it on the public Agent handle. */
4
+ export function registerManagedAgent(agent, client, id, options = {}) {
5
+ managedAgents.set(agent, {
6
+ client,
7
+ eventAgent: agent,
8
+ id,
9
+ ...(options.voiceTransport === undefined ? {} : { voiceTransport: options.voiceTransport }),
10
+ });
11
+ }
12
+
13
+ /** @internal Retains managed lifecycle ownership for a capability-bound Agent projection. */
14
+ export function registerManagedAgentAlias(agent, source, options = {}) {
15
+ const state = managedAgent(source);
16
+ managedAgents.set(agent, {
17
+ ...state,
18
+ ...(options.voiceTransport === undefined ? {} : { voiceTransport: options.voiceTransport }),
19
+ });
20
+ }
21
+
22
+ /** @internal Resolves an optional browser media transport owned by an Agent projection. */
23
+ export function managedBrowserVoiceTransport(agent) {
24
+ return managedAgent(agent).voiceTransport;
25
+ }
26
+
27
+ /** @internal Starts the canonical Realtime lifecycle on the selected durable Agent. */
28
+ export function startManagedRealtime(agent, voiceSessionId, operationId) {
29
+ const { client, id } = managedAgent(agent);
30
+ return client.json(`${agentPath(id)}/realtime/start`, {
31
+ method: "POST",
32
+ body: JSON.stringify({
33
+ voice_session_id: voiceSessionId,
34
+ operation_id: operationId,
35
+ }),
36
+ });
37
+ }
38
+
39
+ /** @internal Warms exact-query retrieval without admitting an Agent turn. */
40
+ export function prefetchManagedRealtime(agent, voiceSessionId, query, signal) {
41
+ const { client, id } = managedAgent(agent);
42
+ return client.json(`${agentPath(id)}/realtime/prefetch`, {
43
+ method: "POST", signal,
44
+ body: JSON.stringify({ voice_session_id: voiceSessionId, query }),
45
+ });
46
+ }
47
+
48
+ /** @internal Atomically routes one Rust-formatted voice delegation on the durable Agent. */
49
+ export function routeManagedRealtime(agent, voiceSessionId, operationId, input) {
50
+ const { client, id } = managedAgent(agent);
51
+ return client.json(`${agentPath(id)}/realtime/delegate`, {
52
+ method: "POST",
53
+ body: JSON.stringify({
54
+ voice_session_id: voiceSessionId,
55
+ operation_id: operationId,
56
+ input,
57
+ }),
58
+ });
59
+ }
60
+
61
+ /** @internal Ends the canonical Realtime lifecycle on the selected durable Agent. */
62
+ export function stopManagedRealtime(agent, voiceSessionId, operationId) {
63
+ const { client, id } = managedAgent(agent);
64
+ return client.json(`${agentPath(id)}/realtime/stop`, {
65
+ method: "POST",
66
+ body: JSON.stringify({
67
+ voice_session_id: voiceSessionId,
68
+ operation_id: operationId,
69
+ }),
70
+ });
71
+ }
72
+
73
+ /** @internal Cancels only a managed turn that this voice session started. */
74
+ export function cancelManagedTurn(agent, turnId) {
75
+ const { client, id } = managedAgent(agent);
76
+ return client.json(`${agentPath(id)}/turns/${encodeURIComponent(turnId)}/cancel`, {
77
+ method: "POST",
78
+ });
79
+ }
80
+
81
+ /** @internal Streams only canonical typed Agent events from the durable envelope log. */
82
+ export function observeManagedAgentEvents(agent, listener) {
83
+ if (typeof listener !== "function") throw new TypeError("managed voice event listener must be a function");
84
+ const controller = new AbortController();
85
+ void (async () => {
86
+ try {
87
+ const { eventAgent } = managedAgent(agent);
88
+ for await (const envelope of eventAgent.events.watch({
89
+ cursor: "latest",
90
+ signal: controller.signal,
91
+ })) {
92
+ if (controller.signal.aborted) return;
93
+ if (envelope.data.type === "event") {
94
+ listener(Object.freeze({ event: envelope.data.event, turnId: envelope.turnId, cursor: envelope.cursor }));
95
+ } else if (envelope.data.type === "turn_failed") {
96
+ listener(Object.freeze({ event: envelope.data, turnId: envelope.turnId, cursor: envelope.cursor }));
97
+ }
98
+ }
99
+ } catch (error) {
100
+ if (!controller.signal.aborted) reportError(error);
101
+ }
102
+ })();
103
+ return () => controller.abort();
104
+ }
105
+
106
+ function managedAgent(agent) {
107
+ const state = managedAgents.get(agent);
108
+ if (!state) throw new TypeError("voice requires a managed Nanocodex Agent");
109
+ return state;
110
+ }
111
+
112
+ function agentPath(id) {
113
+ return `/v1/agents/${encodeURIComponent(id)}`;
114
+ }
115
+
116
+ function reportError(error) {
117
+ if (typeof globalThis.reportError === "function") globalThis.reportError(error);
118
+ else console.error(error);
119
+ }
package/node/Agent.d.mts CHANGED
@@ -1,21 +1,48 @@
1
1
  import type {
2
+ AgentLifecycle,
2
3
  AgentOptions,
4
+ CodeEvaluator,
3
5
  DefaultAgent,
4
- MppSession,
5
- ToolMap,
6
+ DurabilityStore,
7
+ McpServers,
8
+ ToolConfiguration,
6
9
  } from "../types.mjs";
10
+ import type { ManagedTransport, ResponsesTransport } from "./Transport.mjs";
11
+ import type { Tool as SubagentTool } from "../runtime/subagents.mjs";
12
+ import type { Workspace } from "./workspace.mjs";
13
+ import type { Tools } from "../tools/Tools.mjs";
7
14
 
8
15
  export type Agent = DefaultAgent;
16
+ type ToolExposureOptions =
17
+ | { mcp?: false | undefined; toolMode?: "code" | "direct" | undefined }
18
+ | { mcp: McpServers; toolMode?: "code" | undefined };
9
19
 
10
20
  /** Creates a Node-hosted Rust/WASM Agent. */
21
+ export function create(options: create.ManagedOptions): Promise<AgentLifecycle>;
11
22
  export function create(options: create.Options): Promise<create.ReturnType>;
12
23
  export declare namespace create {
13
- type Options = AgentOptions & ({ apiKey: string; mpp?: never } | { apiKey?: never; mpp: MppSession }) & {
14
- apiBaseUrl?: string | undefined;
24
+ type ManagedOptions = Readonly<{
25
+ transport: ManagedTransport;
26
+ tools?: Tools | undefined;
27
+ }>;
28
+ type Options = AgentOptions & ToolExposureOptions & {
29
+ codeEvaluator?: CodeEvaluator | undefined;
30
+ /** Caller-owned rooted filesystem mounted through standard workspace tools. */
31
+ filesystem?: Workspace | undefined;
15
32
  module?: unknown;
16
- tools?: ToolMap | undefined;
17
- toolMode?: "code" | "direct" | undefined;
18
- websocketUrl?: string | undefined;
19
- };
33
+ transport: ResponsesTransport;
34
+ } & (
35
+ | {
36
+ durability?: undefined;
37
+ durabilityId?: undefined;
38
+ tools?: ToolConfiguration<SubagentTool> | undefined;
39
+ }
40
+ | {
41
+ durability: DurabilityStore;
42
+ durabilityId: string;
43
+ /** The root remains durable; clean subagent children are in-memory. */
44
+ tools?: ToolConfiguration<SubagentTool> | undefined;
45
+ }
46
+ );
20
47
  type ReturnType = Agent;
21
48
  }