@openagents-org/agent-launcher 0.2.199 → 0.2.200

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.199",
3
+ "version": "0.2.200",
4
4
  "description": "OpenAgents Launcher \u2014 install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -203,6 +203,63 @@ class CodexAdapter extends BaseAdapter {
203
203
  return resolveWslBinary('codex');
204
204
  }
205
205
 
206
+ /**
207
+ * How to spawn `bin`: `{ file, args, shell }`, with `args` going before the
208
+ * codex arguments. On Windows an npm `.cmd` shim is resolved to
209
+ * `[node, <entry>.js]` (or the native `.exe` it forwards to) and spawned
210
+ * without a shell. Handing the shim to cmd.exe instead joined everything
211
+ * into one unquoted command line, so a profile folder with a space in it
212
+ * (`C:\Users\Windows 用户\…`) was cut at the space and the run died with
213
+ * "'C:\Users\Windows' 不是内部或外部命令".
214
+ */
215
+ _resolveExec(bin, isWindows = IS_WINDOWS) {
216
+ const lower = String(bin).toLowerCase();
217
+ if (/\.[cm]?js$/.test(lower)) return { file: this._findNodeBin(), args: [bin], shell: false };
218
+ if (!isWindows || !/\.(cmd|bat)$/.test(lower)) return { file: bin, args: [], shell: false };
219
+ try {
220
+ const content = fs.readFileSync(bin, 'utf-8');
221
+ const js = content.match(/%dp0%\\([^\s"*?]+\.[cm]?js)/i);
222
+ if (js) {
223
+ return { file: this._findNodeBin(), args: [path.resolve(path.dirname(bin), js[1])], shell: false };
224
+ }
225
+ const exe = content.match(/%dp0%\\([^\s"*?]+\.exe)/i);
226
+ if (exe) return { file: path.resolve(path.dirname(bin), exe[1]), args: [], shell: false };
227
+ } catch {}
228
+ // A shim we can't read through still has to run under cmd.exe. Quote it,
229
+ // so at least the path survives the command line cmd.exe is given.
230
+ return { file: `"${bin}"`, args: [], shell: true };
231
+ }
232
+
233
+ _findNodeBin() {
234
+ const home = os.homedir();
235
+ const candidates = IS_WINDOWS
236
+ ? [path.join(home, '.openagents', 'nodejs', 'node.exe')]
237
+ : [path.join(home, '.openagents', 'nodejs', 'bin', 'node'),
238
+ path.join(home, '.openagents', 'nodejs', 'node')];
239
+ for (const c of candidates) { try { if (fs.existsSync(c)) return c; } catch {} }
240
+ return process.execPath || 'node';
241
+ }
242
+
243
+ static _dirExists(p) {
244
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
245
+ }
246
+
247
+ /**
248
+ * Decode CLI output. Codex writes UTF-8, but text that came from Windows
249
+ * itself (cmd.exe, a system error) is in the console code page, which on a
250
+ * Chinese system is GBK and showed up in chat as rows of "�". Fall back to
251
+ * GB18030 only when UTF-8 fails and GB18030 reads the bytes cleanly.
252
+ */
253
+ static _decodeOutput(buf, isWindows = IS_WINDOWS) {
254
+ const utf8 = buf.toString('utf-8');
255
+ if (!isWindows || !utf8.includes('\uFFFD')) return utf8;
256
+ try {
257
+ return new TextDecoder('gb18030', { fatal: true }).decode(buf);
258
+ } catch {
259
+ return utf8;
260
+ }
261
+ }
262
+
206
263
  _buildSystemContext(channelName) {
207
264
  const base = buildOpenclawSystemPrompt({
208
265
  agentName: this.agentName,
@@ -314,6 +371,14 @@ class CodexAdapter extends BaseAdapter {
314
371
  }
315
372
 
316
373
  async _handleViaSubprocess(content, msgChannel, attachments = []) {
374
+ // A missing cwd fails the spawn itself, and Node blames the shell for it
375
+ // ("spawn C:\Windows\system32\cmd.exe ENOENT"), which names nothing the
376
+ // user can fix. Say which folder is gone instead.
377
+ if (this.workingDir && !CodexAdapter._dirExists(this.workingDir)) {
378
+ await this.sendError(msgChannel, `Working directory does not exist: ${this.workingDir}`);
379
+ return;
380
+ }
381
+
317
382
  const env = { ...(this.agentEnv || process.env) };
318
383
  const effectiveModel = this._effectiveModel();
319
384
 
@@ -412,26 +477,27 @@ class CodexAdapter extends BaseAdapter {
412
477
  // Stopped while this turn was being prepared: start nothing (no tokens).
413
478
  if (this._stoppedBeforeStart(msgChannel)) return { stopped: true, responseText: '', exitCode: null };
414
479
  return new Promise((resolve, reject) => {
415
- const proc = spawn(cmd[0], cmd.slice(1), {
480
+ const exec = this._resolveExec(cmd[0]);
481
+ const proc = spawn(exec.file, [...exec.args, ...cmd.slice(1)], {
416
482
  stdio: ['pipe', 'pipe', 'pipe'],
417
483
  env,
418
484
  cwd: this.workingDir,
419
485
  detached: !IS_WINDOWS,
420
486
  windowsHide: true,
421
- shell: IS_WINDOWS,
487
+ shell: exec.shell,
422
488
  });
423
489
  this._channelProcesses[msgChannel] = proc;
424
490
 
425
491
  const responseTexts = [];
426
492
  let hasToolUseSinceLastText = false;
427
493
  let lineBuffer = '';
428
- let stderrBuf = '';
494
+ const stderrChunks = [];
429
495
  let lastErrorMessage = '';
430
496
  let turnFailed = false;
431
497
  let _pendingLines = Promise.resolve();
432
498
 
433
499
  if (proc.stderr) {
434
- proc.stderr.on('data', (chunk) => { stderrBuf += chunk.toString('utf-8'); });
500
+ proc.stderr.on('data', (chunk) => { stderrChunks.push(chunk); });
435
501
  }
436
502
 
437
503
  if (proc.stdin) {
@@ -518,6 +584,7 @@ class CodexAdapter extends BaseAdapter {
518
584
 
519
585
  delete this._channelProcesses[msgChannel];
520
586
 
587
+ const stderrBuf = CodexAdapter._decodeOutput(Buffer.concat(stderrChunks));
521
588
  if (code !== 0) {
522
589
  this._log(`Codex CLI exited with code ${code}`);
523
590
  if (stderrBuf.trim()) {
package/src/daemon.js CHANGED
@@ -769,14 +769,19 @@ async _runNodeCommand(n, cmd) {
769
769
  // reaches the workspace via the heartbeat's agents[].probe.
770
770
  this._probeAgent(name).then(() => this._nodeHeartbeat()).catch(() => {});
771
771
  this._askCliModels(name);
772
- } else if (action === 'start_agent') {
773
- const r = await this._runAgn(['start', name]);
774
- ok = r.code === 0;
775
- message = ok ? `Agent '${name}' started` : (r.stderr || r.stdout || 'start failed');
776
- } else if (action === 'stop_agent') {
777
- const r = await this._runAgn(['stop', name]);
778
- ok = r.code === 0;
779
- message = ok ? `Agent '${name}' stopped` : (r.stderr || r.stdout || 'stop failed');
772
+ } else if (action === 'start_agent' || action === 'stop_agent') {
773
+ // In-process, not via `agn start|stop`: that spawned a whole CLI just to
774
+ // drop a line into daemon.cmd for THIS process to poll back up, and the
775
+ // new state then waited for the next 10s heartbeat. A Stop clicked in
776
+ // the workspace could sit at "running" for half a minute. Report the
777
+ // new state as soon as it is set instead; stopAgent flips it to
778
+ // 'stopped' before it starts waiting on the agent to exit.
779
+ const settled = action === 'stop_agent' ? this.stopAgent(name) : this._startAgentIfIdle(name);
780
+ this._nodeHeartbeat();
781
+ await settled;
782
+ this._nodeHeartbeat();
783
+ ok = true;
784
+ message = `Agent '${name}' ${action === 'stop_agent' ? 'stopped' : 'started'}`;
780
785
  } else if (action === 'remove_agent') {
781
786
  const r = await this._runAgn(['remove', name]);
782
787
  ok = r.code === 0;
@@ -1097,6 +1102,31 @@ async _runNodeCommand(n, cmd) {
1097
1102
  this._writeStatus();
1098
1103
  }
1099
1104
 
1105
+ /**
1106
+ * Start an agent unless it is already running.
1107
+ *
1108
+ * 'start' must be idempotent. The launcher sends start:<name> right after
1109
+ * (re)spawning the daemon, but the daemon's own start() already launched
1110
+ * every configured agent. A blind restart here tears down the just-joined
1111
+ * workspace session and re-joins as the same agent; the server revokes the
1112
+ * first session and the agent then stops the moment it next touches the
1113
+ * workspace (e.g. the first user message → "thinking..." status). Only
1114
+ * (re)launch when it isn't running.
1115
+ */
1116
+ async _startAgentIfIdle(agentName) {
1117
+ const running =
1118
+ (this._adapters && this._adapters[agentName]) ||
1119
+ ['running', 'starting'].includes(
1120
+ this._processes[agentName] && this._processes[agentName].state
1121
+ );
1122
+ if (running) {
1123
+ this._log(`Command: start ${agentName} — already running, skipping`);
1124
+ return;
1125
+ }
1126
+ this._log(`Command: start ${agentName}`);
1127
+ await this.restartAgent(agentName);
1128
+ }
1129
+
1100
1130
  /**
1101
1131
  * Restart a single agent by name.
1102
1132
  */
@@ -1785,25 +1815,7 @@ async _runNodeCommand(n, cmd) {
1785
1815
  this._log(`Command: stop ${agentName}`);
1786
1816
  this.stopAgent(agentName);
1787
1817
  } else if (cmd.startsWith('start:')) {
1788
- const agentName = cmd.slice(6).trim();
1789
- // 'start' must be idempotent. The launcher sends start:<name> right
1790
- // after (re)spawning the daemon, but the daemon's own start() already
1791
- // launched every configured agent. A blind restart here tears down
1792
- // the just-joined workspace session and re-joins as the same agent;
1793
- // the server revokes the first session and the agent then stops the
1794
- // moment it next touches the workspace (e.g. the first user message →
1795
- // "thinking..." status). Only (re)launch when it isn't running.
1796
- const running =
1797
- (this._adapters && this._adapters[agentName]) ||
1798
- ['running', 'starting'].includes(
1799
- this._processes[agentName] && this._processes[agentName].state
1800
- );
1801
- if (running) {
1802
- this._log(`Command: start ${agentName} — already running, skipping`);
1803
- } else {
1804
- this._log(`Command: start ${agentName}`);
1805
- this.restartAgent(agentName);
1806
- }
1818
+ this._startAgentIfIdle(cmd.slice(6).trim());
1807
1819
  } else if (cmd.startsWith('restart:')) {
1808
1820
  const agentName = cmd.slice(8).trim();
1809
1821
  this._log(`Command: restart ${agentName}`);