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
package/node/Agent.mjs CHANGED
@@ -7,67 +7,149 @@ import {
7
7
  bindHostSession,
8
8
  createAgentClient,
9
9
  createEventChannel,
10
+ createSessionId,
10
11
  defineRuntime,
12
+ loadDurabilityRuntime,
13
+ loadSubscriptionRuntime,
14
+ reportError,
15
+ registerDefinitionHost,
16
+ releaseDefinitionHost,
11
17
  releaseHostSession,
12
18
  toWasmConfig,
13
19
  } from "../internal.mjs";
14
20
  import { createNodeHost } from "./host.mjs";
21
+ import { resolveResponsesTransport } from "../runtime/responses-transport.mjs";
22
+ import {
23
+ createManagedAgent,
24
+ managedTransportOptions,
25
+ } from "../runtime/managed-transport.mjs";
26
+ import { resolveTools } from "../runtime/tool-configuration.mjs";
15
27
 
16
28
  let initializedWeb;
17
29
  let NodeNanocodex;
18
30
 
19
31
  export function create(options = {}) {
32
+ if (managedTransportOptions(options?.transport)) return createManagedAgent(options);
20
33
  const {
21
34
  model,
22
35
  thinking,
23
36
  reasoningMode,
24
37
  fastMode,
25
38
  instructions,
39
+ additionalInstructions,
26
40
  sessionId,
27
41
  workspace,
28
42
  resume,
29
- apiKey,
30
- mpp,
31
- websocketUrl,
32
- apiBaseUrl,
43
+ durability,
44
+ durabilityId,
45
+ transport,
33
46
  module,
47
+ filesystem,
34
48
  tools,
35
49
  toolMode,
50
+ mcp,
51
+ codeEvaluator,
36
52
  } = options;
53
+ const stableSessionId = sessionId ?? createSessionId();
54
+ const {
55
+ apiKey,
56
+ subscription,
57
+ mpp,
58
+ websocketUrl,
59
+ apiBaseUrl,
60
+ websocketWarmup,
61
+ } = resolveResponsesTransport(transport);
62
+ const { tools: hostTools, subagents: subagentConfig } = resolveTools(tools);
37
63
  const events = createEventChannel();
38
- if (mpp !== undefined && apiKey !== undefined) {
39
- throw new TypeError("apiKey and mpp are mutually exclusive");
64
+ if (filesystem && workspace !== undefined && workspace !== filesystem.root) {
65
+ throw new TypeError("workspace must match filesystem.root when both are provided");
40
66
  }
67
+ const tempoMcp = mpp?.[Symbol.for("nanocodex.tempo.mcp")];
68
+ let hostDefinitionId;
41
69
  const host = createNodeHost({
42
70
  mpp,
71
+ mcpServers: mcp === false
72
+ ? undefined
73
+ : tempoMcp ? { ...tempoMcp, ...mcp } : mcp,
43
74
  onEvent: events.emit,
44
- tools,
75
+ filesystem,
76
+ tools: hostTools,
45
77
  toolMode,
46
- workspace: workspace ?? resume?.workspace,
78
+ workspace: workspace ?? filesystem?.root ?? resume?.workspace,
79
+ codeEvaluator,
80
+ onDispose: () => releaseDefinitionHost(hostDefinitionId),
47
81
  });
82
+ let durabilityOwner;
83
+ let creationStarted = false;
84
+ hostDefinitionId = registerDefinitionHost(host);
48
85
  activateHost(host);
49
86
  const runtime = defineRuntime({
50
87
  key: "node-wasm",
51
88
  name: "Nanocodex Node WASM",
52
89
  type: "node",
53
90
  async create(config) {
54
- activateHost(host);
55
- const Nanocodex = module === undefined
56
- ? loadNodeNanocodex()
57
- : await loadWebNanocodex(module);
58
- activateHost(host);
59
- return new Nanocodex(JSON.stringify(toWasmConfig({
60
- apiKey: apiKey ?? (mpp === undefined ? undefined : "mpp-managed"),
61
- websocketUrl: websocketUrl ?? (mpp === undefined
62
- ? undefined
63
- : "wss://openai.mpp.tempo.xyz/v1/responses"),
64
- apiBaseUrl,
65
- ...config,
66
- })));
91
+ creationStarted = true;
92
+ try {
93
+ if (durability !== undefined || durabilityId !== undefined) {
94
+ durabilityOwner = (await loadDurabilityRuntime()).own(
95
+ host,
96
+ durability,
97
+ durabilityId,
98
+ );
99
+ }
100
+ activateHost(host);
101
+ await host.ready();
102
+ const Nanocodex = module === undefined
103
+ ? loadNodeNanocodex()
104
+ : await loadWebNanocodex(module);
105
+ activateHost(host);
106
+ const configJson = JSON.stringify(toWasmConfig({
107
+ apiKey: apiKey ?? (subscription === undefined
108
+ ? mpp === undefined ? undefined : "mpp-managed"
109
+ : "subscription-managed"),
110
+ websocketUrl: websocketUrl ?? (mpp === undefined
111
+ ? undefined
112
+ : "wss://openai.mpp.tempo.xyz/v1/responses"),
113
+ apiBaseUrl,
114
+ websocketWarmup,
115
+ subagents: subagentConfig,
116
+ hostDefinitionId,
117
+ ...config,
118
+ durabilityHostId: durabilityOwner?.id,
119
+ }));
120
+ return subscription === undefined
121
+ ? Nanocodex.create(configJson)
122
+ : Nanocodex.createWithChatGpt(
123
+ configJson,
124
+ (await loadSubscriptionRuntime()).rawSubscription(subscription),
125
+ );
126
+ } catch (error) {
127
+ durabilityOwner?.abandon();
128
+ await host.dispose();
129
+ throw error;
130
+ }
67
131
  },
68
132
  subscribe: events.subscribe,
69
- adopt: (raw) => bindHostSession(host, raw.sessionId),
70
- release: (raw) => releaseHostSession(host, raw.sessionId),
133
+ adopt(raw) {
134
+ host.retain();
135
+ try {
136
+ durabilityOwner?.retain();
137
+ bindHostSession(host, raw.sessionId);
138
+ events.addSource(raw);
139
+ } catch (error) {
140
+ events.removeSource(raw);
141
+ durabilityOwner?.release();
142
+ releaseHost(host);
143
+ throw error;
144
+ }
145
+ },
146
+ release(raw) {
147
+ events.removeSource(raw);
148
+ host.releaseSession(raw.sessionId);
149
+ releaseHostSession(host, raw.sessionId);
150
+ durabilityOwner?.release();
151
+ releaseHost(host);
152
+ },
71
153
  decorate: (agent) => agent.extend(agentActions()),
72
154
  });
73
155
  return createAgentClient(runtime, {
@@ -76,12 +158,21 @@ export function create(options = {}) {
76
158
  reasoningMode,
77
159
  fastMode,
78
160
  instructions,
79
- sessionId,
80
- workspace,
161
+ additionalInstructions,
162
+ sessionId: stableSessionId,
163
+ workspace: workspace ?? filesystem?.root,
81
164
  resume,
165
+ durabilityId,
166
+ }).catch(async (error) => {
167
+ if (!creationStarted) await host.dispose();
168
+ throw error;
82
169
  });
83
170
  }
84
171
 
172
+ function releaseHost(host) {
173
+ void host.release().catch(reportError);
174
+ }
175
+
85
176
  function loadNodeNanocodex() {
86
177
  const require = createRequire(import.meta.url);
87
178
  NodeNanocodex ||= require("../pkg-node/nanocodex.js").Nanocodex;
@@ -0,0 +1,9 @@
1
+ import type {
2
+ ChatGptSubscriptionHandle,
3
+ ChatGptSubscriptionOptions,
4
+ } from "../types.mjs";
5
+
6
+ /** Opens the Rust-owned ChatGPT device-login and credential lifecycle. */
7
+ export function open(
8
+ options: Omit<ChatGptSubscriptionOptions, "module"> & { module?: never },
9
+ ): Promise<ChatGptSubscriptionHandle>;
@@ -0,0 +1,17 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ import { installHostBridge } from "../internal.mjs";
4
+ import { openSubscription } from "../runtime/chatgpt-subscription.mjs";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ let WasmChatGptSubscription;
8
+
9
+ /** Opens a Rust-managed ChatGPT subscription over caller-owned storage and fetch. */
10
+ export async function open(options) {
11
+ if (options?.module !== undefined) {
12
+ throw new TypeError("Node ChatGptSubscription does not accept a browser WASM module");
13
+ }
14
+ installHostBridge();
15
+ WasmChatGptSubscription ||= require("../pkg-node/nanocodex.js").ChatGptSubscription;
16
+ return openSubscription(options, (config) => WasmChatGptSubscription.open(config));
17
+ }
@@ -0,0 +1,41 @@
1
+ import type {
2
+ ChatGptSubscriptionHandle,
3
+ MppSession,
4
+ } from "../types.mjs";
5
+ import type { Options as ManagedClientOptions } from "../managed/Agent.mjs";
6
+
7
+ declare const responsesTransport: unique symbol;
8
+ declare const managedTransport: unique symbol;
9
+
10
+ export type ResponsesTransport = Readonly<{
11
+ [responsesTransport]: true;
12
+ }>;
13
+ export type ManagedTransport = Readonly<{ [managedTransport]: true }>;
14
+ export type Transport = ResponsesTransport | ManagedTransport;
15
+
16
+ type EndpointOptions = Readonly<{
17
+ apiBaseUrl?: string | undefined;
18
+ websocketUrl?: string | undefined;
19
+ websocketWarmup?: boolean | undefined;
20
+ }>;
21
+
22
+ export function openAi(options: EndpointOptions & Readonly<{
23
+ apiKey: string;
24
+ }>): ResponsesTransport;
25
+
26
+ export function chatGpt(options: EndpointOptions & Readonly<{
27
+ subscription: ChatGptSubscriptionHandle;
28
+ }>): ResponsesTransport;
29
+
30
+ export function mpp(options: EndpointOptions & Readonly<{
31
+ session: MppSession;
32
+ }>): ResponsesTransport;
33
+
34
+ export type ManagedIdentity =
35
+ | Readonly<{ create: true; id?: never }>
36
+ | Readonly<{ id: string; create?: never }>;
37
+
38
+ /** Account-authenticated durable Agent transport with explicit create/open identity. */
39
+ export function managed(options: ManagedClientOptions & Readonly<{
40
+ agent: ManagedIdentity;
41
+ }>): ManagedTransport;
@@ -0,0 +1,46 @@
1
+ import {
2
+ createResponsesTransport,
3
+ nonEmpty,
4
+ } from "../runtime/responses-transport.mjs";
5
+ import { createManagedTransport } from "../runtime/managed-transport.mjs";
6
+
7
+ export function openAi(options) {
8
+ const apiKey = nonEmpty(options?.apiKey, "OpenAI API key");
9
+ return createResponsesTransport({
10
+ apiKey,
11
+ ...endpoints(options),
12
+ });
13
+ }
14
+
15
+ export function chatGpt(options) {
16
+ if (!options?.subscription || typeof options.subscription !== "object") {
17
+ throw new TypeError("ChatGPT transport requires a subscription handle");
18
+ }
19
+ return createResponsesTransport({
20
+ subscription: options.subscription,
21
+ ...endpoints(options),
22
+ });
23
+ }
24
+
25
+ export function mpp(options) {
26
+ if (!options?.session || typeof options.session.ws !== "function") {
27
+ throw new TypeError("MPP transport requires a session with ws(endpoint)");
28
+ }
29
+ return createResponsesTransport({
30
+ mpp: options.session,
31
+ ...endpoints(options),
32
+ });
33
+ }
34
+
35
+ /** Account-authenticated durable Agent transport with explicit create/open identity. */
36
+ export function managed(options) {
37
+ return createManagedTransport(options);
38
+ }
39
+
40
+ function endpoints(options = {}) {
41
+ return {
42
+ apiBaseUrl: options.apiBaseUrl,
43
+ websocketUrl: options.websocketUrl,
44
+ websocketWarmup: options.websocketWarmup,
45
+ };
46
+ }
package/node/host.mjs CHANGED
@@ -5,23 +5,70 @@ import WebSocket from "ws";
5
5
  import packageMetadata from "../package.json" with { type: "json" };
6
6
 
7
7
  import { createCodeRuntime } from "../runtime/code-runtime.mjs";
8
+ import { createMcpRuntime } from "../runtime/mcp-runtime.mjs";
9
+ import {
10
+ settleCleanup,
11
+ toolRouterBrand,
12
+ toolRouterRuntime,
13
+ toolRuntimeLifecycle,
14
+ } from "../runtime/tool-router.mjs";
15
+ import { utf8ByteLength } from "../runtime/utf8.mjs";
8
16
 
9
17
  const RESPONSES_WEBSOCKETS_BETA = "responses_websockets=2026-02-06";
10
18
  const USER_AGENT = `nanocodex-wasm/${packageMetadata.version}`;
11
19
  const DEFAULT_MAX_QUEUED_MESSAGES = 4_096;
12
20
  const DEFAULT_MAX_QUEUED_BYTES = 32 * 1024 * 1024;
13
21
  const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;
22
+ const MPP_CLIENT_PROTOCOL_ERROR_CLOSE_CODE = 3008;
14
23
 
15
24
  export function createNodeHost(options = {}) {
25
+ const toolMode = options.toolMode ?? "code";
26
+ if (toolMode !== "code" && toolMode !== "direct") {
27
+ throw new TypeError("toolMode must be code or direct");
28
+ }
29
+ const toolsRouter = options.tools?.[toolRouterBrand]
30
+ ? options.tools[toolRouterRuntime]
31
+ : undefined;
32
+ const toolsMcp = toolsRouter?.hasSourceKind("mcp") === true;
33
+ if (toolsRouter?.hasSource("workspace") && options.filesystem) {
34
+ throw new TypeError("workspace is already configured in Tools");
35
+ }
36
+ if (toolsMcp && options.mcpServers) {
37
+ throw new TypeError("MCP is already configured in Tools");
38
+ }
39
+ if ((toolsMcp || options.mcpServers) && toolMode !== "code") {
40
+ throw new TypeError("remote MCP requires Code Mode");
41
+ }
42
+ const toolsLifecycle = options.tools?.[toolRuntimeLifecycle];
43
+ toolsLifecycle?.available();
16
44
  const connections = new Map();
17
45
  const code = createCodeRuntime(options.tools, {
18
46
  require: createRequire(resolve(options.workspace ?? process.cwd(), ".nanocodex-code-mode.cjs")),
19
47
  console: new Console({ stdout: process.stderr, stderr: process.stderr }),
48
+ evaluate: options.codeEvaluator,
49
+ });
50
+ const filesystem = options.filesystem
51
+ ? import("../runtime/workspace.mjs")
52
+ .then(({ tools }) => code.addTools(tools(options.filesystem)))
53
+ : undefined;
54
+ const mcp = options.mcpServers
55
+ ? createMcpRuntime(options.mcpServers, { clientName: "nanocodex-node" })
56
+ : undefined;
57
+ let disposal;
58
+ const mcpInstalled = mcp?.then(async (provider) => {
59
+ if (disposal) {
60
+ await provider.close();
61
+ return;
62
+ }
63
+ try { code.addProvider(provider, { id: "mcp", kind: "mcp" }); }
64
+ catch (error) {
65
+ try { await provider.close(); }
66
+ catch (cleanupError) {
67
+ throw new AggregateError([error, cleanupError], "MCP installation and cleanup failed");
68
+ }
69
+ throw error;
70
+ }
20
71
  });
21
- const toolMode = options.toolMode ?? "code";
22
- if (toolMode !== "code" && toolMode !== "direct") {
23
- throw new TypeError("toolMode must be code or direct");
24
- }
25
72
  const onEvent = options.onEvent || (() => {});
26
73
  const connectTimeoutMs = options.connectTimeoutMs ?? 30_000;
27
74
  const sendTimeoutMs = options.sendTimeoutMs ?? 30_000;
@@ -29,19 +76,21 @@ export function createNodeHost(options = {}) {
29
76
  const maxQueuedBytes = options.maxQueuedBytes ?? DEFAULT_MAX_QUEUED_BYTES;
30
77
  const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
31
78
  let nextHandle = 1;
79
+ let references = 0;
32
80
 
33
81
  function connect(endpoint, apiKey, sessionId, metadata = {}) {
34
82
  if (options.mpp) return connectMpp(endpoint);
35
83
  return new Promise((resolve, reject) => {
36
84
  let settled = false;
37
85
  let upgradeResponse;
86
+ const threadId = metadata.threadId ?? sessionId;
38
87
  const headers = {
39
88
  Authorization: `Bearer ${apiKey}`,
40
89
  "OpenAI-Beta": RESPONSES_WEBSOCKETS_BETA,
41
90
  "x-openai-internal-codex-responses-lite": "true",
42
91
  "session-id": sessionId,
43
- "thread-id": sessionId,
44
- "x-client-request-id": sessionId,
92
+ "thread-id": threadId,
93
+ "x-client-request-id": threadId,
45
94
  "x-responsesapi-include-timing-metrics": "true",
46
95
  "User-Agent": USER_AGENT,
47
96
  };
@@ -60,12 +109,13 @@ export function createNodeHost(options = {}) {
60
109
  socket.on("unexpected-response", (_request, response) => {
61
110
  if (settled) return;
62
111
  settled = true;
112
+ response.setEncoding("utf8");
63
113
  const chunks = [];
64
- response.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
114
+ response.on("data", (chunk) => chunks.push(chunk));
65
115
  response.on("end", () => {
66
116
  const error = new Error(`WebSocket handshake was rejected with HTTP ${response.statusCode}`);
67
117
  error.status = response.statusCode;
68
- error.body = chunks.length ? Buffer.concat(chunks).toString("utf8") : "empty response body";
118
+ error.body = chunks.length ? chunks.join("") : "empty response body";
69
119
  const retryAfter = Number(header(response.headers, "retry-after"));
70
120
  if (Number.isFinite(retryAfter) && retryAfter >= 0) error.retryAfter = retryAfter;
71
121
  reject(error);
@@ -125,8 +175,15 @@ export function createNodeHost(options = {}) {
125
175
  });
126
176
  socket.addEventListener("close", (event) => {
127
177
  if (!connection.intentionallyClosed && !connection.overflowed) {
178
+ const code = event.code ?? 1000;
128
179
  const suffix = event.reason ? `: ${event.reason}` : "";
129
- enqueue(connection, { kind: "closed", detail: `with code ${event.code ?? 1000}${suffix}` });
180
+ enqueue(connection, code === MPP_CLIENT_PROTOCOL_ERROR_CLOSE_CODE
181
+ ? {
182
+ kind: "error",
183
+ detail: `MPP WebSocket payment flow failed with code ${code}${suffix}`,
184
+ reconnectable: false,
185
+ }
186
+ : { kind: "closed", detail: `with code ${code}${suffix}` });
130
187
  }
131
188
  });
132
189
  socket.addEventListener("error", () => {
@@ -177,7 +234,7 @@ export function createNodeHost(options = {}) {
177
234
  });
178
235
  }
179
236
 
180
- function next(handle, timeoutMs) {
237
+ function next(handle) {
181
238
  const connection = connections.get(handle);
182
239
  if (!connection) {
183
240
  return Promise.resolve(JSON.stringify({ kind: "closed", detail: "before the next frame" }));
@@ -189,12 +246,7 @@ export function createNodeHost(options = {}) {
189
246
  }
190
247
  if (connection.waiter) return Promise.reject(new Error("concurrent reads are unsupported"));
191
248
  return new Promise((resolve) => {
192
- const timer = setTimeout(() => {
193
- connection.waiter = undefined;
194
- resolve(JSON.stringify({ kind: "timeout" }));
195
- }, timeoutMs);
196
249
  connection.waiter = (message) => {
197
- clearTimeout(timer);
198
250
  connection.waiter = undefined;
199
251
  resolve(JSON.stringify(message));
200
252
  };
@@ -234,18 +286,48 @@ export function createNodeHost(options = {}) {
234
286
  connection.queuedBytes += bytes;
235
287
  }
236
288
 
289
+ function dispose() {
290
+ if (disposal) return disposal;
291
+ disposal = Promise.resolve().then(() => settleCleanup([
292
+ ...[...connections.keys()].map((handle) => () => close(handle)),
293
+ () => code.reset(),
294
+ () => mcpInstalled,
295
+ () => toolsLifecycle?.close(),
296
+ () => options.onDispose?.(),
297
+ ], "Nanocodex host disposal failed", disposal));
298
+ return disposal;
299
+ }
300
+
301
+ toolsLifecycle?.claim();
237
302
  return Object.freeze({
303
+ ready: async () => { await Promise.all([filesystem, mcpInstalled]); },
304
+ retain() {
305
+ if (disposal) throw new Error("Nanocodex host is already disposed");
306
+ references += 1;
307
+ },
308
+ release() {
309
+ if (references > 0) references -= 1;
310
+ return references === 0 ? dispose() : Promise.resolve();
311
+ },
238
312
  connect,
239
313
  send,
240
314
  next,
241
315
  close,
242
316
  sleep: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
243
- executeCode: code.executeCode,
317
+ executeCode: code.executeCodeObserved,
318
+ waitCode: code.waitCodeObserved,
319
+ beginCodeTurn: code.beginTurn,
320
+ cancelCodeTurn: code.cancelTurn,
321
+ nextCodeUpdate: code.nextCodeUpdate,
244
322
  executeTool: code.executeTool,
323
+ bindSubagentSession: code.bindSubagentSession,
324
+ cancelCode: code.cancel,
245
325
  toolMode: () => toolMode,
246
326
  toolDefinitions: code.toolDefinitions,
327
+ releaseSession: code.releaseSession,
247
328
  emitEvent: onEvent,
248
329
  reset: code.reset,
330
+ dispose,
249
331
  });
250
332
  }
251
333
 
@@ -267,7 +349,7 @@ function header(headers, name) {
267
349
  }
268
350
 
269
351
  function messageBytes(message) {
270
- return Buffer.byteLength(message.kind === "text" ? message.text : JSON.stringify(message), "utf8");
352
+ return utf8ByteLength(message.kind === "text" ? message.text : JSON.stringify(message));
271
353
  }
272
354
 
273
355
  function errorMessage(error) {
package/node/index.d.mts CHANGED
@@ -1,18 +1,62 @@
1
- export { Actions } from "../index.mjs";
1
+ export * as Actions from "../actions/index.mjs";
2
+ export {
3
+ createMemoryChatGptSubscriptionStore,
4
+ subscriptionRevision,
5
+ } from "../runtime/subscription-store.mjs";
6
+ export { createQuickJsEvaluator } from "../runtime/quickjs-evaluator.mjs";
7
+ export {
8
+ createTempoProvider,
9
+ createTempoProviderFromAccounts,
10
+ DEFAULT_MERCATOR_MCP_URL,
11
+ } from "../runtime/tempo-provider.mjs";
12
+ export type {
13
+ AccountsTempoProviderOptions,
14
+ AccountsWallet,
15
+ TempoProvider,
16
+ } from "../runtime/tempo-provider.mjs";
2
17
  export type {
3
18
  AgentEvent,
19
+ AgentLifecycle,
20
+ AgentSessionContext,
21
+ ChatGptCredential,
22
+ ChatGptCredentialSeed,
23
+ ChatGptLoginStatus,
24
+ ChatGptSubscriptionHandle,
25
+ ChatGptSubscriptionOptions,
26
+ ChatGptSubscriptionStore,
4
27
  CostStatus,
28
+ CodeEvaluator,
29
+ CodeEvaluatorEnvironment,
5
30
  EstimatedUsdCost,
6
31
  PromptInput,
7
32
  PromptItem,
33
+ LifecycleTurn,
34
+ LifecycleTurnResult,
8
35
  ReasoningMode,
9
36
  SessionSnapshot,
10
37
  Thinking,
11
38
  Tool,
39
+ NamedTool,
12
40
  ToolContext,
41
+ SubagentToolContext,
42
+ ToolConfiguration,
13
43
  ToolMap,
14
44
  Turn,
15
45
  TurnResult,
16
46
  TurnUsage,
47
+ McpPayment,
48
+ McpServer,
49
+ McpServers,
50
+ MemoryChatGptSubscriptionStore,
51
+ MppSession,
52
+ SubscriptionCommitRequest,
53
+ SubscriptionCommitResult,
54
+ SubscriptionRevision,
55
+ SubscriptionStoredValue,
17
56
  } from "../types.mjs";
18
57
  export * as Agent from "./Agent.mjs";
58
+ export * as ChatGptSubscription from "./ChatGptSubscription.mjs";
59
+ export * as Subagents from "../runtime/subagents.mjs";
60
+ export * as Transport from "./Transport.mjs";
61
+ export * as Workspace from "./workspace.mjs";
62
+ export * as Tools from "../tools/index.mjs";
package/node/index.mjs CHANGED
@@ -1,2 +1,17 @@
1
- export { Actions } from "../index.mjs";
1
+ export * as Actions from "../actions/index.mjs";
2
+ export {
3
+ createMemoryChatGptSubscriptionStore,
4
+ subscriptionRevision,
5
+ } from "../runtime/subscription-store.mjs";
6
+ export { createQuickJsEvaluator } from "../runtime/quickjs-evaluator.mjs";
7
+ export {
8
+ createTempoProvider,
9
+ createTempoProviderFromAccounts,
10
+ DEFAULT_MERCATOR_MCP_URL,
11
+ } from "../runtime/tempo-provider.mjs";
2
12
  export * as Agent from "./Agent.mjs";
13
+ export * as ChatGptSubscription from "./ChatGptSubscription.mjs";
14
+ export * as Subagents from "../runtime/subagents.mjs";
15
+ export * as Transport from "./Transport.mjs";
16
+ export * as Workspace from "./workspace.mjs";
17
+ export * as Tools from "../tools/index.mjs";
@@ -0,0 +1,10 @@
1
+ import type { Workspace, WorkspaceBackend, WorkspaceEntry } from "../runtime/workspace.mjs";
2
+
3
+ export { tools } from "../runtime/workspace.mjs";
4
+
5
+ export function open(options: {
6
+ path: string;
7
+ root?: string;
8
+ }): Promise<Workspace>;
9
+
10
+ export type { Workspace, WorkspaceBackend, WorkspaceEntry };