@nodetool-ai/cli 0.8.1 → 0.8.3

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 (213) hide show
  1. package/README.md +31 -1
  2. package/dist/.nodetool-build-stamp +1 -1
  3. package/dist/affected/affected.d.ts +11 -13
  4. package/dist/affected/affected.d.ts.map +1 -1
  5. package/dist/affected/affected.js +51 -2
  6. package/dist/affected/affected.js.map +1 -1
  7. package/dist/app-debug/app-target.d.ts +1 -1
  8. package/dist/app-debug/app-target.d.ts.map +1 -1
  9. package/dist/app-debug/harness.d.ts +3 -1
  10. package/dist/app-debug/harness.d.ts.map +1 -1
  11. package/dist/app-debug/harness.js +23 -0
  12. package/dist/app-debug/harness.js.map +1 -1
  13. package/dist/app.d.ts.map +1 -1
  14. package/dist/app.js +2 -1
  15. package/dist/app.js.map +1 -1
  16. package/dist/chat-codeact.d.ts +8 -0
  17. package/dist/chat-codeact.d.ts.map +1 -1
  18. package/dist/chat-codeact.js +59 -21
  19. package/dist/chat-codeact.js.map +1 -1
  20. package/dist/chat-context.d.ts.map +1 -1
  21. package/dist/chat-context.js +7 -2
  22. package/dist/chat-context.js.map +1 -1
  23. package/dist/child-exit.d.ts +3 -0
  24. package/dist/child-exit.d.ts.map +1 -0
  25. package/dist/child-exit.js +17 -0
  26. package/dist/child-exit.js.map +1 -0
  27. package/dist/commands/__tests__/timeline-render-audio.test.js +1 -1
  28. package/dist/commands/__tests__/timeline-render-audio.test.js.map +1 -1
  29. package/dist/commands/__tests__/timeline-render-completeness.test.d.ts +2 -0
  30. package/dist/commands/__tests__/timeline-render-completeness.test.d.ts.map +1 -0
  31. package/dist/commands/__tests__/timeline-render-completeness.test.js +117 -0
  32. package/dist/commands/__tests__/timeline-render-completeness.test.js.map +1 -0
  33. package/dist/commands/__tests__/timeline-score.test.d.ts +2 -0
  34. package/dist/commands/__tests__/timeline-score.test.d.ts.map +1 -0
  35. package/dist/commands/__tests__/timeline-score.test.js +100 -0
  36. package/dist/commands/__tests__/timeline-score.test.js.map +1 -0
  37. package/dist/commands/affected.d.ts.map +1 -1
  38. package/dist/commands/affected.js +10 -5
  39. package/dist/commands/affected.js.map +1 -1
  40. package/dist/commands/agent.d.ts.map +1 -1
  41. package/dist/commands/agent.js +12 -2
  42. package/dist/commands/agent.js.map +1 -1
  43. package/dist/commands/app.d.ts.map +1 -1
  44. package/dist/commands/app.js +29 -5
  45. package/dist/commands/app.js.map +1 -1
  46. package/dist/commands/apps.d.ts.map +1 -1
  47. package/dist/commands/apps.js +126 -32
  48. package/dist/commands/apps.js.map +1 -1
  49. package/dist/commands/debug-summary-output.d.ts +22 -0
  50. package/dist/commands/debug-summary-output.d.ts.map +1 -0
  51. package/dist/commands/debug-summary-output.js +28 -0
  52. package/dist/commands/debug-summary-output.js.map +1 -0
  53. package/dist/commands/deploy-helpers.d.ts +2 -1
  54. package/dist/commands/deploy-helpers.d.ts.map +1 -1
  55. package/dist/commands/errors.d.ts +11 -0
  56. package/dist/commands/errors.d.ts.map +1 -0
  57. package/dist/commands/errors.js +177 -0
  58. package/dist/commands/errors.js.map +1 -0
  59. package/dist/commands/eval.d.ts.map +1 -1
  60. package/dist/commands/eval.js +4 -1
  61. package/dist/commands/eval.js.map +1 -1
  62. package/dist/commands/extension.d.ts +12 -0
  63. package/dist/commands/extension.d.ts.map +1 -0
  64. package/dist/commands/extension.js +30 -0
  65. package/dist/commands/extension.js.map +1 -0
  66. package/dist/commands/game-benchmark.d.ts +34 -0
  67. package/dist/commands/game-benchmark.d.ts.map +1 -0
  68. package/dist/commands/game-benchmark.js +95 -0
  69. package/dist/commands/game-benchmark.js.map +1 -0
  70. package/dist/commands/game-smoke.d.ts +3 -0
  71. package/dist/commands/game-smoke.d.ts.map +1 -0
  72. package/dist/commands/game-smoke.js +23 -0
  73. package/dist/commands/game-smoke.js.map +1 -0
  74. package/dist/commands/game.d.ts.map +1 -1
  75. package/dist/commands/game.js +291 -20
  76. package/dist/commands/game.js.map +1 -1
  77. package/dist/commands/harness.d.ts +50 -0
  78. package/dist/commands/harness.d.ts.map +1 -1
  79. package/dist/commands/harness.js +289 -73
  80. package/dist/commands/harness.js.map +1 -1
  81. package/dist/commands/js-script.d.ts.map +1 -1
  82. package/dist/commands/js-script.js +6 -22
  83. package/dist/commands/js-script.js.map +1 -1
  84. package/dist/commands/mcp.d.ts +21 -0
  85. package/dist/commands/mcp.d.ts.map +1 -0
  86. package/dist/commands/mcp.js +166 -0
  87. package/dist/commands/mcp.js.map +1 -0
  88. package/dist/commands/output.d.ts +8 -0
  89. package/dist/commands/output.d.ts.map +1 -1
  90. package/dist/commands/output.js +18 -0
  91. package/dist/commands/output.js.map +1 -1
  92. package/dist/commands/package.d.ts.map +1 -1
  93. package/dist/commands/package.js +12 -12
  94. package/dist/commands/package.js.map +1 -1
  95. package/dist/commands/resource-read.d.ts.map +1 -1
  96. package/dist/commands/resource-read.js +5 -1
  97. package/dist/commands/resource-read.js.map +1 -1
  98. package/dist/commands/runs.d.ts +7 -0
  99. package/dist/commands/runs.d.ts.map +1 -0
  100. package/dist/commands/runs.js +302 -0
  101. package/dist/commands/runs.js.map +1 -0
  102. package/dist/commands/sketch.d.ts.map +1 -1
  103. package/dist/commands/sketch.js +6 -22
  104. package/dist/commands/sketch.js.map +1 -1
  105. package/dist/commands/timeline-render.d.ts +6 -1
  106. package/dist/commands/timeline-render.d.ts.map +1 -1
  107. package/dist/commands/timeline-render.js +15 -25
  108. package/dist/commands/timeline-render.js.map +1 -1
  109. package/dist/commands/timeline-score.d.ts +16 -0
  110. package/dist/commands/timeline-score.d.ts.map +1 -0
  111. package/dist/commands/timeline-score.js +90 -0
  112. package/dist/commands/timeline-score.js.map +1 -0
  113. package/dist/commands/timeline.d.ts.map +1 -1
  114. package/dist/commands/timeline.js +8 -22
  115. package/dist/commands/timeline.js.map +1 -1
  116. package/dist/commands/version-commands.d.ts +2 -5
  117. package/dist/commands/version-commands.d.ts.map +1 -1
  118. package/dist/commands/version-commands.js.map +1 -1
  119. package/dist/commands/worker.js +1 -1
  120. package/dist/commands/worker.js.map +1 -1
  121. package/dist/debug/server-runner.d.ts +2 -0
  122. package/dist/debug/server-runner.d.ts.map +1 -1
  123. package/dist/debug/server-runner.js +45 -4
  124. package/dist/debug/server-runner.js.map +1 -1
  125. package/dist/debug-bundle.d.ts +12 -0
  126. package/dist/debug-bundle.d.ts.map +1 -0
  127. package/dist/debug-bundle.js +23 -0
  128. package/dist/debug-bundle.js.map +1 -0
  129. package/dist/document-json.d.ts +11 -0
  130. package/dist/document-json.d.ts.map +1 -0
  131. package/dist/document-json.js +27 -0
  132. package/dist/document-json.js.map +1 -0
  133. package/dist/harness/capability-coverage.d.ts +1 -1
  134. package/dist/harness/capability-coverage.d.ts.map +1 -1
  135. package/dist/harness/capability-coverage.js +1 -1
  136. package/dist/harness/capability-coverage.js.map +1 -1
  137. package/dist/harness/capability-table.d.ts.map +1 -1
  138. package/dist/harness/capability-table.js +365 -35
  139. package/dist/harness/capability-table.js.map +1 -1
  140. package/dist/harness/changed-files.d.ts +2 -0
  141. package/dist/harness/changed-files.d.ts.map +1 -1
  142. package/dist/harness/changed-files.js +14 -0
  143. package/dist/harness/changed-files.js.map +1 -1
  144. package/dist/harness/registry.d.ts +32 -4
  145. package/dist/harness/registry.d.ts.map +1 -1
  146. package/dist/harness/registry.js +377 -33
  147. package/dist/harness/registry.js.map +1 -1
  148. package/dist/index.js +4 -3
  149. package/dist/index.js.map +1 -1
  150. package/dist/interaction-script.d.ts +23 -0
  151. package/dist/interaction-script.d.ts.map +1 -1
  152. package/dist/interaction-script.js +50 -1
  153. package/dist/interaction-script.js.map +1 -1
  154. package/dist/js-script-debug/harness.d.ts +29 -1
  155. package/dist/js-script-debug/harness.d.ts.map +1 -1
  156. package/dist/js-script-debug/harness.js +29 -72
  157. package/dist/js-script-debug/harness.js.map +1 -1
  158. package/dist/js-script-debug/target.d.ts.map +1 -1
  159. package/dist/js-script-debug/target.js +1 -24
  160. package/dist/js-script-debug/target.js.map +1 -1
  161. package/dist/local-model-interfaces.d.ts.map +1 -1
  162. package/dist/local-model-interfaces.js +1 -24
  163. package/dist/local-model-interfaces.js.map +1 -1
  164. package/dist/node-registry.d.ts +14 -0
  165. package/dist/node-registry.d.ts.map +1 -1
  166. package/dist/node-registry.js +15 -18
  167. package/dist/node-registry.js.map +1 -1
  168. package/dist/nodetool-main.d.ts +15 -0
  169. package/dist/nodetool-main.d.ts.map +1 -0
  170. package/dist/nodetool-main.js +1411 -0
  171. package/dist/nodetool-main.js.map +1 -0
  172. package/dist/nodetool.d.ts +0 -13
  173. package/dist/nodetool.d.ts.map +1 -1
  174. package/dist/nodetool.js +17 -1683
  175. package/dist/nodetool.js.map +1 -1
  176. package/dist/package-assets.d.ts +8 -0
  177. package/dist/package-assets.d.ts.map +1 -0
  178. package/dist/package-assets.js +21 -0
  179. package/dist/package-assets.js.map +1 -0
  180. package/dist/providers.d.ts +1 -1
  181. package/dist/providers.d.ts.map +1 -1
  182. package/dist/providers.js +15 -1
  183. package/dist/providers.js.map +1 -1
  184. package/dist/run-dsl.d.ts +6 -0
  185. package/dist/run-dsl.d.ts.map +1 -1
  186. package/dist/run-dsl.js +4 -1
  187. package/dist/run-dsl.js.map +1 -1
  188. package/dist/sandbox-catalog.d.ts +15 -1
  189. package/dist/sandbox-catalog.d.ts.map +1 -1
  190. package/dist/sandbox-catalog.js +58 -2
  191. package/dist/sandbox-catalog.js.map +1 -1
  192. package/dist/settings.d.ts.map +1 -1
  193. package/dist/settings.js +2 -0
  194. package/dist/settings.js.map +1 -1
  195. package/dist/sketch-debug/harness.d.ts +14 -0
  196. package/dist/sketch-debug/harness.d.ts.map +1 -1
  197. package/dist/sketch-debug/harness.js +11 -66
  198. package/dist/sketch-debug/harness.js.map +1 -1
  199. package/dist/sketch-debug/target.d.ts.map +1 -1
  200. package/dist/sketch-debug/target.js +1 -24
  201. package/dist/sketch-debug/target.js.map +1 -1
  202. package/dist/stdin.d.ts +6 -1
  203. package/dist/stdin.d.ts.map +1 -1
  204. package/dist/stdin.js +10 -1
  205. package/dist/stdin.js.map +1 -1
  206. package/dist/timeline-debug/harness.d.ts +14 -0
  207. package/dist/timeline-debug/harness.d.ts.map +1 -1
  208. package/dist/timeline-debug/harness.js +11 -66
  209. package/dist/timeline-debug/harness.js.map +1 -1
  210. package/dist/timeline-debug/target.d.ts.map +1 -1
  211. package/dist/timeline-debug/target.js +1 -24
  212. package/dist/timeline-debug/target.js.map +1 -1
  213. package/package.json +39 -35
@@ -0,0 +1,1411 @@
1
+ /**
2
+ * nodetool — Top-level CLI mirroring the Python nodetool CLI.
3
+ *
4
+ * Usage:
5
+ * nodetool info # system/env info
6
+ * nodetool serve [--host] [--port] # start TS server
7
+ * nodetool chat [--url] [--provider] # interactive chat
8
+ * nodetool workflows list/get/run
9
+ * nodetool jobs list/get
10
+ * nodetool assets list/get
11
+ * nodetool secrets list/store <key>
12
+ * nodetool settings show
13
+ */
14
+ import { program } from "commander";
15
+ import { createRequire } from "node:module";
16
+ import { fileURLToPath } from "node:url";
17
+ import { dirname, resolve } from "node:path";
18
+ import { spawnSync } from "node:child_process";
19
+ import { workflowToDsl, workflowToScript } from "@nodetool-ai/dsl";
20
+ import { initDb, migrateSqliteDb, Workflow, Asset, Secret, getSecret } from "@nodetool-ai/models";
21
+ import { readCachedHfModels, searchCachedHfModels } from "@nodetool-ai/huggingface";
22
+ import { initMasterKey } from "@nodetool-ai/security";
23
+ import { installLocalModelInterfaces } from "./local-model-interfaces.js";
24
+ import { getDefaultDbPath, getDefaultAssetsPath } from "@nodetool-ai/config";
25
+ import { ExecutionSession, isExecutionPreflightError } from "@nodetool-ai/execution";
26
+ import { NodeRegistry, createGraphNodeTypeResolver } from "@nodetool-ai/node-sdk";
27
+ import { registerBuiltinPacks } from "@nodetool-ai/base-nodes/builtin-packs";
28
+ import { CLI_LOCAL_BUILTIN_PACK_POLICY, CLI_DSL_BUILTIN_PACK_POLICY } from "./node-registry.js";
29
+ import { ProcessingContext, createLocalWorkspace, initTelemetry, onPythonBridgeCreated } from "@nodetool-ai/runtime";
30
+ import { FileStorageAdapter } from "@nodetool-ai/storage";
31
+ import { mkdirSync } from "node:fs";
32
+ import { addSupervisorOptions, createSupervisorHandle, parseSupervisorFlags, printSupervisedSummary, recordSupervisorCost, streamInterventionLines } from "./supervisor.js";
33
+ import { registerPackageCommands } from "./commands/package.js";
34
+ import { registerPackCommands } from "./commands/packs.js";
35
+ import { registerDeployCommands } from "./commands/deploy.js";
36
+ import { registerHfCommands } from "./commands/models-hf.js";
37
+ import { registerWorkerCommands } from "./commands/worker.js";
38
+ import { installWorkerActivityHeartbeat } from "@nodetool-ai/compute";
39
+ import { registerRecommendedCommand } from "./commands/models-recommended.js";
40
+ import { registerAgentCommands } from "./commands/agent.js";
41
+ import { registerDbCommands } from "./commands/db.js";
42
+ import { registerDebugCommands } from "./commands/debug.js";
43
+ import { registerAppCommands } from "./commands/app.js";
44
+ import { registerAppsCommands } from "./commands/apps.js";
45
+ import { registerValidateCommand } from "./commands/validate.js";
46
+ import { registerTimelineCommands } from "./commands/timeline.js";
47
+ import { registerSketchCommands } from "./commands/sketch.js";
48
+ import { registerJsScriptCommands } from "./commands/js-script.js";
49
+ import { registerReliabilityCommands } from "./commands/reliability.js";
50
+ import { registerNodeCommands } from "./commands/node.js";
51
+ import { registerGenerateCommand } from "./commands/generate.js";
52
+ import { registerExtensionCommands } from "./commands/extension.js";
53
+ import { registerEvalCommand } from "./commands/eval.js";
54
+ import { registerJtbdCommand } from "./commands/jtbd.js";
55
+ import { registerAffectedCommand } from "./commands/affected.js";
56
+ import { registerMcpClientCommands } from "./commands/mcp.js";
57
+ import { registerHarnessCommands } from "./commands/harness.js";
58
+ import { registerCollectionCommands } from "./commands/collections.js";
59
+ import { registerCostsCommands } from "./commands/costs.js";
60
+ import { registerErrorsCommands } from "./commands/errors.js";
61
+ import { registerGenerationsCommands } from "./commands/generations.js";
62
+ import { registerRunsCommands } from "./commands/runs.js";
63
+ import { registerGameCommands } from "./commands/game.js";
64
+ import { registerAuthCommands } from "./commands/auth.js";
65
+ import { registerTelegramCommands } from "./commands/telegram.js";
66
+ import { registerResourceReadCommands } from "./commands/resource-read.js";
67
+ import { createApiClient } from "./api-client.js";
68
+ import { listAllModels, listConfiguredProviderInfo, listOllamaModels, listProviderModels } from "./providers.js";
69
+ import { isString } from "./predicates.js";
70
+ import { printTable, asJson, readSecretValue } from "./commands/output.js";
71
+ import { printCommandError } from "./command-errors.js";
72
+ import { childExitCode } from "./child-exit.js";
73
+ const __filename = fileURLToPath(import.meta.url);
74
+ const __dirname = dirname(__filename);
75
+ /**
76
+ * The CLI's own version, read from its package.json rather than repeated here.
77
+ * A literal drifts silently: it sat at "0.1.0" across every 0.7.0-rc release,
78
+ * so `nodetool --version` told users nothing about what they had installed.
79
+ */
80
+ const CLI_VERSION = createRequire(import.meta.url)("../package.json").version;
81
+ // ---------------------------------------------------------------------------
82
+ // DB setup (for secrets commands)
83
+ // ---------------------------------------------------------------------------
84
+ // The local single-user id every direct-DB command runs as, matching the
85
+ // `workflows run` / `secrets` commands and the stdio MCP server.
86
+ import { resolveLocalSecret } from "./local-secrets.js";
87
+ const LOCAL_USER_ID = "1";
88
+ // Open the local SQLite database for a read-only command. Unlike setupDb() this
89
+ // skips master-key unlocking (no secret decryption needed to list/read rows),
90
+ // so it never emits a keychain warning. Idempotent — initDb() is a no-op once
91
+ // a connection is open.
92
+ function ensureDb() {
93
+ initDb(getDefaultDbPath());
94
+ }
95
+ async function setupDb() {
96
+ ensureDb();
97
+ // Resolve the master encryption key from keychain / env / AWS so that
98
+ // both encryption (Secret.upsert) and decryption (Secret.getDecryptedValue)
99
+ // use the same persistent key. Without this, a fresh process would
100
+ // auto-generate a one-shot key inside `getMasterKey()`, encrypt with it,
101
+ // then lose it on exit — and the next launch could not decrypt.
102
+ try {
103
+ await initMasterKey();
104
+ }
105
+ catch (err) {
106
+ const msg = err instanceof Error ? err.message : String(err);
107
+ process.stderr.write(`Could not unlock the secret store: ${msg}\n` +
108
+ `Tip: set SECRETS_MASTER_KEY or grant keychain access.\n`);
109
+ }
110
+ }
111
+ // ---------------------------------------------------------------------------
112
+ // API clients
113
+ // ---------------------------------------------------------------------------
114
+ // REST GET (text) — used for the DSL export endpoint which stays REST
115
+ // because it returns a TypeScript source string rather than JSON.
116
+ async function apiGetText(apiUrl, path) {
117
+ const res = await fetch(`${apiUrl}${path}`);
118
+ if (!res.ok)
119
+ throw new Error(`HTTP ${res.status}: ${await res.text()}`);
120
+ return res.text();
121
+ }
122
+ // This CLI's package version, stamped into exported bundle manifests.
123
+ function cliVersion() {
124
+ try {
125
+ const req = createRequire(import.meta.url);
126
+ return req("../package.json").version;
127
+ }
128
+ catch {
129
+ // Version is best-effort metadata; omit it if the file can't be read.
130
+ return undefined;
131
+ }
132
+ }
133
+ // Download asset bytes from a running server, used by the export commands to
134
+ // resolve `asset://` / `/api/storage/` (and optionally http) refs into bytes.
135
+ function makeAssetFetcher(apiUrl) {
136
+ return async (ref) => {
137
+ let url = null;
138
+ if (ref.startsWith("asset://")) {
139
+ const id = ref.slice("asset://".length);
140
+ const bareId = id.replace(/\.[^.]+$/, "");
141
+ try {
142
+ const meta = await fetch(`${apiUrl}/api/assets/${encodeURIComponent(bareId)}`);
143
+ if (meta.ok) {
144
+ const j = (await meta.json());
145
+ if (j.get_url) {
146
+ url = j.get_url.startsWith("/")
147
+ ? `${apiUrl}${j.get_url}`
148
+ : j.get_url;
149
+ }
150
+ }
151
+ }
152
+ catch {
153
+ // Metadata lookup failed — fall back to the storage route below.
154
+ }
155
+ url ??= `${apiUrl}/api/storage/${encodeURIComponent(id)}`;
156
+ }
157
+ else if (ref.includes("/api/storage/")) {
158
+ url = /^https?:\/\//.test(ref)
159
+ ? ref
160
+ : `${apiUrl}${ref.startsWith("/") ? ref : `/${ref}`}`;
161
+ }
162
+ else if (/^https?:\/\//.test(ref)) {
163
+ url = ref;
164
+ }
165
+ if (!url)
166
+ return null;
167
+ const res = await fetch(url);
168
+ if (!res.ok)
169
+ return null;
170
+ return new Uint8Array(await res.arrayBuffer());
171
+ };
172
+ }
173
+ // Resolve asset bytes from the local assets directory, so the export commands
174
+ // work by id without a running server. `asset://<key>` is tried verbatim as a
175
+ // storage key first (that's how import-bundle writes refs), then via the DB
176
+ // record to derive `<id>.<ext>` from the content type. Remote http(s) refs
177
+ // still fetch over the network.
178
+ async function makeLocalAssetFetcher() {
179
+ const { getAssetFileName } = await import("@nodetool-ai/websocket");
180
+ const storage = new FileStorageAdapter(getDefaultAssetsPath());
181
+ return async (ref) => {
182
+ if (ref.startsWith("asset://")) {
183
+ const raw = ref.slice("asset://".length);
184
+ const direct = await storage.retrieve(`/api/storage/${raw}`);
185
+ if (direct)
186
+ return direct;
187
+ const bareId = raw.replace(/\.[^.]+$/, "");
188
+ const asset = await Asset.find(LOCAL_USER_ID, bareId);
189
+ if (!asset)
190
+ return null;
191
+ const key = getAssetFileName(asset.id, asset.content_type);
192
+ return storage.retrieve(`/api/storage/${key}`);
193
+ }
194
+ if (ref.includes("/api/storage/")) {
195
+ const local = await storage.retrieve(ref);
196
+ if (local)
197
+ return local;
198
+ }
199
+ if (/^https?:\/\//.test(ref)) {
200
+ const res = await fetch(ref);
201
+ if (!res.ok)
202
+ return null;
203
+ return new Uint8Array(await res.arrayBuffer());
204
+ }
205
+ return null;
206
+ };
207
+ }
208
+ // Asset and timeline persistence for every context any command builds, here
209
+ // rather than per-entrance: `debug` wired none while `workflows run` wired
210
+ // four, so one workflow saved an image under one command and threw under the
211
+ // other. The interfaces touch the database only when a node calls them, so
212
+ // installing them before `setupDb()` is safe.
213
+ await installLocalModelInterfaces();
214
+ /**
215
+ * What to print when a run command fails. A preflight refusal already reads as
216
+ * a complete explanation — printing the error class in front of it only buries
217
+ * the secret name the user has to go set.
218
+ */
219
+ function describeRunFailure(error) {
220
+ return isExecutionPreflightError(error) ? error.message : String(error);
221
+ }
222
+ // ---------------------------------------------------------------------------
223
+ // info
224
+ // ---------------------------------------------------------------------------
225
+ program
226
+ .name("nodetool")
227
+ .description("NodeTool CLI")
228
+ .version(CLI_VERSION)
229
+ .option("--trace-file <path>", "Append every LLM/agent/workflow span as JSONL to <path>")
230
+ .option("--trace-stdout [format]", "Stream spans to stdout: 'pretty' (default) or 'json' (JSONL)")
231
+ .option("--no-trace-stdout", "Disable stdout span output (overrides NODETOOL_TRACE_STDOUT)")
232
+ .hook("preAction", async (thisCommand, actionCommand) => {
233
+ // With `--trace`, the `debug` command owns telemetry: it routes spans into
234
+ // its bundle's trace.jsonl via its own initTelemetry call. Initializing here
235
+ // first would win the one-shot init and drop that file sink, so skip it.
236
+ // Without `--trace`, fall through so the global --trace-file/--trace-stdout
237
+ // flags still work for a debug run.
238
+ if (actionCommand?.name() === "debug" && actionCommand.opts()["trace"])
239
+ return;
240
+ const opts = thisCommand.opts();
241
+ await initTelemetry({
242
+ ...(opts.traceFile && { traceFile: opts.traceFile }),
243
+ ...(opts.traceStdout !== undefined && {
244
+ stdout: parseTraceStdout(opts.traceStdout)
245
+ })
246
+ });
247
+ });
248
+ function parseTraceStdout(v) {
249
+ if (v === false)
250
+ return false;
251
+ if (v === true)
252
+ return "pretty";
253
+ if (isString(v)) {
254
+ const lower = v.toLowerCase();
255
+ if (lower === "false" || lower === "0" || lower === "no")
256
+ return false;
257
+ if (lower === "json")
258
+ return "json";
259
+ if (lower === "pretty" || lower === "true" || lower === "1")
260
+ return "pretty";
261
+ }
262
+ throw new Error(`--trace-stdout must be 'pretty' or 'json' (got ${JSON.stringify(v)})`);
263
+ }
264
+ // ---------------------------------------------------------------------------
265
+ // run — execute a TypeScript/JavaScript DSL workflow file
266
+ // ---------------------------------------------------------------------------
267
+ addSupervisorOptions(program
268
+ .command("run <dsl-file>")
269
+ .description("Run a TypeScript/JavaScript DSL workflow file")
270
+ .option("--json", "Output results as JSON (default: pretty-print)")).action(async (dslFile, opts) => {
271
+ try {
272
+ const { resolve } = await import("node:path");
273
+ const { runDslFile } = await import("./run-dsl.js");
274
+ const { NodeRegistry } = await import("@nodetool-ai/node-sdk");
275
+ registerBuiltinPacks(NodeRegistry.global, CLI_DSL_BUILTIN_PACK_POLICY);
276
+ const supervisorConfig = parseSupervisorFlags(opts);
277
+ const absolutePath = resolve(dslFile);
278
+ let results;
279
+ let interventions = [];
280
+ if (supervisorConfig) {
281
+ // The supervisor's provider key comes from the secret store, and its
282
+ // spend is written to the local ledger — both need the DB.
283
+ await setupDb();
284
+ const { runDslFileSupervised } = await import("./run-dsl-supervised.js");
285
+ const run = await runDslFileSupervised(absolutePath, supervisorConfig, opts.json === true);
286
+ results = run.results;
287
+ interventions = run.interventions;
288
+ }
289
+ else {
290
+ results = await runDslFile(absolutePath);
291
+ }
292
+ const { printRunJson, previewJson } = await import("./run-json.js");
293
+ if (opts.json) {
294
+ // A supervised run reports what the supervisor did alongside the
295
+ // outputs; an unsupervised one keeps the bare results shape.
296
+ await printRunJson(supervisorConfig ? { results, interventions } : results);
297
+ }
298
+ else {
299
+ for (const [workflowName, outputs] of Object.entries(results)) {
300
+ console.log(`\n${workflowName}:`);
301
+ for (const [key, value] of Object.entries(outputs)) {
302
+ console.log(` ${key}: ${previewJson(value)}`);
303
+ }
304
+ }
305
+ }
306
+ }
307
+ catch (e) {
308
+ console.error(describeRunFailure(e));
309
+ process.exit(1);
310
+ }
311
+ });
312
+ program
313
+ .command("info")
314
+ .description("Display system and environment information")
315
+ .option("--json", "Output as JSON")
316
+ .action((opts) => {
317
+ const apiKeys = [
318
+ "ANTHROPIC_API_KEY",
319
+ "OPENAI_API_KEY",
320
+ "GEMINI_API_KEY",
321
+ "MISTRAL_API_KEY",
322
+ "GROQ_API_KEY",
323
+ "OLLAMA_API_URL",
324
+ "SERPAPI_API_KEY",
325
+ "HF_TOKEN"
326
+ ];
327
+ const data = {
328
+ version: CLI_VERSION,
329
+ node_version: process.version,
330
+ platform: process.platform,
331
+ arch: process.arch,
332
+ api_keys: Object.fromEntries(apiKeys.map((k) => [k, process.env[k] ? "configured" : "not set"])),
333
+ environment: {
334
+ ENV: process.env["ENV"] ?? "development",
335
+ LOG_LEVEL: process.env["LOG_LEVEL"] ?? "INFO",
336
+ PORT: process.env["PORT"] ?? "7777"
337
+ }
338
+ };
339
+ if (opts.json) {
340
+ asJson(data);
341
+ return;
342
+ }
343
+ console.log("\nNodeTool System Information\n");
344
+ printTable([
345
+ { property: "Version", value: data.version },
346
+ { property: "Node.js", value: data.node_version },
347
+ { property: "Platform", value: `${data.platform}/${data.arch}` }
348
+ ]);
349
+ console.log("\nAPI Keys:");
350
+ printTable(Object.entries(data.api_keys).map(([k, v]) => ({ key: k, status: v })));
351
+ console.log("\nEnvironment:");
352
+ printTable(Object.entries(data.environment).map(([k, v]) => ({
353
+ variable: k,
354
+ value: v
355
+ })));
356
+ console.log();
357
+ });
358
+ // ---------------------------------------------------------------------------
359
+ // serve
360
+ // ---------------------------------------------------------------------------
361
+ program
362
+ .command("serve")
363
+ .description("Start the NodeTool WebSocket + HTTP server")
364
+ .option("--host <host>", "Host to bind", "127.0.0.1")
365
+ .option("--port <port>", "Port to listen on", "7777")
366
+ .action((opts) => {
367
+ const serverPath = resolve(__dirname, "../../websocket/dist/server.js");
368
+ process.env["HOST"] = opts.host;
369
+ process.env["PORT"] = opts.port;
370
+ const result = spawnSync("node", [serverPath], {
371
+ stdio: "inherit",
372
+ env: { ...process.env }
373
+ });
374
+ if (result.error)
375
+ console.error(`Could not start the server: ${result.error.message}`);
376
+ process.exit(childExitCode(result));
377
+ });
378
+ // ---------------------------------------------------------------------------
379
+ // chat
380
+ // ---------------------------------------------------------------------------
381
+ program
382
+ .command("chat")
383
+ .description("Start fullscreen chat")
384
+ .helpOption(false)
385
+ .option("-p, --provider <provider>", "LLM provider")
386
+ .option("-m, --model <model>", "Model ID")
387
+ .option("-a, --agent", "Agent mode")
388
+ .option("-u, --url <url>", "WebSocket server URL")
389
+ .option("-w, --workspace <path>", "Workspace directory")
390
+ .option("--tools <tools>", "Comma-separated enabled tools")
391
+ .allowUnknownOption()
392
+ .action((_opts, cmd) => {
393
+ const chatPath = resolve(__dirname, import.meta.url.endsWith(".ts") ? "index.ts" : "index.js");
394
+ const args = cmd.args;
395
+ const rawArgs = process.argv;
396
+ // Re-run with the chat entry point, forwarding all flags after "chat"
397
+ const chatIdx = rawArgs.indexOf("chat");
398
+ const forwarded = chatIdx >= 0 ? rawArgs.slice(chatIdx + 1) : args;
399
+ const result = spawnSync(process.execPath, [...process.execArgv, chatPath, ...forwarded], {
400
+ stdio: "inherit",
401
+ env: { ...process.env }
402
+ });
403
+ process.exit(childExitCode(result));
404
+ });
405
+ // ---------------------------------------------------------------------------
406
+ // workflows
407
+ // ---------------------------------------------------------------------------
408
+ const workflows = program
409
+ .command("workflows")
410
+ .description("Workflow management");
411
+ addSupervisorOptions(workflows
412
+ .command("run <workflow_id_or_file>")
413
+ .description("Run a workflow by ID, JSON file, or TypeScript DSL file")
414
+ .option("--params <json>", "JSON params string")
415
+ .option("--json", "Output as JSON")
416
+ .option("--asset-output-mode <mode>", "How media outputs are materialized: native | raw | data_uri | workspace | storage_url | temp_url", "native")
417
+ .option("--workspace <dir>", "Workspace directory for workspace-mode asset output (default: ./nodetool-output)")
418
+ .option("--trigger-event <json>", 'Wake a trigger node as the scheduler/webhook adapter would: \'{"node_id":"watch","payload":{"path":"/tmp/a.csv","event":"created"}}\'. ' +
419
+ "Without it a webhook, file-watch or manual trigger has no event to " +
420
+ "emit and the run stalls until its timeout — so this is the only way " +
421
+ "to exercise a trigger-driven workflow from the CLI.")).action(async (idOrFile, opts) => {
422
+ try {
423
+ const supervisorConfig = parseSupervisorFlags(opts);
424
+ await setupDb();
425
+ let graph;
426
+ let workflowId = null;
427
+ const params = opts.params
428
+ ? JSON.parse(opts.params)
429
+ : {};
430
+ // A trigger node emits from `emitTriggerEvent`, not `genProcess`, and
431
+ // only when the run carries an event addressed to it. The kernel has
432
+ // always accepted one (`RunJobRequest.trigger_event`); nothing on the
433
+ // CLI could supply it, so a webhook or file-watch workflow could be
434
+ // validated but never executed. `input_id` defaults because every
435
+ // caller would otherwise invent the same throwaway id.
436
+ const triggerEvent = opts.triggerEvent
437
+ ? (() => {
438
+ const parsed = JSON.parse(opts.triggerEvent);
439
+ if (!parsed.node_id) {
440
+ throw new Error('--trigger-event needs a "node_id" naming the trigger node to wake.');
441
+ }
442
+ return {
443
+ node_id: parsed.node_id,
444
+ payload: parsed.payload ?? {},
445
+ input_id: parsed.input_id ?? `cli-${Date.now()}`
446
+ };
447
+ })()
448
+ : null;
449
+ // Determine if argument is a file path or workflow ID
450
+ if (idOrFile.endsWith(".json") ||
451
+ idOrFile.endsWith(".ts") ||
452
+ idOrFile.endsWith(".tsx") ||
453
+ idOrFile.includes("/") ||
454
+ idOrFile.includes("\\")) {
455
+ /** A DSL/JSON workflow file: the graph, optionally wrapped. */
456
+ let raw;
457
+ if (idOrFile.endsWith(".ts") || idOrFile.endsWith(".tsx")) {
458
+ // Execute DSL file via tsx and capture JSON output
459
+ const { execFileSync } = await import("node:child_process");
460
+ const output = execFileSync("npx", ["tsx", resolve(idOrFile)], {
461
+ encoding: "utf8",
462
+ cwd: dirname(resolve(idOrFile)),
463
+ timeout: 30000
464
+ });
465
+ raw = JSON.parse(output.trim());
466
+ }
467
+ else {
468
+ const { readFileSync } = await import("node:fs");
469
+ raw = JSON.parse(readFileSync(idOrFile, "utf8"));
470
+ }
471
+ graph = raw.graph ?? raw;
472
+ workflowId = raw.workflow_id ?? raw.id ?? null;
473
+ if (raw.params)
474
+ Object.assign(params, raw.params);
475
+ }
476
+ else {
477
+ const wf = await Workflow.get(idOrFile);
478
+ if (!wf)
479
+ throw new Error(`Workflow not found: ${idOrFile}`);
480
+ graph = wf.graph;
481
+ workflowId = idOrFile;
482
+ }
483
+ if (!graph?.nodes || !graph?.edges) {
484
+ throw new Error("Invalid workflow: missing nodes or edges");
485
+ }
486
+ // Editor-only nodes (Comment, Group, Reroute) and the data→properties
487
+ // rename are handled by `ExecutionSession.create` below, which runs
488
+ // the graph through `normalizeGraph` (@nodetool-ai/execution) — no
489
+ // need to duplicate that here.
490
+ const registry = new NodeRegistry();
491
+ registerBuiltinPacks(registry, CLI_LOCAL_BUILTIN_PACK_POLICY);
492
+ const jobId = `job-${Date.now()}`;
493
+ // Resolve asset URIs (e.g. /api/storage/<key>) against the local
494
+ // assets directory, so workflows referencing stored assets run the
495
+ // same decode path the server does.
496
+ // Apply the workflow's assigned workspace (if any) so file ops and
497
+ // workspace-driving nodes land in the same directory as a server run.
498
+ const { resolveWorkflowWorkspace } = await import("@nodetool-ai/websocket");
499
+ const assignedWorkspace = workflowId
500
+ ? await resolveWorkflowWorkspace(workflowId, "1")
501
+ : null;
502
+ const ASSET_OUTPUT_MODES = [
503
+ "native",
504
+ "raw",
505
+ "data_uri",
506
+ "workspace",
507
+ "storage_url",
508
+ "temp_url"
509
+ ];
510
+ const assetOutputMode = (opts.assetOutputMode ??
511
+ "native");
512
+ if (!ASSET_OUTPUT_MODES.includes(assetOutputMode)) {
513
+ throw new Error(`Unknown --asset-output-mode "${assetOutputMode}". ` +
514
+ `Expected one of: ${ASSET_OUTPUT_MODES.join(", ")}`);
515
+ }
516
+ // `--workspace <dir>` wins, then whatever the workflow is assigned.
517
+ // `workspace` asset mode writes each output into <workspace>/assets, so
518
+ // it needs somewhere to write even when the run has no saved workflow (a
519
+ // JSON or DSL file target). Fall back to ./nodetool-output so a bare
520
+ // `workflows run file.json --asset-output-mode workspace` produces files
521
+ // in the current directory rather than failing.
522
+ const overrideWorkspaceDir = opts.workspace ??
523
+ (assignedWorkspace
524
+ ? null
525
+ : assetOutputMode === "workspace"
526
+ ? resolve(process.cwd(), "nodetool-output")
527
+ : null);
528
+ if (overrideWorkspaceDir) {
529
+ mkdirSync(overrideWorkspaceDir, { recursive: true });
530
+ }
531
+ const runWorkspace = overrideWorkspaceDir
532
+ ? createLocalWorkspace(overrideWorkspaceDir)
533
+ : assignedWorkspace;
534
+ const assetStorage = new FileStorageAdapter(getDefaultAssetsPath());
535
+ const context = new ProcessingContext({
536
+ jobId,
537
+ workflowId,
538
+ userId: "1",
539
+ secretResolver: resolveLocalSecret,
540
+ storage: assetStorage,
541
+ assetOutputMode,
542
+ workspace: runWorkspace
543
+ });
544
+ const supervisor = supervisorConfig
545
+ ? await createSupervisorHandle({
546
+ config: supervisorConfig,
547
+ context
548
+ })
549
+ : null;
550
+ console.error(`Running workflow${workflowId ? ` ${workflowId}` : ""}` +
551
+ (supervisor
552
+ ? ` supervised by ${supervisor.providerId}/${supervisor.model}`
553
+ : "") +
554
+ "...");
555
+ // ExecutionSession owns graph hydration, Python-bridge connection
556
+ // (NODETOOL_WORKER_URL/NODETOOL_WORKER_TOKEN → remote worker; unset →
557
+ // local stdio worker; pure-TS graphs get none), and executor
558
+ // resolution (registry → Python bridge → throw).
559
+ const sessionOptions = {
560
+ graph,
561
+ registry,
562
+ // Registry alone hydrates node flags but not `propertyTypes`, and
563
+ // correlation analysis reads list-ness only from that map — so a
564
+ // saved workflow (which never carries it) had every list handle
565
+ // read as non-list, and legal fan-in into one was rejected before
566
+ // any node ran. The resolver fills it from node metadata.
567
+ resolveNodeType: createGraphNodeTypeResolver(registry).resolveNodeType,
568
+ jobId,
569
+ workflowId,
570
+ params,
571
+ context
572
+ };
573
+ if (triggerEvent) {
574
+ sessionOptions.triggerEvent = triggerEvent;
575
+ }
576
+ // Message capture is retention, so it stays off unless a supervised
577
+ // run needs the stream to print its `⛨` lines as they happen.
578
+ if (supervisor) {
579
+ sessionOptions.supervisor = supervisor.handle;
580
+ sessionOptions.captureMessages = true;
581
+ }
582
+ const session = await ExecutionSession.create(sessionOptions);
583
+ const interventionLines = supervisor
584
+ ? streamInterventionLines(session.messages)
585
+ : Promise.resolve();
586
+ const result = await session.result;
587
+ await interventionLines;
588
+ supervisor?.handle.close();
589
+ const interventions = result.interventions ?? [];
590
+ if (supervisor && interventions.length > 0) {
591
+ await recordSupervisorCost({
592
+ interventions,
593
+ jobId,
594
+ workflowId,
595
+ userId: "1",
596
+ providerId: supervisor.providerId,
597
+ model: supervisor.model
598
+ });
599
+ }
600
+ const { printRunJson, previewJson } = await import("./run-json.js");
601
+ if (opts.json) {
602
+ await printRunJson(result, {
603
+ outputDir: resolve(process.cwd(), "nodetool-output", jobId)
604
+ });
605
+ }
606
+ else {
607
+ console.log(`Status: ${result.status}`);
608
+ if (result.error)
609
+ console.error(`Error: ${result.error}`);
610
+ for (const [nodeId, outputs] of Object.entries(result.outputs ?? {})) {
611
+ if (Array.isArray(outputs) && outputs.length > 0) {
612
+ console.log(`\nNode ${nodeId}:`);
613
+ for (const out of outputs) {
614
+ console.log(` ${previewJson(out, 200)}`);
615
+ }
616
+ }
617
+ }
618
+ printSupervisedSummary(interventions);
619
+ }
620
+ process.exit(result.status === "completed" ? 0 : 1);
621
+ }
622
+ catch (e) {
623
+ console.error(describeRunFailure(e));
624
+ process.exit(1);
625
+ }
626
+ });
627
+ workflows
628
+ .command("export-script <workflow_id_or_file>")
629
+ .description("Convert a workflow into a JavaScript script that calls each node in order (local DB by id, or a JSON file)")
630
+ .option("-t, --target <target>", "sandbox (a JS script document or Code node body) or node (a standalone Node.js .mjs)", "sandbox")
631
+ .option("-o, --output <file>", "Write the script to a file")
632
+ .action(async (idOrFile, opts) => {
633
+ try {
634
+ if (opts.target !== "sandbox" && opts.target !== "node") {
635
+ throw new Error(`Unknown target "${opts.target}": use "sandbox" or "node"`);
636
+ }
637
+ let graph;
638
+ let name;
639
+ if (idOrFile.endsWith(".json") ||
640
+ idOrFile.includes("/") ||
641
+ idOrFile.includes("\\")) {
642
+ const { readFileSync } = await import("node:fs");
643
+ const raw = JSON.parse(readFileSync(idOrFile, "utf8"));
644
+ graph = (raw.graph ?? raw);
645
+ name = isString(raw.name) ? raw.name : null;
646
+ }
647
+ else {
648
+ ensureDb();
649
+ const wf = await Workflow.find(LOCAL_USER_ID, idOrFile);
650
+ if (!wf)
651
+ throw new Error(`Workflow not found: ${idOrFile}`);
652
+ graph = wf.getGraph();
653
+ name = isString(wf.name) ? wf.name : null;
654
+ }
655
+ const script = workflowToScript(graph, {
656
+ target: opts.target,
657
+ workflowName: name
658
+ });
659
+ for (const issue of script.unsupported) {
660
+ console.error(`warning: ${issue.node_type} (${issue.node_id}) ${issue.message}`);
661
+ }
662
+ if (opts.output) {
663
+ const { writeFile } = await import("node:fs/promises");
664
+ await writeFile(opts.output, script.code, "utf8");
665
+ console.log(opts.output);
666
+ return;
667
+ }
668
+ console.log(script.code);
669
+ }
670
+ catch (e) {
671
+ printCommandError(e);
672
+ process.exit(1);
673
+ }
674
+ });
675
+ workflows
676
+ .command("export-dsl <workflow_id_or_file>")
677
+ .description("Export a workflow as TypeScript DSL code (local DB by id; --api-url for remote)")
678
+ .option("--api-url <url>", "Fetch the workflow from a remote server instead of the local database", process.env["NODETOOL_API_URL"])
679
+ .option("-o, --output <file>", "Write the exported DSL to a file")
680
+ .action(async (idOrFile, opts) => {
681
+ try {
682
+ let source;
683
+ if (idOrFile.endsWith(".json") ||
684
+ idOrFile.includes("/") ||
685
+ idOrFile.includes("\\")) {
686
+ const { readFileSync } = await import("node:fs");
687
+ const raw = JSON.parse(readFileSync(idOrFile, "utf8"));
688
+ const graph = (raw.graph ?? raw);
689
+ source = workflowToDsl(graph, {
690
+ workflowName: isString(raw.name) ? raw.name : null
691
+ });
692
+ }
693
+ else if (opts.apiUrl) {
694
+ source = await apiGetText(opts.apiUrl, `/api/workflows/${idOrFile}/dsl-export`);
695
+ }
696
+ else {
697
+ ensureDb();
698
+ const wf = await Workflow.find(LOCAL_USER_ID, idOrFile);
699
+ if (!wf)
700
+ throw new Error(`Workflow not found: ${idOrFile}`);
701
+ const graph = wf.getGraph();
702
+ source = workflowToDsl(graph, {
703
+ workflowName: isString(wf.name) ? wf.name : null
704
+ });
705
+ }
706
+ if (opts.output) {
707
+ const { writeFile } = await import("node:fs/promises");
708
+ await writeFile(opts.output, source, "utf8");
709
+ console.log(opts.output);
710
+ return;
711
+ }
712
+ console.log(source);
713
+ }
714
+ catch (e) {
715
+ printCommandError(e);
716
+ process.exit(1);
717
+ }
718
+ });
719
+ workflows
720
+ .command("export-example <workflow_id_or_file>")
721
+ .description("Export a workflow as a shipped template: materialize its assets into the " +
722
+ "package's constant asset dir (package:// refs) and write the example JSON")
723
+ .option("--api-url <url>", "Fetch the workflow and asset bytes from a remote server instead of the local DB/assets", process.env["NODETOOL_API_URL"])
724
+ .option("--package <name>", "Owning package", "nodetool-base")
725
+ .option("--assets-dir <dir>", "Root holding <package>/<file> constant assets (defaults to the monorepo base-nodes assets dir)")
726
+ .option("--examples-dir <dir>", "Directory the example JSON is written under, as <dir>/<package>/<name>.json")
727
+ .option("-o, --output <file>", "Write the example JSON to this exact path")
728
+ .option("--include-remote", "Also materialize http(s) and local-file refs (off by default)")
729
+ .action(async (idOrFile, opts) => {
730
+ try {
731
+ const { readFileSync } = await import("node:fs");
732
+ const { mkdir, writeFile } = await import("node:fs/promises");
733
+ const { join } = await import("node:path");
734
+ const { materializeWorkflowConstantAssets } = await import("@nodetool-ai/websocket");
735
+ let name = "";
736
+ let description = "";
737
+ let tags = [];
738
+ let graph;
739
+ const isFile = idOrFile.endsWith(".json") ||
740
+ idOrFile.includes("/") ||
741
+ idOrFile.includes("\\");
742
+ if (isFile) {
743
+ const raw = JSON.parse(readFileSync(idOrFile, "utf8"));
744
+ name = isString(raw.name) ? raw.name : "workflow";
745
+ description =
746
+ isString(raw.description) ? raw.description : "";
747
+ tags = Array.isArray(raw.tags)
748
+ ? raw.tags.filter((t) => typeof t === "string")
749
+ : [];
750
+ graph = (raw.graph ?? raw);
751
+ }
752
+ else if (opts.apiUrl) {
753
+ const client = createApiClient(opts.apiUrl);
754
+ const wf = (await client.workflows.get.query({
755
+ id: idOrFile
756
+ }));
757
+ name = isString(wf.name) ? wf.name : "workflow";
758
+ description =
759
+ isString(wf.description) ? wf.description : "";
760
+ tags = Array.isArray(wf.tags)
761
+ ? wf.tags.filter((t) => typeof t === "string")
762
+ : [];
763
+ graph = wf.graph;
764
+ }
765
+ else {
766
+ ensureDb();
767
+ const wf = await Workflow.find(LOCAL_USER_ID, idOrFile);
768
+ if (!wf)
769
+ throw new Error(`Workflow not found: ${idOrFile}`);
770
+ name = isString(wf.name) ? wf.name : "workflow";
771
+ description =
772
+ isString(wf.description) ? wf.description : "";
773
+ tags = Array.isArray(wf.tags)
774
+ ? wf.tags.filter((t) => typeof t === "string")
775
+ : [];
776
+ graph = wf.getGraph();
777
+ }
778
+ if (!graph?.nodes) {
779
+ throw new Error("Workflow has no graph to export");
780
+ }
781
+ const repoRoot = resolve(__dirname, "..", "..", "..");
782
+ const baseNodesDir = join(repoRoot, "packages", "base-nodes", "nodetool");
783
+ const assetsRoot = opts.assetsDir ?? join(baseNodesDir, "assets");
784
+ const examplesDir = opts.examplesDir ?? join(baseNodesDir, "examples");
785
+ const fetchAssetBytes = opts.apiUrl
786
+ ? makeAssetFetcher(opts.apiUrl.replace(/\/+$/, ""))
787
+ : await makeLocalAssetFetcher();
788
+ const materializeOptions = {
789
+ packageName: opts.package,
790
+ assetsRoot,
791
+ fetchAssetBytes
792
+ };
793
+ if (opts.includeRemote) {
794
+ materializeOptions.includeRemote = true;
795
+ }
796
+ const result = await materializeWorkflowConstantAssets(graph, materializeOptions);
797
+ const slug = name
798
+ .toLowerCase()
799
+ .replace(/[^a-z0-9]+/g, "-")
800
+ .replace(/^-+|-+$/g, "");
801
+ const example = {
802
+ id: slug || "workflow",
803
+ access: "public",
804
+ name,
805
+ description,
806
+ tags,
807
+ package_name: opts.package,
808
+ graph: result.graph
809
+ };
810
+ // Sanitize the on-disk filename separately from the display name so
811
+ // names with path separators can't escape the examples directory.
812
+ const safeFileName = name.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._]+/, "") ||
813
+ "workflow";
814
+ const outPath = opts.output ??
815
+ join(examplesDir, opts.package, `${safeFileName}.json`);
816
+ await mkdir(dirname(outPath), { recursive: true });
817
+ await writeFile(outPath, JSON.stringify(example, null, 2) + "\n", "utf8");
818
+ for (const a of result.exported) {
819
+ console.error(` asset ${a.source} → ${a.packageUri} (${a.byteLength} bytes)`);
820
+ }
821
+ for (const s of result.skipped) {
822
+ console.error(` warning: could not resolve asset ${s} (left as-is)`);
823
+ }
824
+ console.log(outPath);
825
+ }
826
+ catch (e) {
827
+ printCommandError(e);
828
+ process.exit(1);
829
+ }
830
+ });
831
+ workflows
832
+ .command("export-bundle <workflow_id_or_file...>")
833
+ .description("Export one or more workflows as a portable .nodetool bundle (zip): the " +
834
+ "graphs plus the bytes of every asset they reference, in a single file")
835
+ .option("--api-url <url>", "Fetch the workflow and asset bytes from a remote server instead of the local DB/assets", process.env["NODETOOL_API_URL"])
836
+ .option("-o, --output <file>", "Output path (default: <name>.nodetool)")
837
+ .option("--include-remote", "Also embed http(s) and local-file refs (off by default)")
838
+ .action(async (idsOrFiles, opts) => {
839
+ try {
840
+ const { readFileSync } = await import("node:fs");
841
+ const { writeFile } = await import("node:fs/promises");
842
+ const { packWorkflowsBundle } = await import("@nodetool-ai/websocket");
843
+ const toBundleWf = (raw) => ({
844
+ name: isString(raw.name) ? raw.name : "workflow",
845
+ description: isString(raw.description) ? raw.description : "",
846
+ tags: Array.isArray(raw.tags)
847
+ ? raw.tags.filter((t) => typeof t === "string")
848
+ : [],
849
+ run_mode: raw.run_mode ?? null,
850
+ settings: raw.settings ?? null,
851
+ graph: (raw.graph ?? raw)
852
+ });
853
+ const useServer = Boolean(opts.apiUrl);
854
+ const apiUrl = opts.apiUrl?.replace(/\/+$/, "") ?? "";
855
+ if (!useServer)
856
+ ensureDb();
857
+ const workflowsToPack = [];
858
+ for (const idOrFile of idsOrFiles) {
859
+ const isFile = idOrFile.endsWith(".json") ||
860
+ idOrFile.includes("/") ||
861
+ idOrFile.includes("\\");
862
+ let raw;
863
+ if (isFile) {
864
+ raw = JSON.parse(readFileSync(idOrFile, "utf8"));
865
+ }
866
+ else if (useServer) {
867
+ raw = (await createApiClient(apiUrl).workflows.get.query({
868
+ id: idOrFile
869
+ }));
870
+ }
871
+ else {
872
+ const found = await Workflow.find(LOCAL_USER_ID, idOrFile);
873
+ if (!found)
874
+ throw new Error(`Workflow not found: ${idOrFile}`);
875
+ raw = { ...found, graph: found.getGraph() };
876
+ }
877
+ const wf = toBundleWf(raw);
878
+ if (!wf.graph?.nodes) {
879
+ throw new Error(`Workflow '${idOrFile}' has no graph to export`);
880
+ }
881
+ workflowsToPack.push(wf);
882
+ }
883
+ const packOptions = {
884
+ workflows: workflowsToPack,
885
+ fetchAssetBytes: useServer
886
+ ? makeAssetFetcher(apiUrl)
887
+ : await makeLocalAssetFetcher(),
888
+ nodetoolVersion: cliVersion()
889
+ };
890
+ if (opts.includeRemote) {
891
+ packOptions.includeRemote = true;
892
+ }
893
+ const { bytes, manifest, skipped } = await packWorkflowsBundle(packOptions);
894
+ const defaultBase = workflowsToPack.length === 1
895
+ ? workflowsToPack[0].name.replace(/[^A-Za-z0-9._-]+/g, "_")
896
+ : `${workflowsToPack.length}-workflows`;
897
+ const outPath = opts.output ?? `${defaultBase}.nodetool`;
898
+ await writeFile(outPath, bytes);
899
+ for (const a of manifest.assets) {
900
+ console.error(` embedded ${a.file} (${a.bytes} bytes)`);
901
+ }
902
+ for (const s of skipped) {
903
+ console.error(` warning: could not resolve asset ${s} (left as-is)`);
904
+ }
905
+ console.error(` bundled ${manifest.workflows.length} workflow(s), ${manifest.assets.length} asset(s)`);
906
+ console.log(outPath);
907
+ }
908
+ catch (e) {
909
+ printCommandError(e);
910
+ process.exit(1);
911
+ }
912
+ });
913
+ workflows
914
+ .command("import-bundle <bundle_file>")
915
+ .description("Import a .nodetool bundle into the local library: store its assets and " +
916
+ "create the workflows with refs rewritten to the imported assets")
917
+ .option("--json", "Output the created workflows as JSON")
918
+ .action(async (bundleFile, opts) => {
919
+ try {
920
+ const { readFileSync } = await import("node:fs");
921
+ const { randomUUID } = await import("node:crypto");
922
+ const { extname } = await import("node:path");
923
+ const { importWorkflowBundle } = await import("@nodetool-ai/websocket");
924
+ await setupDb();
925
+ const storage = new FileStorageAdapter(getDefaultAssetsPath());
926
+ const zip = new Uint8Array(readFileSync(bundleFile));
927
+ const result = await importWorkflowBundle(zip, {
928
+ storeAsset: async ({ bytes, fileName, contentType }) => {
929
+ const id = randomUUID();
930
+ const key = `${id}${extname(fileName)}`;
931
+ await storage.store(key, bytes, contentType);
932
+ return { uri: `asset://${key}`, assetId: id };
933
+ }
934
+ });
935
+ const created = [];
936
+ for (const wf of result.workflows) {
937
+ created.push(await Workflow.create({
938
+ user_id: "1",
939
+ name: wf.name,
940
+ description: wf.description ?? "",
941
+ tags: wf.tags ?? [],
942
+ access: "private",
943
+ graph: wf.graph,
944
+ run_mode: wf.run_mode ?? "workflow",
945
+ settings: wf.settings ?? null
946
+ }));
947
+ }
948
+ for (const s of result.missing) {
949
+ console.error(` warning: bundle asset ${s} was missing from the archive`);
950
+ }
951
+ for (const m of result.checksumMismatches) {
952
+ console.error(` warning: ${m}`);
953
+ }
954
+ console.error(` imported ${created.length} workflow(s) and ${result.imported.length} asset(s) into local storage`);
955
+ if (opts.json) {
956
+ asJson(created);
957
+ }
958
+ else {
959
+ for (const c of created) {
960
+ console.log(String(c.id));
961
+ }
962
+ }
963
+ }
964
+ catch (e) {
965
+ printCommandError(e, opts.json);
966
+ process.exit(1);
967
+ }
968
+ });
969
+ // ---------------------------------------------------------------------------
970
+ // jobs / assets — the read commands are registered from commands/resource-read.ts
971
+ // ---------------------------------------------------------------------------
972
+ const jobs = program.command("jobs").description("Job management");
973
+ const assets = program.command("assets").description("Asset management");
974
+ registerResourceReadCommands({ workflows, jobs, assets }, { ensureDb, localUserId: LOCAL_USER_ID });
975
+ const models = program.command("models").description("Model management");
976
+ const modelKinds = [
977
+ "llm",
978
+ "image",
979
+ "tts",
980
+ "asr",
981
+ "video",
982
+ "embedding"
983
+ ];
984
+ function modelRow(m) {
985
+ return {
986
+ id: m["id"],
987
+ name: m["name"],
988
+ provider: m["provider"] ?? "",
989
+ type: m["type"] ?? "",
990
+ repo_id: m["repo_id"] ?? ""
991
+ };
992
+ }
993
+ models
994
+ .command("list")
995
+ .description("List all models (recommended + provider + HF cached); local by default, --api-url for remote")
996
+ .option("--api-url <url>", "Query a remote server instead of local providers/cache", process.env["NODETOOL_API_URL"])
997
+ .option("--json", "Output as JSON")
998
+ .action(async (opts) => {
999
+ try {
1000
+ let rows;
1001
+ if (opts.apiUrl) {
1002
+ const client = createApiClient(opts.apiUrl);
1003
+ rows = await client.models.all.query();
1004
+ }
1005
+ else {
1006
+ await setupDb();
1007
+ rows = await listAllModels();
1008
+ }
1009
+ if (opts.json) {
1010
+ asJson(rows);
1011
+ return;
1012
+ }
1013
+ printTable(rows.map(modelRow));
1014
+ }
1015
+ catch (e) {
1016
+ printCommandError(e, opts.json);
1017
+ process.exit(1);
1018
+ }
1019
+ });
1020
+ models
1021
+ .command("providers")
1022
+ .description("List configured providers and their capabilities")
1023
+ .option("--json", "Output as JSON")
1024
+ .action(async (opts) => {
1025
+ await setupDb();
1026
+ try {
1027
+ const data = await listConfiguredProviderInfo();
1028
+ if (opts.json) {
1029
+ asJson(data);
1030
+ return;
1031
+ }
1032
+ printTable(data.map((p) => ({
1033
+ provider: p.provider,
1034
+ capabilities: p.capabilities.join(", ")
1035
+ })));
1036
+ }
1037
+ catch (e) {
1038
+ printCommandError(e, opts.json);
1039
+ process.exit(1);
1040
+ }
1041
+ });
1042
+ registerRecommendedCommand(models);
1043
+ registerHfCommands(models);
1044
+ models
1045
+ .command("ollama")
1046
+ .description("List Ollama models (queries the local daemon; --api-url for remote)")
1047
+ .option("--api-url <url>", "Query a remote server instead of the local Ollama daemon", process.env["NODETOOL_API_URL"])
1048
+ .option("--json", "Output as JSON")
1049
+ .action(async (opts) => {
1050
+ try {
1051
+ let rows;
1052
+ if (opts.apiUrl) {
1053
+ const client = createApiClient(opts.apiUrl);
1054
+ rows = await client.models.ollama.query();
1055
+ }
1056
+ else {
1057
+ await setupDb();
1058
+ rows = await listOllamaModels();
1059
+ }
1060
+ if (opts.json) {
1061
+ asJson(rows);
1062
+ return;
1063
+ }
1064
+ printTable(rows.map(modelRow));
1065
+ }
1066
+ catch (e) {
1067
+ printCommandError(e, opts.json);
1068
+ process.exit(1);
1069
+ }
1070
+ });
1071
+ models
1072
+ .command("huggingface")
1073
+ .description("List HuggingFace cached models (scans the local cache; --api-url for remote)")
1074
+ .option("--api-url <url>", "Query a remote server instead of the local HuggingFace cache", process.env["NODETOOL_API_URL"])
1075
+ .option("--query <q>", "Search query")
1076
+ .option("--type <t>", "Filter by HF model type")
1077
+ .option("--json", "Output as JSON")
1078
+ .action(async (opts) => {
1079
+ try {
1080
+ let rows;
1081
+ if (opts.apiUrl) {
1082
+ const client = createApiClient(opts.apiUrl);
1083
+ if (opts.query || opts.type) {
1084
+ const search = {};
1085
+ if (opts.query) {
1086
+ search.query = String(opts.query);
1087
+ }
1088
+ if (opts.type) {
1089
+ search.type = String(opts.type);
1090
+ }
1091
+ rows = await client.models.huggingfaceSearch.query(search);
1092
+ }
1093
+ else {
1094
+ rows = await client.models.huggingfaceList.query();
1095
+ }
1096
+ }
1097
+ else if (opts.query || opts.type) {
1098
+ // Wrap a bare query in wildcards so it matches as a substring, the same
1099
+ // normalization the server's huggingfaceSearch applies.
1100
+ const rawQuery = opts.query ? String(opts.query) : undefined;
1101
+ const query = rawQuery && !rawQuery.includes("*") ? `*${rawQuery}*` : rawQuery;
1102
+ rows = await searchCachedHfModels(query ? [query] : undefined, opts.type ? [String(opts.type)] : undefined);
1103
+ }
1104
+ else {
1105
+ rows = await readCachedHfModels();
1106
+ }
1107
+ if (opts.json) {
1108
+ asJson(rows);
1109
+ return;
1110
+ }
1111
+ printTable(rows.map(modelRow));
1112
+ }
1113
+ catch (e) {
1114
+ printCommandError(e, opts.json);
1115
+ process.exit(1);
1116
+ }
1117
+ });
1118
+ models
1119
+ .command("by-provider <provider>")
1120
+ .description(`List models for a provider. --kind one of: ${modelKinds.join(", ")}`)
1121
+ .option("--kind <kind>", "Model kind", "llm")
1122
+ .option("--json", "Output as JSON")
1123
+ .action(async (provider, opts) => {
1124
+ const kind = opts.kind;
1125
+ if (!modelKinds.includes(kind)) {
1126
+ console.error(`Invalid --kind '${opts.kind}'. Must be one of: ${modelKinds.join(", ")}`);
1127
+ process.exit(1);
1128
+ }
1129
+ await setupDb();
1130
+ try {
1131
+ const rows = await listProviderModels(provider, kind);
1132
+ if (opts.json) {
1133
+ asJson(rows);
1134
+ return;
1135
+ }
1136
+ printTable(rows.map(modelRow));
1137
+ }
1138
+ catch (e) {
1139
+ printCommandError(e, opts.json);
1140
+ process.exit(1);
1141
+ }
1142
+ });
1143
+ // ---------------------------------------------------------------------------
1144
+ // storage
1145
+ // ---------------------------------------------------------------------------
1146
+ const storage = program
1147
+ .command("storage")
1148
+ .description("Maintain the asset storage backend");
1149
+ storage
1150
+ .command("migrate-keys")
1151
+ .description("Move asset objects under their owner's prefix (<userId>/<assetId>.<ext>)")
1152
+ .option("--dry-run", "Report what would move without writing anything")
1153
+ .option("--user-id <id>", "Migrate only this user's objects")
1154
+ .option("--json", "Output the report as JSON")
1155
+ .action(async (opts) => {
1156
+ await setupDb();
1157
+ const { migrateStorageKeys, formatMigrateKeysReport } = await import("./commands/storage.js");
1158
+ try {
1159
+ const migrateOptions = {
1160
+ dryRun: Boolean(opts.dryRun)
1161
+ };
1162
+ if (opts.userId) {
1163
+ migrateOptions.userId = opts.userId;
1164
+ }
1165
+ const report = await migrateStorageKeys(migrateOptions);
1166
+ if (opts.json) {
1167
+ console.log(JSON.stringify(report, null, 2));
1168
+ }
1169
+ else {
1170
+ console.log(formatMigrateKeysReport(report, Boolean(opts.dryRun)));
1171
+ }
1172
+ if (report.failed > 0)
1173
+ process.exit(1);
1174
+ }
1175
+ catch (e) {
1176
+ printCommandError(e, opts.json);
1177
+ process.exit(1);
1178
+ }
1179
+ });
1180
+ workflows
1181
+ .command("migrate-code-inputs")
1182
+ .description("Rewrite saved Code node bodies to read declared inputs off `inputs`")
1183
+ .option("--dry-run", "Report what would change without writing anything")
1184
+ .option("--user-id <id>", "Migrate only this user's workflows")
1185
+ .option("--json", "Output the report as JSON")
1186
+ .action(async (opts) => {
1187
+ await setupDb();
1188
+ const { migrateCodeInputs, formatMigrateCodeInputsReport } = await import("./commands/migrate-code-inputs.js");
1189
+ try {
1190
+ const migrateOptions = {
1191
+ dryRun: Boolean(opts.dryRun)
1192
+ };
1193
+ if (opts.userId) {
1194
+ migrateOptions.userId = opts.userId;
1195
+ }
1196
+ const report = await migrateCodeInputs(migrateOptions);
1197
+ if (opts.json) {
1198
+ console.log(JSON.stringify(report, null, 2));
1199
+ }
1200
+ else {
1201
+ console.log(formatMigrateCodeInputsReport(report, Boolean(opts.dryRun)));
1202
+ }
1203
+ if (report.failed > 0)
1204
+ process.exit(1);
1205
+ }
1206
+ catch (e) {
1207
+ printCommandError(e, opts.json);
1208
+ process.exit(1);
1209
+ }
1210
+ });
1211
+ // ---------------------------------------------------------------------------
1212
+ // secrets
1213
+ // ---------------------------------------------------------------------------
1214
+ const secrets = program
1215
+ .command("secrets")
1216
+ .description("Manage encrypted secrets");
1217
+ secrets
1218
+ .command("list")
1219
+ .description("List stored secret keys (values are never shown)")
1220
+ .option("--user-id <id>", "User ID", "1")
1221
+ .action(async (opts) => {
1222
+ await setupDb();
1223
+ try {
1224
+ const [items] = await Secret.listForUser(opts.userId, 100);
1225
+ if (items.length === 0) {
1226
+ console.log("No secrets stored.");
1227
+ return;
1228
+ }
1229
+ printTable(items.map((s) => ({ key: s.key, updated_at: s.updated_at ?? "" })));
1230
+ }
1231
+ catch (e) {
1232
+ printCommandError(e);
1233
+ process.exit(1);
1234
+ }
1235
+ });
1236
+ secrets
1237
+ .command("store <key>")
1238
+ .description("Store or update a secret (prompts for value)")
1239
+ .option("--user-id <id>", "User ID", "1")
1240
+ .option("--description <desc>", "Optional description")
1241
+ .action(async (key, opts) => {
1242
+ await setupDb();
1243
+ try {
1244
+ // Hidden on a TTY: an echoed value stays in the terminal scrollback.
1245
+ const value = await readSecretValue(`Enter value for '${key}': `);
1246
+ if (!value)
1247
+ throw new Error(`No value given for '${key}'; nothing stored.`);
1248
+ await Secret.upsert({
1249
+ userId: opts.userId,
1250
+ key,
1251
+ value,
1252
+ description: opts.description
1253
+ });
1254
+ console.log(`Secret '${key}' stored.`);
1255
+ }
1256
+ catch (e) {
1257
+ printCommandError(e);
1258
+ process.exit(1);
1259
+ }
1260
+ });
1261
+ secrets
1262
+ .command("get <key>")
1263
+ .description("Retrieve and print a secret value")
1264
+ .option("--user-id <id>", "User ID", "1")
1265
+ .action(async (key, opts) => {
1266
+ await setupDb();
1267
+ try {
1268
+ const value = await getSecret(key, opts.userId);
1269
+ if (value == null) {
1270
+ console.error(`Secret '${key}' not found.`);
1271
+ process.exit(1);
1272
+ }
1273
+ console.log(value);
1274
+ }
1275
+ catch (e) {
1276
+ printCommandError(e);
1277
+ process.exit(1);
1278
+ }
1279
+ });
1280
+ // ---------------------------------------------------------------------------
1281
+ // settings
1282
+ // ---------------------------------------------------------------------------
1283
+ const settings = program
1284
+ .command("settings")
1285
+ .description("View configuration settings");
1286
+ settings
1287
+ .command("show")
1288
+ .description("Show current settings from environment")
1289
+ .option("--json", "Output as JSON")
1290
+ .action((opts) => {
1291
+ const vars = [
1292
+ "ENV",
1293
+ "LOG_LEVEL",
1294
+ "PORT",
1295
+ "HOST",
1296
+ "DB_PATH",
1297
+ "NODETOOL_API_URL",
1298
+ "ANTHROPIC_API_KEY",
1299
+ "OPENAI_API_KEY",
1300
+ "GEMINI_API_KEY",
1301
+ "MISTRAL_API_KEY",
1302
+ "GROQ_API_KEY",
1303
+ "OLLAMA_API_URL",
1304
+ "SERPAPI_API_KEY",
1305
+ "HF_TOKEN",
1306
+ "VECTORSTORE_DB_PATH",
1307
+ "ASSET_BUCKET",
1308
+ "S3_ENDPOINT_URL"
1309
+ ];
1310
+ const data = Object.fromEntries(vars.map((k) => [
1311
+ k,
1312
+ process.env[k]
1313
+ ? k.endsWith("KEY") || k.endsWith("TOKEN")
1314
+ ? "***"
1315
+ : process.env[k]
1316
+ : ""
1317
+ ]));
1318
+ if (opts.json) {
1319
+ asJson(data);
1320
+ return;
1321
+ }
1322
+ printTable(Object.entries(data).map(([variable, value]) => ({ variable, value })));
1323
+ });
1324
+ // ---------------------------------------------------------------------------
1325
+ // mcp
1326
+ // ---------------------------------------------------------------------------
1327
+ const mcp = program
1328
+ .command("mcp")
1329
+ .description("Use NodeTool as an MCP server from Claude Code, Codex, OpenCode, or any MCP client");
1330
+ registerMcpClientCommands(mcp);
1331
+ mcp
1332
+ .command("serve")
1333
+ .description("Run the NodeTool MCP server over stdio for an external agent " +
1334
+ "(Claude Code, Codex, …). All logging goes to stderr; stdout is the " +
1335
+ "MCP protocol channel.")
1336
+ .action(async () => {
1337
+ try {
1338
+ const { createMcpServer, createMcpStdioTransport, forwardMcpStdioToLocalServer } = await import("@nodetool-ai/websocket");
1339
+ if (await forwardMcpStdioToLocalServer()) {
1340
+ process.stderr.write("NodeTool MCP forwarding to the local API server.\n");
1341
+ return;
1342
+ }
1343
+ await setupDb();
1344
+ // A local TS-node registry powers list_nodes / search_nodes /
1345
+ // validate_workflow without spinning up a Python worker.
1346
+ const registry = new NodeRegistry();
1347
+ registerBuiltinPacks(registry, CLI_LOCAL_BUILTIN_PACK_POLICY);
1348
+ // stdio serves exactly one local user; "1" is the local single-user id.
1349
+ const server = createMcpServer({
1350
+ registry,
1351
+ agentToolsScope: { userId: "1", source: "stdio-local" }
1352
+ });
1353
+ const transport = createMcpStdioTransport();
1354
+ await server.connect(transport);
1355
+ process.stderr.write("NodeTool MCP server ready on stdio.\n");
1356
+ // The stdio transport keeps the event loop alive until the client
1357
+ // closes the connection.
1358
+ }
1359
+ catch (e) {
1360
+ printCommandError(e);
1361
+ process.exit(1);
1362
+ }
1363
+ });
1364
+ // ---------------------------------------------------------------------------
1365
+ // package
1366
+ // ---------------------------------------------------------------------------
1367
+ registerPackageCommands(program);
1368
+ registerPackCommands(program);
1369
+ registerWorkerCommands(program);
1370
+ // Any command that opens a remote Python bridge keeps the attached worker's
1371
+ // idle clock fresh, so the reaper doesn't pause a GPU that is mid-job.
1372
+ installWorkerActivityHeartbeat(onPythonBridgeCreated);
1373
+ // ---------------------------------------------------------------------------
1374
+ // deploy — registered from commands/deploy.ts
1375
+ // ---------------------------------------------------------------------------
1376
+ registerDeployCommands(program);
1377
+ registerAgentCommands(program);
1378
+ registerDbCommands(program);
1379
+ registerDebugCommands(program);
1380
+ registerAppCommands(program);
1381
+ registerAppsCommands(program);
1382
+ registerValidateCommand(program);
1383
+ registerTimelineCommands(program);
1384
+ registerSketchCommands(program);
1385
+ registerGameCommands(program);
1386
+ registerJsScriptCommands(program);
1387
+ registerReliabilityCommands(program);
1388
+ registerNodeCommands(program);
1389
+ registerGenerateCommand(program);
1390
+ registerExtensionCommands(program);
1391
+ registerEvalCommand(program);
1392
+ registerJtbdCommand(program, setupDb);
1393
+ registerAffectedCommand(program);
1394
+ registerHarnessCommands(program);
1395
+ registerCollectionCommands(program);
1396
+ registerCostsCommands(program);
1397
+ registerErrorsCommands(program);
1398
+ registerGenerationsCommands(program);
1399
+ registerRunsCommands(program, {
1400
+ ensureDb: async () => {
1401
+ const dbPath = getDefaultDbPath();
1402
+ await migrateSqliteDb(dbPath);
1403
+ initDb(dbPath);
1404
+ },
1405
+ localUserId: LOCAL_USER_ID
1406
+ });
1407
+ registerAuthCommands(program);
1408
+ registerTelegramCommands(program);
1409
+ // ---------------------------------------------------------------------------
1410
+ program.parse();
1411
+ //# sourceMappingURL=nodetool-main.js.map