@alicloud/autowonder 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js ADDED
@@ -0,0 +1,1113 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { execFileSync, spawn, spawnSync } = require("child_process");
5
+ const crypto = require("crypto");
6
+ const path = require("path");
7
+ const fs = require("fs");
8
+ const os = require("os");
9
+ const https = require("https");
10
+ const http = require("http");
11
+
12
+ const { ensureDir, error, log, resolveUserPath } = require("./shared");
13
+ const {
14
+ ensureQoderReady,
15
+ findQoderExecutable,
16
+ isQoderFamilyProvider,
17
+ } = require("./qoder-bootstrap");
18
+ const { fetchExecutorEnvironment } = require("./executor-environment");
19
+
20
+ const VERSION = require("../package.json").version;
21
+ const AUTOWONDER_HOME = path.join(os.homedir(), ".autowonder");
22
+ const BIN_DIR = path.join(AUTOWONDER_HOME, "bin");
23
+ function daemonBinPath() {
24
+ if (process.platform === "win32") {
25
+ return path.join(BIN_DIR, `v${VERSION}`, "autowonder-daemon.exe");
26
+ }
27
+ return path.join(BIN_DIR, "autowonder-daemon");
28
+ }
29
+ const DAEMON_BIN = daemonBinPath();
30
+ const CONFIG_PATH = path.join(AUTOWONDER_HOME, "config.json");
31
+ const PID_PATH = path.join(AUTOWONDER_HOME, "daemon.pid");
32
+ const STATE_PATH = path.join(AUTOWONDER_HOME, "daemon-state.json");
33
+ const LOG_PATH = path.join(AUTOWONDER_HOME, "daemon.log");
34
+
35
+ const BINARY_BASE_URL = process.env.AUTOWONDER_BINARY_URL || "";
36
+ const SOURCE_REPO = process.env.AUTOWONDER_SOURCE_REPO || "";
37
+ const BUNDLED_BIN_DIR = path.join(__dirname, "..", "vendor");
38
+
39
+ const DEFAULT_API_ADDR = process.env.AUTOWONDER_API_ADDR || "127.0.0.1:34989";
40
+ const IS_WIN32 = process.platform === "win32";
41
+
42
+ function safeChmod(filePath, mode) {
43
+ try { fs.chmodSync(filePath, mode); } catch {}
44
+ }
45
+
46
+ // ─── Helpers ─────────────────────────────────────────────────────────
47
+
48
+ function detectProvider() {
49
+ const providers = [];
50
+ if (findQoderExecutable("qoder")) providers.push("qoder");
51
+ return providers;
52
+ }
53
+
54
+ // The client only launches the Qoder-family CLIs, so every other provider is
55
+ // rejected here before any unsupported command can be spawned.
56
+ function assertSupportedProvider(provider) {
57
+ if (isQoderFamilyProvider(provider)) return provider;
58
+ const shown = provider ? `: ${provider}` : "";
59
+ error(`Unsupported provider${shown}. The AutoWonder client only launches the Qoder CLI (qodercli) or Qoder CLI CN (qodercn) command; use --provider qoder or --provider qodercn`);
60
+ process.exit(1);
61
+ }
62
+
63
+ const QODER_CONTEXT_WINDOWS = new Set(["1000000", "400000", "260000"]);
64
+ const QODER_REASONING_EFFORTS = new Set(["none", "low", "medium", "high", "xhigh", "max"]);
65
+
66
+ function validateQoderOptions(flags) {
67
+ if (flags["reasoning-effort"] && !QODER_REASONING_EFFORTS.has(flags["reasoning-effort"])) {
68
+ error("--reasoning-effort must be one of: none, low, medium, high, xhigh, max");
69
+ return false;
70
+ }
71
+ if (flags["context-window"] && !/^[1-9][0-9]*$/.test(flags["context-window"])) {
72
+ error("--context-window must be a positive integer");
73
+ return false;
74
+ }
75
+ if (flags["context-window"] && !QODER_CONTEXT_WINDOWS.has(flags["context-window"])) {
76
+ error("--context-window must be one of: 1000000, 400000, 260000");
77
+ return false;
78
+ }
79
+ return true;
80
+ }
81
+
82
+ function daemonRunning() {
83
+ const pid = readPid();
84
+ return Boolean(pid && processRunning(pid) && ownsDaemonProcess(pid));
85
+ }
86
+
87
+ function processRunning(pid) {
88
+ try { process.kill(pid, 0); return true; } catch { return false; }
89
+ }
90
+
91
+ function processFingerprint(pid) {
92
+ if (IS_WIN32) {
93
+ const result = spawnSync("wmic", [
94
+ "process", "where", `ProcessId=${pid}`, "get", "CreationDate,CommandLine", "/format:list",
95
+ ], { encoding: "utf8", timeout: 3000 });
96
+ return result.status === 0 ? (result.stdout || "").trim() : "";
97
+ }
98
+ const result = spawnSync("ps", ["-p", String(pid), "-o", "lstart=", "-o", "command="], {
99
+ encoding: "utf8",
100
+ timeout: 2000,
101
+ });
102
+ return result.status === 0 ? (result.stdout || "").trim() : "";
103
+ }
104
+
105
+ function legacyDaemonProcess(pid) {
106
+ if (IS_WIN32) {
107
+ const result = spawnSync("wmic", [
108
+ "process", "where", `ProcessId=${pid}`, "get", "ExecutablePath", "/format:list",
109
+ ], { encoding: "utf8", timeout: 3000 });
110
+ if (result.status !== 0) return false;
111
+ const output = (result.stdout || "").trim();
112
+ const normalized = DAEMON_BIN.replace(/\//g, "\\");
113
+ return output.includes(DAEMON_BIN) || output.includes(normalized);
114
+ }
115
+ const result = spawnSync("ps", ["-p", String(pid), "-o", "command="], {
116
+ encoding: "utf8",
117
+ timeout: 2000,
118
+ });
119
+ if (result.status !== 0) return false;
120
+ const command = (result.stdout || "").trim();
121
+ return command === DAEMON_BIN || command.startsWith(`${DAEMON_BIN} `);
122
+ }
123
+
124
+ function readDaemonState() {
125
+ if (!fs.existsSync(STATE_PATH)) return null;
126
+ try { return JSON.parse(fs.readFileSync(STATE_PATH, "utf8")); } catch { return null; }
127
+ }
128
+
129
+ function ownsDaemonProcess(pid) {
130
+ const state = readDaemonState();
131
+ if (state && state.pid === pid) {
132
+ const fingerprint = processFingerprint(pid);
133
+ return Boolean(fingerprint && fingerprint === state.fingerprint);
134
+ }
135
+ return legacyDaemonProcess(pid);
136
+ }
137
+
138
+ function clearDaemonState() {
139
+ try { fs.unlinkSync(PID_PATH); } catch {}
140
+ try { fs.unlinkSync(STATE_PATH); } catch {}
141
+ }
142
+
143
+ function saveDaemonState(pid, instanceId) {
144
+ const fingerprint = processFingerprint(pid);
145
+ if (!fingerprint) return false;
146
+ fs.writeFileSync(PID_PATH, String(pid) + "\n");
147
+ fs.writeFileSync(STATE_PATH, JSON.stringify({ pid, fingerprint, instanceId }) + "\n", { mode: 0o600 });
148
+ return true;
149
+ }
150
+
151
+ async function waitForProcessExit(pid, timeoutMs = 5000) {
152
+ const deadline = Date.now() + timeoutMs;
153
+ while (Date.now() < deadline) {
154
+ if (!processRunning(pid)) return true;
155
+ await new Promise((resolve) => setTimeout(resolve, 50));
156
+ }
157
+ return !processRunning(pid);
158
+ }
159
+
160
+ function checkDaemonHealth(addr, instanceId) {
161
+ return new Promise((resolve) => {
162
+ const request = http.get(`http://${addr}/health`, { timeout: 500 }, (response) => {
163
+ let body = "";
164
+ response.setEncoding("utf8");
165
+ response.on("data", (chunk) => { body += chunk; });
166
+ response.on("end", () => {
167
+ try {
168
+ const health = JSON.parse(body);
169
+ resolve(response.statusCode === 200 && health.status === "ok" && health.instanceId === instanceId);
170
+ } catch {
171
+ resolve(false);
172
+ }
173
+ });
174
+ });
175
+ request.on("timeout", () => request.destroy());
176
+ request.on("error", () => resolve(false));
177
+ });
178
+ }
179
+
180
+ async function waitForDaemonHealth(addr, pid, instanceId, timeoutMs = 5000) {
181
+ const deadline = Date.now() + timeoutMs;
182
+ while (Date.now() < deadline) {
183
+ if (!processRunning(pid)) return false;
184
+ if (await checkDaemonHealth(addr, instanceId)) return true;
185
+ await new Promise((resolve) => setTimeout(resolve, 50));
186
+ }
187
+ return false;
188
+ }
189
+
190
+ function readPid() {
191
+ if (!fs.existsSync(PID_PATH)) return null;
192
+ const pid = parseInt(fs.readFileSync(PID_PATH, "utf8").trim(), 10);
193
+ return pid || null;
194
+ }
195
+
196
+ function loadConfig() {
197
+ if (!fs.existsSync(CONFIG_PATH)) return {};
198
+ try { return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8")); } catch { return {}; }
199
+ }
200
+
201
+ function saveConfig(config) {
202
+ ensureDir(AUTOWONDER_HOME);
203
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", "utf8");
204
+ }
205
+
206
+ function binaryPlatformKey() {
207
+ const platform = process.platform;
208
+ const arch = process.arch === "arm64" ? "arm64" : "amd64";
209
+ return `${platform}-${arch}`;
210
+ }
211
+
212
+ function binaryExists() {
213
+ try {
214
+ fs.accessSync(DAEMON_BIN, fs.constants.X_OK);
215
+ return true;
216
+ } catch { return false; }
217
+ }
218
+
219
+ function installBundledBinary(source, destination) {
220
+ const temporary = `${destination}.tmp-${process.pid}-${crypto.randomUUID()}`;
221
+ try {
222
+ fs.copyFileSync(source, temporary);
223
+ safeChmod(temporary, 0o755);
224
+ fs.renameSync(temporary, destination);
225
+ } finally {
226
+ try { fs.unlinkSync(temporary); } catch {}
227
+ }
228
+ }
229
+
230
+ // ─── Binary Installation ─────────────────────────────────────────────
231
+
232
+ async function installBinary(options = {}) {
233
+ if (binaryExists() && !options.force) {
234
+ log("Daemon binary already installed.");
235
+ return true;
236
+ }
237
+
238
+ const platform = binaryPlatformKey();
239
+ log(`Installing autowonder-daemon for ${platform}...`);
240
+ ensureDir(BIN_DIR);
241
+ if (IS_WIN32) ensureDir(path.dirname(DAEMON_BIN));
242
+
243
+ // Priority 1: bundled binary in npm package (vendor/)
244
+ const ext = IS_WIN32 ? ".exe" : "";
245
+ const bundledPath = path.join(BUNDLED_BIN_DIR, `autowonder-daemon-${platform}${ext}`);
246
+ if (fs.existsSync(bundledPath)) {
247
+ installBundledBinary(bundledPath, DAEMON_BIN);
248
+ log(`Installed from bundled binary: ${DAEMON_BIN}`);
249
+ return true;
250
+ }
251
+
252
+ // Priority 2: download from URL (OSS or CDN)
253
+ if (BINARY_BASE_URL) {
254
+ const url = `${BINARY_BASE_URL}/v${VERSION}/autowonder-daemon-${platform}${ext}`;
255
+ const downloaded = await tryDownload(url, DAEMON_BIN);
256
+ if (downloaded) {
257
+ safeChmod(DAEMON_BIN, 0o755);
258
+ log(`Downloaded daemon binary: ${DAEMON_BIN}`);
259
+ return true;
260
+ }
261
+ }
262
+
263
+ // Priority 3: build from source
264
+ log("Pre-built binary not available. Building from source...");
265
+ return buildFromSource();
266
+ }
267
+
268
+ function tryDownload(url, dest) {
269
+ return new Promise((resolve) => {
270
+ ensureDir(path.dirname(dest));
271
+ const client = url.startsWith("https") ? https : http;
272
+
273
+ function doRequest(requestUrl, redirects) {
274
+ if (redirects > 5) { resolve(false); return; }
275
+ const parsedUrl = new URL(requestUrl);
276
+ const options = {
277
+ hostname: parsedUrl.hostname,
278
+ port: parsedUrl.port || undefined,
279
+ path: parsedUrl.pathname + parsedUrl.search,
280
+ headers: { "User-Agent": "autowonder-npm" },
281
+ };
282
+ client.get(options, (res) => {
283
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
284
+ doRequest(res.headers.location, redirects + 1);
285
+ return;
286
+ }
287
+ if (res.statusCode !== 200) { res.resume(); resolve(false); return; }
288
+ const file = fs.createWriteStream(dest);
289
+ res.pipe(file);
290
+ file.on("finish", () => { file.close(); resolve(true); });
291
+ file.on("error", () => { try { fs.unlinkSync(dest); } catch {} resolve(false); });
292
+ }).on("error", () => resolve(false));
293
+ }
294
+ doRequest(url, 0);
295
+ });
296
+ }
297
+
298
+ function buildFromSource() {
299
+ if (!SOURCE_REPO) {
300
+ error("No pre-built binary available for this platform.");
301
+ error("Set AUTOWONDER_SOURCE_REPO to build from source.");
302
+ return false;
303
+ }
304
+
305
+ try { execFileSync(IS_WIN32 ? "where" : "which", ["go"], { stdio: "ignore" }); } catch {
306
+ error("Go is not installed. Install Go 1.22+ or provide a pre-built binary.");
307
+ error(" macOS: brew install go");
308
+ error(" Linux: https://go.dev/dl/");
309
+ return false;
310
+ }
311
+
312
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "autowonder-build-"));
313
+ try {
314
+ log("Cloning source repository...");
315
+ execFileSync("git", ["clone", "--depth", "1", SOURCE_REPO, tmpDir], { stdio: "inherit" });
316
+ log("Building daemon...");
317
+ ensureDir(BIN_DIR);
318
+ execFileSync("go", ["build", "-o", DAEMON_BIN, "./cmd/autowonder-daemon"], { cwd: tmpDir, stdio: "inherit" });
319
+ safeChmod(DAEMON_BIN, 0o755);
320
+ log(`Built daemon binary: ${DAEMON_BIN}`);
321
+ return true;
322
+ } catch (e) {
323
+ error(`Build failed: ${e.message}`);
324
+ return false;
325
+ } finally {
326
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch {}
327
+ }
328
+ }
329
+
330
+ // ─── Commands ────────────────────────────────────────────────────────
331
+
332
+ async function cmdConnect(args) {
333
+ const normalizedArgs = args.flatMap((arg) => {
334
+ for (const key of ["QODER_PERSONAL_ACCESS_TOKEN", "QODERCN_PERSONAL_ACCESS_TOKEN"]) {
335
+ const prefix = `--${key}=`;
336
+ if (arg.startsWith(prefix)) return [`--${key}`, arg.slice(prefix.length)];
337
+ }
338
+ return [arg];
339
+ });
340
+ const flags = parseFlags(normalizedArgs, ["ws-url", "token", "executor-id", "provider", "name", "max-tasks", "model", "reasoning-effort", "context-window", "memory-mode", "settings", "workspace-root", "token-aware-enable", "QODER_PERSONAL_ACCESS_TOKEN", "QODERCN_PERSONAL_ACCESS_TOKEN"]);
341
+
342
+ const requestedAccessTokenEnv = flags.provider === "qodercn"
343
+ ? "QODERCN_PERSONAL_ACCESS_TOKEN"
344
+ : "QODER_PERSONAL_ACCESS_TOKEN";
345
+ const hasRequestedAccessToken = Object.prototype.hasOwnProperty.call(flags, requestedAccessTokenEnv);
346
+
347
+ if (
348
+ hasRequestedAccessToken &&
349
+ (flags[requestedAccessTokenEnv] === "true" || !flags[requestedAccessTokenEnv].trim())
350
+ ) {
351
+ error(`--${requestedAccessTokenEnv} requires a non-empty value`);
352
+ process.exit(1);
353
+ }
354
+
355
+ if (!flags["ws-url"] || !flags.token || !flags["executor-id"]) {
356
+ error("Usage: autowonder connect --ws-url <url> --token <token> --executor-id <id> [--provider qoder|qodercn] [--workspace-root <path>]");
357
+ process.exit(1);
358
+ }
359
+ const requestedProvider = flags.provider;
360
+ if (requestedProvider) assertSupportedProvider(requestedProvider);
361
+ if (isQoderFamilyProvider(requestedProvider) && !validateQoderOptions(flags)) process.exit(1);
362
+
363
+ const providers = detectProvider();
364
+ const provider = requestedProvider || providers[0];
365
+ if (!provider) {
366
+ error(`No agent CLI detected. Install one of: qodercli, qodercn`);
367
+ process.exit(1);
368
+ }
369
+ assertSupportedProvider(provider);
370
+ let selectedAccessTokenEnv = "";
371
+ let hasExplicitAccessToken = false;
372
+ let inheritedAccessToken;
373
+ if (isQoderFamilyProvider(provider)) {
374
+ selectedAccessTokenEnv = provider === "qodercn"
375
+ ? "QODERCN_PERSONAL_ACCESS_TOKEN"
376
+ : "QODER_PERSONAL_ACCESS_TOKEN";
377
+ hasExplicitAccessToken = Object.prototype.hasOwnProperty.call(flags, selectedAccessTokenEnv);
378
+ const inheritedAccessTokenPresent = Object.prototype.hasOwnProperty.call(process.env, selectedAccessTokenEnv);
379
+ inheritedAccessToken = process.env[selectedAccessTokenEnv];
380
+ const nodeVersion = process.env.NODE_ENV === "test" && process.env.AUTOWONDER_TEST_NODE_VERSION
381
+ ? process.env.AUTOWONDER_TEST_NODE_VERSION
382
+ : process.versions.node;
383
+ const nodeMajor = Number.parseInt(nodeVersion.split(".")[0], 10);
384
+ if (!Number.isInteger(nodeMajor) || nodeMajor < 20) {
385
+ const displayName = provider === "qodercn" ? "Qoder CLI CN" : "Qoder CLI";
386
+ error(`${displayName} requires Node.js 20 or newer; current version is ${nodeVersion}. Upgrade Node.js and retry.`);
387
+ process.exit(1);
388
+ }
389
+
390
+ const fetchOptions = {
391
+ wsUrl: flags["ws-url"],
392
+ executorId: flags["executor-id"],
393
+ executorToken: flags.token,
394
+ };
395
+ if (process.env.NODE_ENV === "test" && process.env.AUTOWONDER_TEST_EXECUTOR_ENVIRONMENT_TIMEOUT_MS) {
396
+ fetchOptions.timeoutMs = Number.parseInt(process.env.AUTOWONDER_TEST_EXECUTOR_ENVIRONMENT_TIMEOUT_MS, 10) || 1;
397
+ }
398
+ const platformEnvironment = await fetchExecutorEnvironment(fetchOptions);
399
+ const candidates = [
400
+ hasExplicitAccessToken ? flags[selectedAccessTokenEnv] : "",
401
+ inheritedAccessToken,
402
+ platformEnvironment[selectedAccessTokenEnv],
403
+ ];
404
+ const selectedQoderToken = candidates.find((value) => typeof value === "string" && value.trim());
405
+ const ignoredBlankInheritedToken = inheritedAccessTokenPresent && !selectedQoderToken;
406
+ if (ignoredBlankInheritedToken) delete process.env[selectedAccessTokenEnv];
407
+ let qoderReady = false;
408
+ try {
409
+ qoderReady = await ensureQoderReady(provider, {
410
+ debug: Boolean(flags.debug),
411
+ authenticationMode: selectedQoderToken ? "access_token" : "oauth",
412
+ accessToken: selectedQoderToken || null,
413
+ });
414
+ } finally {
415
+ if (ignoredBlankInheritedToken) process.env[selectedAccessTokenEnv] = inheritedAccessToken;
416
+ }
417
+ if (!qoderReady) process.exit(1);
418
+ }
419
+
420
+ // A version-pinned npx command must always run the binary bundled with that package.
421
+ // Windows locks a running .exe. Its versioned path is immutable, so another
422
+ // Executor using the same package can safely reuse it instead of replacing it.
423
+ const installed = await installBinary({ force: !IS_WIN32 });
424
+ if (!installed) process.exit(1);
425
+
426
+ const hasProviderSettings = Boolean(flags.model || flags["reasoning-effort"]);
427
+ if (hasProviderSettings && provider !== "codex" && !isQoderFamilyProvider(provider)) {
428
+ error("--model and --reasoning-effort are supported only for codex, qoder and qodercn");
429
+ process.exit(1);
430
+ }
431
+ if (flags["context-window"] && !isQoderFamilyProvider(provider)) {
432
+ error("--context-window is supported only for qoder and qodercn");
433
+ process.exit(1);
434
+ }
435
+ if (isQoderFamilyProvider(provider) && !validateQoderOptions(flags)) process.exit(1);
436
+ let claudeSettingsPath = "";
437
+ if (flags.settings) {
438
+ if (provider !== "claude") {
439
+ error("--settings is supported only for claude");
440
+ process.exit(1);
441
+ }
442
+ claudeSettingsPath = resolveUserPath(flags.settings);
443
+ try {
444
+ const stat = fs.statSync(claudeSettingsPath);
445
+ if (!stat.isFile()) throw new Error("not a regular file");
446
+ fs.accessSync(claudeSettingsPath, fs.constants.R_OK);
447
+ } catch {
448
+ error(`Claude settings file does not exist or is not readable: ${claudeSettingsPath}`);
449
+ process.exit(1);
450
+ }
451
+ }
452
+ const memoryMode = flags["memory-mode"] || "platform";
453
+ if (!["platform", "provider-local", "none"].includes(memoryMode)) {
454
+ error("--memory-mode must be one of: platform, provider-local, none");
455
+ process.exit(1);
456
+ }
457
+
458
+ const executorId = flags["executor-id"];
459
+
460
+ const config = {
461
+ serverUrl: flags["ws-url"],
462
+ token: flags.token,
463
+ executorId,
464
+ provider,
465
+ name: flags.name || `daemon_${provider}_${executorId}`,
466
+ maxTasks: parseInt(flags["max-tasks"] || "10", 10),
467
+ memoryMode,
468
+ claudeSettingsPath,
469
+ };
470
+ saveConfig(config);
471
+
472
+ log(`Connecting to ${config.serverUrl || "local mode"}...`);
473
+ log(`Provider: ${provider}`);
474
+ log(`Name: ${config.name}`);
475
+ log(`Max concurrent: ${config.maxTasks}`);
476
+ log("");
477
+
478
+ // Start daemon in foreground (like harness connect)
479
+ const workspaceRoot = flags["workspace-root"] && flags["workspace-root"] !== "true"
480
+ ? path.resolve(resolveUserPath(flags["workspace-root"]))
481
+ : path.join(os.homedir(), `autowonder_workspaces_${provider}_${executorId}`);
482
+ const env = {
483
+ ...process.env,
484
+ AUTOWONDER_PROVIDER: config.provider,
485
+ AUTOWONDER_MAX_CONCURRENT_DISPATCHES: String(config.maxTasks),
486
+ AUTOWONDER_DAEMON_ID: config.name,
487
+ AUTOWONDER_RUNTIME_ID: `rt_${provider}_${executorId}`,
488
+ AUTOWONDER_WORKSPACE_ROOT: workspaceRoot,
489
+ AUTOWONDER_LOCAL_API_ADDR: "127.0.0.1:0",
490
+ AUTOWONDER_SERVER_WS_URL: config.serverUrl,
491
+ AUTOWONDER_EXECUTOR_TOKEN: config.token,
492
+ AUTOWONDER_EXECUTOR_ID: executorId,
493
+ AUTOWONDER_MEMORY_MODE: config.memoryMode,
494
+ };
495
+ if (flags.model) env.AUTOWONDER_MODEL = flags.model;
496
+ if (flags["reasoning-effort"]) env.AUTOWONDER_REASONING_EFFORT = flags["reasoning-effort"];
497
+ if (flags["context-window"]) env.AUTOWONDER_CONTEXT_WINDOW = flags["context-window"];
498
+ if (config.claudeSettingsPath) env.AUTOWONDER_CLAUDE_SETTINGS = config.claudeSettingsPath;
499
+ if (flags.debug) env.AUTOWONDER_DEBUG = "1";
500
+ if (isQoderFamilyProvider(provider) && hasExplicitAccessToken) {
501
+ env[selectedAccessTokenEnv] = flags[selectedAccessTokenEnv];
502
+ } else if (isQoderFamilyProvider(provider)
503
+ && !(typeof inheritedAccessToken === "string" && inheritedAccessToken.trim())) {
504
+ delete env[selectedAccessTokenEnv];
505
+ }
506
+
507
+ // --token-aware-enable: start token-proxy as a sidecar (bypass, non-blocking)
508
+ let tokenProxyChild = null;
509
+ if (flags["token-aware-enable"]) {
510
+ const tokenProxyScript = path.join(__dirname, "token-proxy.js");
511
+ if (fs.existsSync(tokenProxyScript)) {
512
+ const proxyPort = parseInt(process.env.TOKEN_PROXY_PORT || "19876", 10);
513
+ const caCertPath = path.join(AUTOWONDER_HOME, "token-tap", "ca-cert.pem");
514
+ try {
515
+ // The proxy owns its own rotating diagnostic log, so the launcher keeps
516
+ // all three streams on /dev/null and never holds a second unbounded
517
+ // handle on proxy-diag.log.
518
+ const proxyEnv = { ...process.env };
519
+ if (flags.debug) proxyEnv.AUTOWONDER_DEBUG = "1";
520
+ tokenProxyChild = spawn(process.execPath, [tokenProxyScript, "start", "--port", String(proxyPort)], {
521
+ detached: true,
522
+ stdio: ["ignore", "ignore", "ignore"],
523
+ env: proxyEnv,
524
+ });
525
+ tokenProxyChild.unref();
526
+
527
+ // Wait up to 3s for CA cert to appear (proxy generates it on first start)
528
+ const deadline = Date.now() + 3000;
529
+ while (Date.now() < deadline && !fs.existsSync(caCertPath)) {
530
+ spawnSync(process.execPath, ["-e", "setTimeout(()=>{},200)"], { stdio: "ignore" }); // cross-platform sleep
531
+ }
532
+
533
+ if (fs.existsSync(caCertPath)) {
534
+ // Pass proxy config to daemon via env. The daemon will set per-dispatch
535
+ // HTTPS_PROXY=http://d-{dispatchId}:x@host:port for each qodercli process,
536
+ // so the proxy can tag token records with the exact dispatch ID.
537
+ env.AUTOWONDER_TOKEN_PROXY_PORT = String(proxyPort);
538
+ env.AUTOWONDER_TOKEN_PROXY_CA = caCertPath;
539
+ env.AUTOWONDER_TOKEN_PROXY_DIAG_LOG = path.join(AUTOWONDER_HOME, "token-tap", "proxy-diag.log");
540
+ env.NODE_EXTRA_CA_CERTS = caCertPath;
541
+ log(`Token tracking enabled (proxy pid=${tokenProxyChild.pid}, port=${proxyPort})`);
542
+ } else {
543
+ log("WARN: token-proxy CA cert not ready, continuing without token tracking");
544
+ }
545
+ } catch (e) {
546
+ log(`WARN: token-proxy start failed (${e.message}), continuing without token tracking`);
547
+ }
548
+ } else {
549
+ log(`WARN: token-proxy.js not found at ${tokenProxyScript}, --token-aware-enable ignored`);
550
+ }
551
+ }
552
+
553
+ const child = spawn(DAEMON_BIN, [], { env, stdio: "inherit" });
554
+ child.on("exit", (code) => {
555
+ // Stop token-proxy when daemon exits
556
+ if (tokenProxyChild) { try { process.kill(tokenProxyChild.pid); } catch (_) {} }
557
+ process.exit(code || 0);
558
+ });
559
+ process.on("SIGINT", () => {
560
+ child.kill("SIGINT");
561
+ if (tokenProxyChild) { try { process.kill(tokenProxyChild.pid); } catch (_) {} }
562
+ });
563
+ process.on("SIGTERM", () => {
564
+ child.kill("SIGTERM");
565
+ if (tokenProxyChild) { try { process.kill(tokenProxyChild.pid); } catch (_) {} }
566
+ });
567
+ }
568
+
569
+ async function cmdStart(args) {
570
+ const flags = parseFlags(args, ["provider", "max-tasks", "addr"]);
571
+ if (flags.provider) assertSupportedProvider(flags.provider);
572
+
573
+ if (daemonRunning()) {
574
+ log("Daemon is already running.");
575
+ return true;
576
+ }
577
+
578
+ const providers = detectProvider();
579
+ const provider = flags.provider || providers[0];
580
+ if (!provider) {
581
+ error(`No agent CLI detected. Install one of: qodercli, qodercn`);
582
+ process.exit(1);
583
+ }
584
+ assertSupportedProvider(provider);
585
+ if (!(await ensureQoderReady(provider))) process.exit(1);
586
+
587
+ const installed = await installBinary();
588
+ if (!installed) process.exit(1);
589
+
590
+ const addr = flags.addr || DEFAULT_API_ADDR;
591
+ const maxTasks = flags["max-tasks"] || "10";
592
+
593
+ log(`Starting daemon (provider=${provider}, addr=${addr})...`);
594
+
595
+ ensureDir(AUTOWONDER_HOME);
596
+ const logFd = fs.openSync(LOG_PATH, "a");
597
+ const instanceId = crypto.randomUUID();
598
+ const child = spawn(DAEMON_BIN, [], {
599
+ detached: true,
600
+ stdio: ["ignore", logFd, logFd],
601
+ env: {
602
+ ...process.env,
603
+ AUTOWONDER_PROVIDER: provider,
604
+ AUTOWONDER_LOCAL_API_ADDR: addr,
605
+ AUTOWONDER_MAX_CONCURRENT_DISPATCHES: maxTasks,
606
+ AUTOWONDER_DAEMON_INSTANCE_ID: instanceId,
607
+ // The descriptor keeps the file open before the daemon can log anything;
608
+ // naming the path lets the daemon reopen it and own rotation from here on.
609
+ AUTOWONDER_DAEMON_LOG: LOG_PATH,
610
+ },
611
+ });
612
+ fs.closeSync(logFd);
613
+ fs.writeFileSync(PID_PATH, String(child.pid) + "\n");
614
+
615
+ if (!await waitForDaemonHealth(addr, child.pid, instanceId) || !saveDaemonState(child.pid, instanceId)) {
616
+ if (processRunning(child.pid)) {
617
+ try { child.kill("SIGTERM"); } catch {}
618
+ await waitForProcessExit(child.pid, 2000);
619
+ }
620
+ clearDaemonState();
621
+ error(`Daemon failed to become healthy at http://${addr}/health.`);
622
+ process.exitCode = 1;
623
+ return false;
624
+ }
625
+
626
+ child.unref();
627
+
628
+ log(`Daemon started (pid=${child.pid})`);
629
+ log(` API: http://${addr}`);
630
+ log(` Log: ${LOG_PATH}`);
631
+ log(` PID: ${PID_PATH}`);
632
+ return true;
633
+ }
634
+
635
+ async function cmdStop(options = {}) {
636
+ const pid = readPid();
637
+ if (!pid || !processRunning(pid)) {
638
+ if (!options.quiet) log("Daemon is not running.");
639
+ clearDaemonState();
640
+ return true;
641
+ }
642
+ if (!ownsDaemonProcess(pid)) {
643
+ if (!options.quiet) log(`Ignoring stale daemon PID ${pid}; it belongs to another process.`);
644
+ clearDaemonState();
645
+ return true;
646
+ }
647
+ process.kill(pid, "SIGTERM");
648
+ if (!await waitForProcessExit(pid)) {
649
+ error(`Daemon did not stop within 5 seconds (pid=${pid}).`);
650
+ return false;
651
+ }
652
+ if (!options.quiet) log(`Stopped daemon (pid=${pid})`);
653
+ clearDaemonState();
654
+ return true;
655
+ }
656
+
657
+ function httpGetJson(addr, urlPath, timeoutMs = 3000) {
658
+ return new Promise((resolve) => {
659
+ const request = http.get({ hostname: addr.split(":")[0], port: addr.split(":")[1], path: urlPath, timeout: timeoutMs }, (response) => {
660
+ let body = "";
661
+ response.setEncoding("utf8");
662
+ response.on("data", (chunk) => { body += chunk; });
663
+ response.on("end", () => {
664
+ try { resolve({ statusCode: response.statusCode, body: JSON.parse(body) }); } catch { resolve(null); }
665
+ });
666
+ });
667
+ request.on("timeout", () => request.destroy());
668
+ request.on("error", () => resolve(null));
669
+ });
670
+ }
671
+
672
+ function httpPostJson(addr, urlPath, body, timeoutMs = 10000) {
673
+ return new Promise((resolve) => {
674
+ const data = typeof body === "string" ? body : JSON.stringify(body);
675
+ const request = http.request({
676
+ hostname: addr.split(":")[0], port: addr.split(":")[1], path: urlPath, method: "POST", timeout: timeoutMs,
677
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) },
678
+ }, (response) => {
679
+ let responseBody = "";
680
+ response.setEncoding("utf8");
681
+ response.on("data", (chunk) => { responseBody += chunk; });
682
+ response.on("end", () => resolve({ statusCode: response.statusCode, body: responseBody }));
683
+ });
684
+ request.on("timeout", () => request.destroy());
685
+ request.on("error", (e) => resolve({ statusCode: 0, body: e.message }));
686
+ request.write(data);
687
+ request.end();
688
+ });
689
+ }
690
+
691
+ async function cmdStatus() {
692
+ const running = daemonRunning();
693
+ const pid = readPid();
694
+ const config = loadConfig();
695
+
696
+ console.log("");
697
+ console.log(` Status: ${running ? "\x1b[32mrunning\x1b[0m" : "\x1b[31mstopped\x1b[0m"}`);
698
+ if (pid && running) console.log(` PID: ${pid}`);
699
+ console.log(` Provider: ${config.provider || "not configured"}`);
700
+ console.log(` Server: ${config.serverUrl || "local only"}`);
701
+ console.log(` Binary: ${binaryExists() ? DAEMON_BIN : "not installed"}`);
702
+ console.log(` Home: ${AUTOWONDER_HOME}`);
703
+ console.log("");
704
+
705
+ if (running) {
706
+ const health = await httpGetJson(DEFAULT_API_ADDR, "/health");
707
+ if (health && health.statusCode === 200) {
708
+ console.log(` API: http://${DEFAULT_API_ADDR} (${health.body.status})`);
709
+ }
710
+
711
+ const runtimes = await httpGetJson(DEFAULT_API_ADDR, "/runtimes");
712
+ if (runtimes && runtimes.statusCode === 200) {
713
+ for (const rt of (runtimes.body.runtimes || runtimes.body)) {
714
+ console.log(` Runtime: ${rt.id} (${rt.provider}) ${rt.available ? "available" : "unavailable"}${rt.version ? " v" + rt.version : ""}`);
715
+ }
716
+ }
717
+ console.log("");
718
+ }
719
+ }
720
+
721
+ async function cmdDispatch(args) {
722
+ if (args.length === 0) {
723
+ error("Usage: autowonder dispatch <assignment.json | package-url>");
724
+ process.exit(1);
725
+ }
726
+
727
+ if (!daemonRunning()) {
728
+ error("Daemon is not running. Start it first: autowonder start");
729
+ process.exit(1);
730
+ }
731
+
732
+ const input = args[0];
733
+ let body;
734
+
735
+ if (fs.existsSync(input)) {
736
+ body = fs.readFileSync(input, "utf8");
737
+ } else {
738
+ error(`File not found: ${input}`);
739
+ process.exit(1);
740
+ }
741
+
742
+ log(`Submitting dispatch to http://${DEFAULT_API_ADDR}...`);
743
+ const res = await httpPostJson(DEFAULT_API_ADDR, "/dispatches/local", body);
744
+
745
+ if (res.statusCode === 200 || res.statusCode === 202) {
746
+ log("Dispatch submitted successfully.");
747
+ if (res.body) console.log(res.body);
748
+ } else {
749
+ error(`Dispatch failed (HTTP ${res.statusCode})`);
750
+ if (res.body) console.error(res.body);
751
+ process.exit(1);
752
+ }
753
+ }
754
+
755
+ async function cmdWorkitem(args) {
756
+ const sub = args[0];
757
+ if (sub === "upload") {
758
+ return cmdWorkitemUpload(args.slice(1));
759
+ }
760
+ if (sub === "download") {
761
+ return cmdWorkitemDownload(args.slice(1));
762
+ }
763
+ error(`Unknown workitem command: ${sub || "(none)"}`);
764
+ cmdHelp();
765
+ process.exit(1);
766
+ }
767
+
768
+ function uploadExitCode(err) {
769
+ if (err && err.statusCode) {
770
+ switch (err.statusCode) {
771
+ case 401: return 3;
772
+ case 403: return 4;
773
+ case 404: return 5;
774
+ case 409: return 6;
775
+ case 413: return 7;
776
+ }
777
+ if (err.statusCode >= 400) return 8;
778
+ return 9;
779
+ }
780
+ if (err && (err.kind === "network" || err.kind === "redirect")) return 9;
781
+ return 2;
782
+ }
783
+
784
+ function reportUploadFailure(err, json) {
785
+ if (json) {
786
+ const payload = { success: false, error: err.message };
787
+ if (err.statusCode) payload.status = err.statusCode;
788
+ if (err.kind) payload.kind = err.kind;
789
+ if (err.serverError) payload.server = err.serverError;
790
+ console.log(JSON.stringify(payload));
791
+ } else {
792
+ error(err.message);
793
+ if (err.serverError && (err.serverError.message || err.serverError.code)) {
794
+ error(`server: ${err.serverError.message || "rejected"} (code ${err.serverError.code})`);
795
+ }
796
+ }
797
+ }
798
+
799
+ async function cmdWorkitemUpload(args) {
800
+ const upload = require("../lib/workitem-upload");
801
+ const json = args.includes("--json");
802
+ try {
803
+ const parsed = upload.parseUploadFlags(args);
804
+ const serverUrl = upload.validateServerUrl(parsed.serverUrl);
805
+ const workitemId = upload.validateWorkitemId(parsed.workitemId);
806
+ const token = parsed.token || process.env.AUTOWONDER_UPLOAD_TOKEN;
807
+ if (!token) {
808
+ throw new upload.UploadError(
809
+ "no upload token provided. Invoke the MCP tool autowonder.workitem_cli_upload_token to mint one, " +
810
+ "then pass it via --token or the AUTOWONDER_UPLOAD_TOKEN environment variable.",
811
+ { kind: "token" },
812
+ );
813
+ }
814
+ const files = upload.preflightFiles(parsed.files);
815
+
816
+ const { statusCode, body } = await upload.uploadWorkitemDocuments({
817
+ serverUrl, workitemId, files, token,
818
+ });
819
+
820
+ if (statusCode === 200) {
821
+ let parsedBody = null;
822
+ try { parsedBody = JSON.parse(body); } catch { /* non-JSON success bodies are ignored */ }
823
+ if (parsed.json) {
824
+ console.log(JSON.stringify({
825
+ success: true,
826
+ workitemId: Number(workitemId),
827
+ uploaded: files.map((f) => f.filename),
828
+ response: parsedBody,
829
+ }));
830
+ } else {
831
+ log(`Uploaded ${files.length} file(s) to workitem ${workitemId}: ${files.map((f) => f.filename).join(", ")}`);
832
+ }
833
+ return;
834
+ }
835
+
836
+ throw new upload.UploadError(
837
+ `server rejected the upload (HTTP ${statusCode})`,
838
+ { kind: "http", statusCode, serverError: upload.parseServerError(body) },
839
+ );
840
+ } catch (err) {
841
+ reportUploadFailure(err, json);
842
+ process.exit(uploadExitCode(err));
843
+ }
844
+ }
845
+
846
+ async function cmdWorkitemDownload(args) {
847
+ const download = require("../lib/workitem-download");
848
+ const json = args.includes("--json");
849
+ try {
850
+ const parsed = download.parseDownloadFlags(args);
851
+ const serverUrl = download.validateServerUrl(parsed.serverUrl);
852
+ const workitemId = download.validateWorkitemId(parsed.workitemId);
853
+ const token = parsed.token || process.env.AUTOWONDER_DOWNLOAD_TOKEN;
854
+ if (!token) {
855
+ throw new download.DownloadError(
856
+ "no download token provided. Invoke the MCP tool autowonder.workitem_cli_download_token to mint one, " +
857
+ "then pass it via --token or the AUTOWONDER_DOWNLOAD_TOKEN environment variable.",
858
+ { kind: "token" },
859
+ );
860
+ }
861
+ const outputDir = parsed.outputDir || ".";
862
+ ensureDir(outputDir);
863
+
864
+ const index = await download.fetchDocumentIndex({ serverUrl, workitemId, token });
865
+ const selected = download.selectDocuments(index, parsed.files);
866
+
867
+ const downloaded = [];
868
+ for (const entry of selected) {
869
+ const res = await download.downloadDocument({
870
+ serverUrl, workitemId, artifactId: entry.id, token,
871
+ });
872
+ const filename = download.documentFilename(entry);
873
+ const target = download.writeDocument({ outputDir, filename, body: res.body });
874
+ downloaded.push({ id: entry.id, name: filename, path: target, size: res.body.length });
875
+ }
876
+
877
+ if (parsed.json) {
878
+ console.log(JSON.stringify({
879
+ success: true,
880
+ workitemId: Number(workitemId),
881
+ outputDir: path.resolve(outputDir),
882
+ downloaded,
883
+ }));
884
+ } else {
885
+ log(`Downloaded ${downloaded.length} file(s) from workitem ${workitemId} to ${path.resolve(outputDir)}: ${downloaded.map((d) => d.name).join(", ")}`);
886
+ }
887
+ } catch (err) {
888
+ reportUploadFailure(err, json);
889
+ process.exit(uploadExitCode(err));
890
+ }
891
+ }
892
+
893
+ async function cmdScheduledTask(args) {
894
+ const sub = args[0];
895
+ if (sub === "upload") {
896
+ return cmdScheduledTaskUpload(args.slice(1));
897
+ }
898
+ error(`Unknown scheduled-task command: ${sub || "(none)"}`);
899
+ cmdHelp();
900
+ process.exit(1);
901
+ }
902
+
903
+ async function cmdScheduledTaskUpload(args) {
904
+ const upload = require("../lib/workitem-upload");
905
+ const json = args.includes("--json");
906
+ try {
907
+ const parsed = upload.parseUploadFlags(args, {
908
+ idFlag: "scheduled-task-id",
909
+ idKey: "scheduledTaskId",
910
+ });
911
+ const serverUrl = upload.validateServerUrl(parsed.serverUrl);
912
+ const scheduledTaskId = upload.validateScheduledTaskId(parsed.scheduledTaskId);
913
+ const token = parsed.token || process.env.AUTOWONDER_UPLOAD_TOKEN;
914
+ if (!token) {
915
+ throw new upload.UploadError(
916
+ "no upload token provided. Invoke the MCP tool autowonder.workitem_cli_upload_token to mint one, " +
917
+ "then pass it via --token or the AUTOWONDER_UPLOAD_TOKEN environment variable.",
918
+ { kind: "token" },
919
+ );
920
+ }
921
+ const files = upload.preflightFiles(parsed.files);
922
+
923
+ const { statusCode, body } = await upload.uploadScheduledTaskDocuments({
924
+ serverUrl, scheduledTaskId, files, token,
925
+ });
926
+
927
+ if (statusCode === 200) {
928
+ let parsedBody = null;
929
+ try { parsedBody = JSON.parse(body); } catch { /* non-JSON success bodies are ignored */ }
930
+ if (json) {
931
+ console.log(JSON.stringify({
932
+ success: true,
933
+ scheduledTaskId: Number(scheduledTaskId),
934
+ uploaded: files.map((f) => f.filename),
935
+ response: parsedBody,
936
+ }));
937
+ } else {
938
+ log(`Uploaded ${files.length} file(s) to scheduled task ${scheduledTaskId}: ${files.map((f) => f.filename).join(", ")}`);
939
+ }
940
+ return;
941
+ }
942
+
943
+ throw new upload.UploadError(
944
+ `server rejected the upload (HTTP ${statusCode})`,
945
+ { kind: "http", statusCode, serverError: upload.parseServerError(body) },
946
+ );
947
+ } catch (err) {
948
+ reportUploadFailure(err, json);
949
+ process.exit(uploadExitCode(err));
950
+ }
951
+ }
952
+
953
+ async function cmdInstall(args) {
954
+ const flags = parseFlags(args, ["force", "provider", "max-tasks", "addr"]);
955
+ if (flags.provider) assertSupportedProvider(flags.provider);
956
+ const force = flags.force === "true" || args.includes("--force");
957
+ if (force && daemonRunning() && !await cmdStop({ quiet: true })) {
958
+ process.exit(1);
959
+ }
960
+ const installed = await installBinary({ force });
961
+ if (!installed) process.exit(1);
962
+ if (!await cmdStart(args)) process.exit(1);
963
+ }
964
+
965
+ function cmdHelp() {
966
+ console.log(`
967
+ autowonder — local runtime for AI agent dispatch execution
968
+
969
+ Usage:
970
+ autowonder connect --ws-url <url> --token <token> --executor-id <id> Connect to server and run
971
+ autowonder start [--provider qoder|qodercn] Start daemon in background
972
+ autowonder stop Stop background daemon
973
+ autowonder status Show daemon status
974
+ autowonder dispatch <assignment.json> Submit a dispatch
975
+ autowonder install [--force] Install/update and start daemon
976
+ autowonder workitem upload --server-url <url> --workitem-id <id> --file <path> [--file <path>...]
977
+ Upload local requirement/design files to a workitem
978
+ autowonder workitem download --server-url <url> --workitem-id <id> [--file <name-or-id>...] --output-dir <dir>
979
+ Download workitem requirement/design files (no --file = all)
980
+ autowonder scheduled-task upload --server-url <url> --scheduled-task-id <id> --file <path> [--file <path>...]
981
+ Upload local requirement/design files to a scheduled task
982
+
983
+ Options:
984
+ --provider <name> Agent provider: qoder, qodercn only; other providers are rejected (default: auto-detect; qodercn must be explicit)
985
+ --max-tasks <n> Max concurrent dispatches (default: 10)
986
+ --addr <host:port> Local API address (default: 127.0.0.1:34989)
987
+ --ws-url <url> Executor WebSocket endpoint
988
+ --token <token> Executor authentication token
989
+ --executor-id <id> Executor ID
990
+ --model <model> Default model for Codex or Qoder
991
+ --reasoning-effort <level> Default reasoning effort for Codex or Qoder
992
+ --context-window <n> Qoder context window: 1000000, 400000, or 260000
993
+ --settings <file> Claude settings JSON file
994
+ --memory-mode <mode> Memory: platform, provider-local, or none (default: platform)
995
+ --name <name> Runtime name (default: provider + executor ID)
996
+ --workspace-root <path> Workspace directory for dispatch repos
997
+ (default: ~/autowonder_workspaces_<provider>_<executor-id>;
998
+ also settable via AUTOWONDER_WORKSPACE_ROOT. On Windows use a
999
+ non-C drive path here when the default location is not writable)
1000
+ --debug Stream full daemon and agent activity to console + log file
1001
+ --server-url <url> AutoWonder server base URL (workitem/scheduled-task upload, workitem download)
1002
+ --workitem-id <id> Target workitem ID (workitem upload/download)
1003
+ --scheduled-task-id <id> Target scheduled task ID (scheduled-task upload)
1004
+ --file <path> Local file to upload, repeatable (workitem/scheduled-task upload);
1005
+ on download, a document name or artifact id to fetch, repeatable (omit for all)
1006
+ --output-dir <dir> Directory to save downloaded files into (workitem download; default: .)
1007
+ --json Machine-readable output (workitem/scheduled-task upload, workitem download)
1008
+ -h, --help Show this help
1009
+
1010
+ Examples:
1011
+ # Quick start — connect to server
1012
+ npx -y autowonder connect --ws-url wss://autowonder.example.com/ws/executor --token xxx --executor-id 10000 --provider qoder
1013
+
1014
+ # Use a custom workspace directory (e.g. a non-C drive on Windows)
1015
+ npx -y autowonder connect --ws-url wss://autowonder.example.com/ws/executor --token xxx --executor-id 10000 --provider qoder --workspace-root D:\\autowonder
1016
+
1017
+ # Local mode — start daemon, submit tasks manually
1018
+ npx -y autowonder start
1019
+ npx -y autowonder dispatch ./assignment.json
1020
+
1021
+ # Upload requirement/design documents from local files
1022
+ npx -y autowonder@0.2.130 workitem upload --server-url https://private-autowonder.example.com --workitem-id 50063 --file <filepath-1> --file <filepath-2> --file <images-1> --json
1023
+
1024
+ # Download workitem requirement/design documents to a local directory (omit --file for all)
1025
+ npx -y autowonder@0.2.130 workitem download --server-url https://private-autowonder.example.com --workitem-id 50063 --file <name-or-id> --output-dir <dir> --json
1026
+
1027
+ # Upload requirement/design documents to a 7x24 scheduled task
1028
+ npx -y autowonder scheduled-task upload --server-url https://auto-wonder.example.com --scheduled-task-id 123 --file <filepath-1> --file <filepath-2> --json
1029
+
1030
+ # Check what's happening
1031
+ npx -y autowonder status
1032
+ `);
1033
+ }
1034
+
1035
+ // ─── Flag Parser ─────────────────────────────────────────────────────
1036
+
1037
+ function parseFlags(args, knownFlags) {
1038
+ const flags = {};
1039
+ for (let i = 0; i < args.length; i++) {
1040
+ const arg = args[i];
1041
+ if (arg.startsWith("--")) {
1042
+ const key = arg.slice(2);
1043
+ if (knownFlags.includes(key) && i + 1 < args.length && !args[i + 1].startsWith("--")) {
1044
+ flags[key] = args[++i];
1045
+ } else {
1046
+ flags[key] = "true";
1047
+ }
1048
+ }
1049
+ }
1050
+ return flags;
1051
+ }
1052
+
1053
+ // ─── Windows Encoding Auto-Fix ──────────────────────────────────────
1054
+
1055
+ function ensureWindowsUTF8() {
1056
+ if (process.platform !== "win32") return;
1057
+ // chcp is a .com console tool and CreateProcess resolves no PATHEXT, so it is
1058
+ // addressed by full path. shell:true would join the code page into a cmd.exe
1059
+ // command line instead, which is what emits Node's DEP0190 warning.
1060
+ const chcp = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "chcp.com");
1061
+ const result = spawnSync(chcp, [], { encoding: "utf8", timeout: 2000 });
1062
+ const currentCP = (result.stdout || "").match(/:\s*(\d+)/)?.[1];
1063
+ if (currentCP !== "65001") {
1064
+ spawnSync(chcp, ["65001"], { stdio: "ignore" });
1065
+ }
1066
+ process.env.PYTHONIOENCODING = process.env.PYTHONIOENCODING || "utf-8";
1067
+ process.env.PYTHONUTF8 = process.env.PYTHONUTF8 || "1";
1068
+ process.env.JAVA_TOOL_OPTIONS = process.env.JAVA_TOOL_OPTIONS || "-Dfile.encoding=UTF-8";
1069
+ if (!process.env.GIT_CONFIG_COUNT) {
1070
+ process.env.GIT_CONFIG_COUNT = "3";
1071
+ process.env.GIT_CONFIG_KEY_0 = "i18n.logOutputEncoding";
1072
+ process.env.GIT_CONFIG_VALUE_0 = "utf-8";
1073
+ process.env.GIT_CONFIG_KEY_1 = "i18n.commitEncoding";
1074
+ process.env.GIT_CONFIG_VALUE_1 = "utf-8";
1075
+ process.env.GIT_CONFIG_KEY_2 = "core.longpaths";
1076
+ process.env.GIT_CONFIG_VALUE_2 = "true";
1077
+ }
1078
+ // Persist core.longpaths in git global config so all git operations
1079
+ // (including checkpoint restore) can handle paths > MAX_PATH (260 chars).
1080
+ spawnSync("git", ["config", "--global", "core.longpaths", "true"], { stdio: "ignore", timeout: 5000 });
1081
+ }
1082
+
1083
+ // ─── Main ────────────────────────────────────────────────────────────
1084
+
1085
+ async function main() {
1086
+ ensureWindowsUTF8();
1087
+ const args = process.argv.slice(2);
1088
+ const command = args[0] || "help";
1089
+ const commandArgs = args.slice(1);
1090
+
1091
+ switch (command) {
1092
+ case "connect": return cmdConnect(commandArgs);
1093
+ case "start": return cmdStart(commandArgs);
1094
+ case "stop": return cmdStop();
1095
+ case "status": return cmdStatus();
1096
+ case "dispatch": return cmdDispatch(commandArgs);
1097
+ case "install": return cmdInstall(commandArgs);
1098
+ case "workitem": return cmdWorkitem(commandArgs);
1099
+ case "scheduled-task": return cmdScheduledTask(commandArgs);
1100
+ case "help":
1101
+ case "--help":
1102
+ case "-h": return cmdHelp();
1103
+ default:
1104
+ error(`Unknown command: ${command}`);
1105
+ cmdHelp();
1106
+ process.exit(1);
1107
+ }
1108
+ }
1109
+
1110
+ main().catch((e) => {
1111
+ error(e.message || String(e));
1112
+ process.exit(1);
1113
+ });