@openagents-org/agent-launcher 0.2.224 → 0.2.226

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.224",
3
+ "version": "0.2.226",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -13,19 +13,14 @@
13
13
  * rather than a tweak to the gemini adapter.
14
14
  */
15
15
 
16
- const { redactSecrets } = require('./utils');
16
+ const { redactSecrets, promptFitsArgv } = require('./utils');
17
17
 
18
18
  /**
19
- * Longest prompt passed as `-p <prompt>`. Past it the prompt goes over stdin
20
- * (agyStdinMessage). Windows caps a whole command line at 32,767 characters
21
- * and Node fails the spawn itself with ENAMETOOLONG — the system prompt plus a
22
- * large pinned glossary got there with a one-word message. Linux caps a single
23
- * argument at 128 KiB. Both limits are left headroom for quoting and the rest
24
- * of the argv.
19
+ * Longest prompt passed as `-p <prompt>`; past it the prompt goes over stdin
20
+ * (agyStdinMessage). The limits are shared — see promptFitsArgv in utils.
25
21
  */
26
22
  function agyPromptFitsArgv(prompt, platform = process.platform) {
27
- const limit = platform === 'win32' ? 24000 : 100000;
28
- return String(prompt || '').length <= limit;
23
+ return promptFitsArgv(prompt, platform);
29
24
  }
30
25
 
31
26
  /**
@@ -953,6 +953,21 @@ class CodexAdapter extends BaseAdapter {
953
953
  'at an endpoint that supports the full Responses API, or edit the agent and set Agent capabilities to ' +
954
954
  '"Chat only · Chat Completions API" (it then answers without running tools on this device).';
955
955
  }
956
+ // The base URL answers, but has nothing at /responses: an endpoint that
957
+ // only serves Chat Completions (or a base URL missing its path prefix).
958
+ // Seen as `unexpected status 404 Not Found: 404 page not found, url:
959
+ // http://host:port/v1/responses` on every message, read as "Codex failed
960
+ // to complete this run" with no hint that the setting is the cause.
961
+ if (/\b404\b/.test(detail) && /\/responses\b/i.test(detail)) {
962
+ const m = /url:\s*(\S+)/i.exec(detail);
963
+ let host = '';
964
+ try { host = new URL(m ? m[1] : (customProvider && customProvider.baseUrl) || '').host; } catch {}
965
+ return `${detail}\n\nThe endpoint this agent is set to${host ? ` (${host})` : ''} has no Responses API ` +
966
+ '(/v1/responses), which the Codex CLI sends every request to — so every run here will fail the same way. ' +
967
+ 'Check the base URL (it usually ends in /v1), or, if that service only offers Chat Completions, edit the ' +
968
+ 'agent and set Agent capabilities to "Chat only · Chat Completions API" (it then answers without running ' +
969
+ 'tools on this device).';
970
+ }
956
971
  // A model the user's ChatGPT plan doesn't include for Codex. Seen in the
957
972
  // field with several model names picked in the workspace; every run
958
973
  // fails the same way until another model is chosen.
@@ -50,6 +50,7 @@ const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
50
50
  const { whichBinary, whereBinary, getEnhancedEnv, defaultAgentWorkdir } = require('../paths');
51
51
  const { compareVersions } = require('../installer');
52
52
  const { CopilotStreamParser, redactSensitive } = require('./copilot-stream-parser');
53
+ const { promptFitsArgv } = require('./utils');
53
54
 
54
55
  const IS_WINDOWS = process.platform === 'win32';
55
56
 
@@ -61,6 +62,14 @@ const IS_WINDOWS = process.platform === 'win32';
61
62
  // `--secret-env-vars`/`--no-remote`. Verified end-to-end against 1.0.63.
62
63
  const MIN_VERSION = '1.0.0';
63
64
 
65
+ // First release whose changelog documents a prompt piped over stdin as a
66
+ // prompt-mode run alongside `-p` (1.0.78: its `sessionEnd` hook "the same way
67
+ // `-p` does"). A prompt too long for a command line goes that way instead —
68
+ // on Windows a channel's system prompt plus a large pinned glossary failed the
69
+ // spawn itself with ENAMETOOLONG. An older CLI is told to upgrade rather than
70
+ // handed a stdin it may not read.
71
+ const STDIN_PROMPT_MIN_VERSION = '1.0.78';
72
+
64
73
  // Token-bearing env var NAMES Copilot reads (verified precedence via
65
74
  // `copilot help environment`): COPILOT_GITHUB_TOKEN > GH_TOKEN > GITHUB_TOKEN.
66
75
  // Plus OpenAgents' own workspace token. We pass the NAMES (never values) to
@@ -276,13 +285,14 @@ class CopilotAdapter extends BaseAdapter {
276
285
  * single discrete argv element. Permissions are least-privilege and scoped to
277
286
  * the working directory.
278
287
  */
279
- _buildArgs(prompt, channel, { skipResume = false } = {}) {
288
+ _buildArgs(prompt, channel, { skipResume = false, viaStdin = false } = {}) {
280
289
  const wd = this.workingDir || defaultAgentWorkdir(this.agentName);
281
290
  // Required-value flags take the space form; optional-value/variadic flags
282
291
  // (--resume, --secret-env-vars, --allow-tool — declared `[=value]` /
283
292
  // `[=value...]` in `copilot --help` v1.0.63) MUST use the `=` form so the
284
293
  // next token isn't mistaken for a positional argument.
285
- const args = ['-p', prompt, '--output-format', 'json', '--stream', 'on'];
294
+ // viaStdin: the prompt is written to the child's stdin, so no `-p`.
295
+ const args = [...(viaStdin ? [] : ['-p', prompt]), '--output-format', 'json', '--stream', 'on'];
286
296
 
287
297
  if (this._model) args.push('--model', this._model);
288
298
 
@@ -427,15 +437,25 @@ class CopilotAdapter extends BaseAdapter {
427
437
 
428
438
  const fullPrompt = `${this._buildSystemContext(channel)}\n\n---\n\nUser message:\n${content}`;
429
439
 
440
+ // Too long for a command line: pipe it over stdin instead of `-p`.
441
+ const viaStdin = !promptFitsArgv(fullPrompt);
442
+ if (viaStdin && gate.version && compareVersions(gate.version, STDIN_PROMPT_MIN_VERSION) < 0) {
443
+ await this.sendError(channel,
444
+ `This channel's instructions are too long to pass to GitHub Copilot CLI ${gate.version} on the command line `
445
+ + `(${fullPrompt.length} characters). Copilot CLI ${STDIN_PROMPT_MIN_VERSION} or newer takes them over stdin — `
446
+ + 'upgrade with: copilot update (or npm install -g @github/copilot). A shorter pinned glossary for this channel also works.');
447
+ return;
448
+ }
449
+
430
450
  // Up to 2 attempts: resume first, then a fresh session if resume was stale.
431
451
  for (let attempt = 0; attempt < 2; attempt++) {
432
452
  const skipResume = attempt > 0;
433
- const args = this._buildArgs(fullPrompt, channel, { skipResume });
434
- this._logSpawn(channel, args, skipResume);
453
+ const args = this._buildArgs(fullPrompt, channel, { skipResume, viaStdin });
454
+ this._logSpawn(channel, args, skipResume, viaStdin);
435
455
 
436
456
  let result;
437
457
  try {
438
- result = await this._runTurn(channel, args);
458
+ result = await this._runTurn(channel, args, viaStdin ? fullPrompt : null);
439
459
  } catch (e) {
440
460
  await this.sendError(channel, `Error: ${this._redact(e.message)}`);
441
461
  return;
@@ -501,7 +521,7 @@ class CopilotAdapter extends BaseAdapter {
501
521
  return this._versionGate;
502
522
  }
503
523
 
504
- _logSpawn(channel, args, skipResume) {
524
+ _logSpawn(channel, args, skipResume, viaStdin = false) {
505
525
  // Log a redacted, prompt-free shape of the command. The prompt is replaced
506
526
  // with a placeholder; tokens never appear in argv but redact defensively.
507
527
  const shown = [];
@@ -509,7 +529,7 @@ class CopilotAdapter extends BaseAdapter {
509
529
  if (args[i] === '-p') { shown.push('-p', '<prompt>'); i++; continue; }
510
530
  shown.push(args[i]);
511
531
  }
512
- this._log(`Spawning copilot ${redactSensitive(shown.join(' '))}${skipResume ? ' (no-resume retry)' : ''}`);
532
+ this._log(`Spawning copilot ${redactSensitive(shown.join(' '))}${viaStdin ? ' (prompt on stdin)' : ''}${skipResume ? ' (no-resume retry)' : ''}`);
513
533
  }
514
534
 
515
535
  /**
@@ -518,7 +538,7 @@ class CopilotAdapter extends BaseAdapter {
518
538
  * the turn. Never rejects on CLI failure — failures come back as
519
539
  * `errorMessage` / `staleSession` / `timedOut` so the caller can react.
520
540
  */
521
- _runTurn(channel, args) {
541
+ _runTurn(channel, args, stdinPrompt = null) {
522
542
  // Stopped while this turn was being prepared: start nothing (no tokens).
523
543
  if (this._stoppedBeforeStart(channel)) return Promise.resolve({ userStopped: true });
524
544
  const [file, ...prefix] = this._resolveExec(this._copilotBin);
@@ -529,7 +549,7 @@ class CopilotAdapter extends BaseAdapter {
529
549
  let proc;
530
550
  try {
531
551
  proc = spawn(file, [...prefix, ...args], {
532
- stdio: ['ignore', 'pipe', 'pipe'],
552
+ stdio: [stdinPrompt != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],
533
553
  env,
534
554
  cwd,
535
555
  detached: !IS_WINDOWS,
@@ -539,6 +559,12 @@ class CopilotAdapter extends BaseAdapter {
539
559
  return resolve({ errorMessage: `Failed to launch Copilot CLI: ${this._redact(e.message)}` });
540
560
  }
541
561
  this._channelProcesses[channel] = proc;
562
+ // The whole prompt, then EOF — Copilot reads stdin to the end before the
563
+ // run starts. A child that exits first turns the write into EPIPE.
564
+ if (stdinPrompt != null && proc.stdin) {
565
+ proc.stdin.on('error', () => {});
566
+ proc.stdin.end(stdinPrompt);
567
+ }
542
568
 
543
569
  // Guard the child's stdio streams against 'error'. When the process is
544
570
  // SIGKILL'd on stop, macOS Node can emit a benign EPIPE/ECONNRESET 'error'
@@ -14,11 +14,12 @@ const fs = require('fs');
14
14
  const path = require('path');
15
15
  const os = require('os');
16
16
  const crypto = require('crypto');
17
- const { execSync } = require('child_process');
17
+ const { execSync, spawnSync } = require('child_process');
18
18
  // spawn() here is the WSL bridge from ../wsl: same signature as
19
19
  // child_process.spawn, and a straight pass-through unless the resolved CLI
20
20
  // lives on the other side of the Windows/WSL boundary.
21
21
  const { spawn } = require('../wsl');
22
+ const { opencodeTranscript } = require('../host-agent');
22
23
 
23
24
  const BaseAdapter = require('./base');
24
25
  const { formatAttachmentsForPrompt, redactSecrets, stripAnsi } = require('./utils');
@@ -102,10 +103,14 @@ class OpenCodeAdapter extends BaseAdapter {
102
103
  * @param {object} opts - BaseAdapter opts plus:
103
104
  * @param {Set} [opts.disabledModules]
104
105
  * @param {string} [opts.workingDir]
106
+ * @param {{session_id: string}} [opts.seedSession] - The OpenCode chat this
107
+ * agent was created from (`agn join`). Each channel's first turn carries a
108
+ * transcript of it, so the agent starts with what was said there.
105
109
  */
106
110
  constructor(opts) {
107
111
  super(opts);
108
112
  this.disabledModules = opts.disabledModules || new Set();
113
+ this._seedSession = opts.seedSession && opts.seedSession.session_id ? opts.seedSession : null;
109
114
  // Pin the channel's glossary into the system prompt.
110
115
  this._usesPinnedContext = true;
111
116
 
@@ -183,7 +188,39 @@ class OpenCodeAdapter extends BaseAdapter {
183
188
  if (sessionId) return content;
184
189
  this._ensureWorkspaceSkill(msgChannel);
185
190
  const context = this._buildSystemContext(msgChannel);
186
- return `${context}\n\n---\n\n${content}`;
191
+ const seed = this._seedTranscript(msgChannel);
192
+ return seed
193
+ ? `${context}\n\n---\n\n${seed}\n\n---\n\n${content}`
194
+ : `${context}\n\n---\n\n${content}`;
195
+ }
196
+
197
+ /**
198
+ * For a channel's first turn: the conversation this agent was created from,
199
+ * read with `opencode export` (never written to), or ''. Not a fork: OpenCode
200
+ * forks of a session that ran tools are refused by Anthropic models, whose
201
+ * thinking blocks are bound to the original conversation. A seed that can
202
+ * no longer be read turns seeding off.
203
+ */
204
+ _seedTranscript(msgChannel) {
205
+ const seed = this._seedSession;
206
+ if (!seed || Object.prototype.hasOwnProperty.call(this._channelSessions, msgChannel)) return '';
207
+ try {
208
+ const r = spawnSync(this._opencodeBinary, ['export', seed.session_id], {
209
+ env: this._spawnEnv(msgChannel), encoding: 'utf-8', timeout: 30000,
210
+ maxBuffer: 64 * 1024 * 1024, windowsHide: true,
211
+ shell: IS_WINDOWS && /\.cmd$/i.test(this._opencodeBinary || ''),
212
+ });
213
+ if (r.status !== 0 || !r.stdout) throw new Error((r.stderr || r.error || `exit ${r.status}`).toString().slice(0, 200));
214
+ const text = opencodeTranscript(JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))));
215
+ if (!text) return '';
216
+ return 'Before you joined this workspace, you were in this OpenCode conversation with the user. '
217
+ + 'It is your own memory, quoted for reference; continue from it.\n\n<previous_conversation>\n'
218
+ + `${text}\n</previous_conversation>`;
219
+ } catch (e) {
220
+ this._log(`Seed conversation ${seed.session_id} unavailable (${e.message}); new channels start fresh`);
221
+ this._seedSession = null;
222
+ return '';
223
+ }
187
224
  }
188
225
 
189
226
  /** Environment the CLI is spawned with. */
@@ -1407,9 +1444,12 @@ class OpenCodeAdapter extends BaseAdapter {
1407
1444
  category = 'unsupported_version';
1408
1445
  } else if (has(/\b(401|403)\b/) || has(/unauthor|invalid api key|invalid_api_key|invalid or revoked api key|api key (?:has been |was )?revoked|authentication|auth(entication)? failed|forbidden|invalid token|no api key|missing api key|permission denied/)) {
1409
1446
  category = 'auth_failed';
1410
- } else if (has(/\b402\b|insufficient (?:balance|credits?|funds)|insufficient_quota|out of credits?|payment required|余额不足|欠费|arrearage/)) {
1447
+ } else if (has(/\b402\b|insufficient (?:balance|credits?|funds)|insufficient_quota|out of credits?|payment required|余额不足|欠费|arrearage/)
1448
+ || has(/allowance\b[^.]{0,60}\bused up|allowance_exhausted/)) {
1411
1449
  // A spent account, not a busy one: waiting does not fix it. Seen in the
1412
- // field as "Insufficient balance" under "undetermined reason".
1450
+ // field as "Insufficient balance" under "undetermined reason", and as a
1451
+ // plan's "Your Pass allowance for this period is used up, and your
1452
+ // account is set not to…" with no status code in the run's error.
1413
1453
  category = 'quota_exhausted';
1414
1454
  } else if (has(/\b429\b/) || has(/rate.?limit|too many requests|quota|overloaded/)) {
1415
1455
  category = 'rate_limited';
@@ -287,7 +287,21 @@ function stripCliNoise(text) {
287
287
  return String(text || '').split(/\r?\n/).filter((l) => !BENIGN_CLI_OUTPUT.test(l)).join('\n');
288
288
  }
289
289
 
290
+ /**
291
+ * Whether a prompt can go to a CLI as one argv element (`-p <prompt>`).
292
+ * Windows caps a whole command line at 32,767 characters and Node fails the
293
+ * spawn itself with ENAMETOOLONG — the system prompt plus a large pinned
294
+ * glossary got there with a one-word message. Linux caps a single argument at
295
+ * 128 KiB. Both limits leave headroom for quoting and the rest of the argv.
296
+ * Past it, an adapter sends the prompt over stdin.
297
+ */
298
+ function promptFitsArgv(prompt, platform = process.platform) {
299
+ const limit = platform === 'win32' ? 24000 : 100000;
300
+ return String(prompt || '').length <= limit;
301
+ }
302
+
290
303
  module.exports = {
304
+ promptFitsArgv,
291
305
  SESSION_DEFAULT_RE,
292
306
  networkErrorText,
293
307
  BENIGN_CLI_OUTPUT,
package/src/cli.js CHANGED
@@ -4,9 +4,11 @@
4
4
  // no-stray-console-window default on Windows. See win-console.js.
5
5
  require('./win-console').installWindowsHideDefault();
6
6
 
7
+ const path = require('path');
7
8
  const { AgentConnector, Daemon } = require('./index');
8
9
  const { hasCredentialMetadata, formatAuthGuidance } = require('./auth-guidance');
9
10
  const { AUTH_MODE_KEY, CLI_LOGIN, isCliLogin } = require('./env');
11
+ const { loginCommandOf } = require('./agent-login');
10
12
 
11
13
  // ---------------------------------------------------------------------------
12
14
  // Arg parsing
@@ -202,7 +204,9 @@ async function cmdCreate(connector, flags, positional) {
202
204
  }
203
205
 
204
206
  try {
205
- connector.addAgent({ name, type, role, path: flags.path || process.cwd() });
207
+ // Stored absolute: a relative --path is relative to this shell, and the
208
+ // daemon that later runs the agent has a different cwd.
209
+ connector.addAgent({ name, type, role, path: flags.path ? path.resolve(String(flags.path)) : process.cwd() });
206
210
 
207
211
  // Signal daemon to pick up the new agent
208
212
  try { connector.sendDaemonCommand('reload'); } catch {}
@@ -386,6 +390,25 @@ async function cmdRuntimes(connector, flags) {
386
390
  // which judges the type again with its agents' env, said Ready. Judge it
387
391
  // the way the daemon launches it: a type is ready when one of its agents
388
392
  // is.
393
+ //
394
+ // That key is that agent's alone: a new agent of the type does not get
395
+ // it. `typeReady` keeps the type's own answer (<type>.env, this
396
+ // process's environment, the CLI's sign-in) for the add form, which
397
+ // otherwise read Ready and added an agent with no key at all.
398
+ const typeReady = !!h.ready;
399
+ // Whether the CLI itself is signed in on this device, keys aside: what an
400
+ // agent added on "the account signed in on the device" runs on, the add
401
+ // form's only choice besides a key. Null for a type with no sign-in. A
402
+ // type ready on a key never said whether it is signed in as well, so
403
+ // only that case is asked again, with keys not counting.
404
+ let signedIn = null;
405
+ if (loginCommandOf(e)) {
406
+ if (!h.installed || !h.ready) signedIn = false;
407
+ else if (h.auth_mode === 'cli_login') signedIn = true;
408
+ else {
409
+ try { signedIn = !!connector.healthCheck(e.name, { cliLogin: true }).ready; } catch { signedIn = false; }
410
+ }
411
+ }
389
412
  let agentEnv = null;
390
413
  if (h.installed && !h.ready) {
391
414
  for (const a of agents) {
@@ -417,6 +440,8 @@ async function cmdRuntimes(connector, flags) {
417
440
  type: e.name,
418
441
  installed: !!h.installed,
419
442
  ready: !!h.ready,
443
+ typeReady,
444
+ signedIn,
420
445
  version: h.version || null,
421
446
  reason: h.reason || null,
422
447
  message: h.message || null,
package/src/daemon.js CHANGED
@@ -17,7 +17,7 @@ const {
17
17
  AUTH_MODE_KEY, CLI_LOGIN, MODEL_MODE_KEY, MODEL_DEFAULT, credentialKeys, isCliLogin, modelKeys, stripForCliLogin, typeEnvFor,
18
18
  } = require('./env');
19
19
  const { configuredModel } = require('./agent-model');
20
- const { getEnhancedEnv, whichBinary, IS_WINDOWS, defaultAgentWorkdir } = require('./paths');
20
+ const { getEnhancedEnv, whichBinary, IS_WINDOWS, defaultAgentWorkdir, resolveAgentWorkdir } = require('./paths');
21
21
  const { hostFreeEnv } = require('./host-agent');
22
22
  const { LogWriter } = require('./log-writer');
23
23
  const { redactDiagnostic } = require('./adapters/health-status');
@@ -733,7 +733,7 @@ class Daemon {
733
733
  type: a.type || 'unknown',
734
734
  status: (proc && proc.state) || 'stopped',
735
735
  model: model || null,
736
- workingDir: a.path || null,
736
+ workingDir: resolveAgentWorkdir(a.path),
737
737
  apiKeyMasked: apiKey ? maskApiKey(apiKey) : null,
738
738
  authMode: this._agentAuthMode(a, apiKey),
739
739
  baseUrlHost: endpointHost(this._configuredBaseUrl(a, typeEnv)),
@@ -1128,7 +1128,10 @@ async _runNodeCommand(n, cmd) {
1128
1128
  // Working directory: use the one the user picked, else a managed folder
1129
1129
  // under the launcher home so every remote-created agent has a clean,
1130
1130
  // predictable home without the user typing a path.
1131
- let workingDir = (args.workingDir || '').trim();
1131
+ // A relative path ("my-project") is taken from the home directory —
1132
+ // stored as typed, it resolved against the daemon's cwd and every run
1133
+ // failed (see resolveAgentWorkdir).
1134
+ let workingDir = resolveAgentWorkdir(args.workingDir);
1132
1135
  if (!workingDir) workingDir = path.join(os.homedir(), '.openagents', 'agents', name);
1133
1136
  try { fs.mkdirSync(workingDir, { recursive: true }); } catch {}
1134
1137
  const r1 = await this._runAgn(['create', name, '--type', type, '--install', '--path', workingDir]);
@@ -1204,8 +1207,8 @@ async _runNodeCommand(n, cmd) {
1204
1207
  // that copy, or the agent keeps running on the old key while the save
1205
1208
  // says ok.
1206
1209
  const unshadow = Object.fromEntries(applied.map((key) => [key, '']));
1207
- const newDir = (args.workingDir || '').trim();
1208
- if (newDir && newDir !== (args.currentWorkingDir || '')) {
1210
+ const newDir = resolveAgentWorkdir(args.workingDir);
1211
+ if (newDir && newDir !== (resolveAgentWorkdir(args.currentWorkingDir) || '')) {
1209
1212
  try { fs.mkdirSync(newDir, { recursive: true }); } catch {}
1210
1213
  // The agent's own env goes with the entry remove/create replace, and
1211
1214
  // for a type that keeps its key on the agent that is the key, the
@@ -1882,7 +1885,7 @@ async _runNodeCommand(n, cmd) {
1882
1885
  }
1883
1886
 
1884
1887
  const env = this._buildAgentEnv(agentCfg);
1885
- const cwd = agentCfg.path || undefined;
1888
+ const cwd = resolveAgentWorkdir(agentCfg.path) || undefined;
1886
1889
 
1887
1890
  while (!this._shuttingDown && !this._stoppedAgents.has(name)) {
1888
1891
  try {
@@ -2053,7 +2056,10 @@ async _runNodeCommand(n, cmd) {
2053
2056
  // explicit `path`, adapters used to fall back to process.cwd(), which on
2054
2057
  // a packaged Windows launcher is C:\WINDOWS\system32 — so writing
2055
2058
  // .claude/skills there failed with EPERM. Root it under ~/.openagents.
2056
- workingDir: agentCfg.path || defaultAgentWorkdir(name),
2059
+ // resolveAgentWorkdir: an agent saved with a relative path (older
2060
+ // launchers stored the web form's text verbatim) runs from the home
2061
+ // directory instead of failing on every write.
2062
+ workingDir: resolveAgentWorkdir(agentCfg.path) || defaultAgentWorkdir(name),
2057
2063
  toolMode: agentCfg.tool_mode || 'skills',
2058
2064
  // The conversation `agn join` created this agent from (Claude Code).
2059
2065
  seedSession: agentCfg.seed_session || null,
package/src/host-agent.js CHANGED
@@ -75,7 +75,14 @@ const AUTH_SETTINGS = {
75
75
  codex: ['CODEX_HOME', 'OPENAI_API_KEY', 'OPENAI_BASE_URL'],
76
76
  codebuddy: ['CODEBUDDY_CONFIG_DIR', 'CODEBUDDY_API_KEY'],
77
77
  gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_GENAI_USE_VERTEXAI'],
78
- opencode: [],
78
+ opencode: [
79
+ 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_DIR', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME',
80
+ 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'GEMINI_API_KEY',
81
+ 'GOOGLE_GENERATIVE_AI_API_KEY', 'GOOGLE_API_KEY', 'GROQ_API_KEY', 'MISTRAL_API_KEY',
82
+ 'DEEPSEEK_API_KEY', 'XAI_API_KEY', 'AZURE_API_KEY', 'AZURE_OPENAI_API_KEY',
83
+ 'GOOGLE_CLOUD_PROJECT', 'VERTEX_LOCATION', 'GOOGLE_APPLICATION_CREDENTIALS',
84
+ 'AWS_REGION', 'AWS_PROFILE',
85
+ ],
79
86
  cursor: ['CURSOR_API_KEY'],
80
87
  };
81
88
  const SECRET_RE = /(KEY|TOKEN|SECRET)$/;
@@ -134,8 +141,67 @@ function snapshotTranscript(src, destDir) {
134
141
  return dest;
135
142
  }
136
143
 
144
+ // ---------------------------------------------------------------------------
145
+ // OpenCode sessions
146
+ // ---------------------------------------------------------------------------
147
+ //
148
+ // OpenCode sets OPENCODE=1 for the commands it runs but no session id, so the
149
+ // session is found by where it runs: the most recently updated one in the
150
+ // directory the command was run from is the chat running it.
151
+
152
+ /** Pick the chat's session from `opencode session list --format json` output. */
153
+ function pickOpencodeSession(sessions, cwd) {
154
+ const want = realpath(cwd);
155
+ const here = (Array.isArray(sessions) ? sessions : [])
156
+ .filter((s) => s && s.id && s.directory && realpath(s.directory) === want)
157
+ .sort((a, b) => (Number(b.updated) || 0) - (Number(a.updated) || 0));
158
+ return here[0] || null;
159
+ }
160
+
161
+ function realpath(p) {
162
+ try { return fs.realpathSync(p); } catch { return path.resolve(String(p || '')); }
163
+ }
164
+
165
+ /** `provider/model` the session runs on, from `opencode export <id>` output. */
166
+ function opencodeSessionModel(exported) {
167
+ const m = exported && exported.info && exported.info.model;
168
+ if (m && m.providerID && m.id) return `${m.providerID}/${m.id}`;
169
+ const msgs = (exported && exported.messages) || [];
170
+ for (let i = msgs.length - 1; i >= 0; i--) {
171
+ const info = msgs[i] && msgs[i].info;
172
+ if (info && info.role === 'assistant' && info.providerID && info.modelID) return `${info.providerID}/${info.modelID}`;
173
+ }
174
+ return null;
175
+ }
176
+
177
+ /**
178
+ * A plain-text transcript of an exported OpenCode session: what each side
179
+ * said and which tools ran, newest part kept when it is longer than
180
+ * `maxChars`. Reasoning is left out.
181
+ */
182
+ function opencodeTranscript(exported, maxChars = 30000) {
183
+ const lines = [];
184
+ for (const msg of (exported && exported.messages) || []) {
185
+ const role = msg && msg.info && msg.info.role === 'assistant' ? 'You' : 'User';
186
+ for (const part of (msg && msg.parts) || []) {
187
+ if (part.type === 'text' && part.text && !part.synthetic) {
188
+ lines.push(`${role}: ${part.text.trim()}`);
189
+ } else if (part.type === 'tool' && part.tool) {
190
+ const state = part.state || {};
191
+ const input = state.input ? JSON.stringify(state.input) : '';
192
+ const output = typeof state.output === 'string' ? state.output.trim() : '';
193
+ lines.push(`[You ran ${part.tool}${input ? ` ${input.slice(0, 500)}` : ''}${output ? ` → ${output.slice(0, 500)}` : ''}]`);
194
+ }
195
+ }
196
+ }
197
+ const text = lines.join('\n\n');
198
+ if (text.length <= maxChars) return text;
199
+ return `[…earlier part omitted…]\n\n${text.slice(text.length - maxChars)}`;
200
+ }
201
+
137
202
  module.exports = {
138
203
  detectHostAgent, sandboxedHost, hostFreeEnv, hostAuthEnv,
139
204
  claudeConfigDir, claudeProjectDir, findClaudeTranscript, snapshotTranscript,
205
+ pickOpencodeSession, opencodeSessionModel, opencodeTranscript,
140
206
  HOST_SESSION_KEYS,
141
207
  };
package/src/join.js CHANGED
@@ -22,9 +22,35 @@ const { AUTH_MODE_KEY, CLI_LOGIN } = require('./env');
22
22
  const { defaultAgentWorkdir } = require('./paths');
23
23
  const {
24
24
  detectHostAgent, sandboxedHost, hostFreeEnv, hostAuthEnv,
25
- claudeConfigDir, findClaudeTranscript,
25
+ claudeConfigDir, findClaudeTranscript, pickOpencodeSession, opencodeSessionModel,
26
26
  } = require('./host-agent');
27
27
 
28
+ /**
29
+ * The OpenCode chat running this command: `{ session_id, directory, model }`,
30
+ * or null. OpenCode exports no session id, so its session list is asked for
31
+ * the newest session in this directory.
32
+ */
33
+ function findOpencodeChat({ env, cwd, run }) {
34
+ const json = (args) => {
35
+ const r = run(args, { env, cwd });
36
+ if (!r || r.status !== 0 || !r.stdout) return null;
37
+ try { return JSON.parse(r.stdout); } catch { return null; }
38
+ };
39
+ const session = pickOpencodeSession(json(['session', 'list', '--format', 'json']), cwd);
40
+ if (!session) return null;
41
+ const exported = json(['export', session.id]);
42
+ return { session_id: session.id, directory: session.directory, model: exported ? opencodeSessionModel(exported) : null };
43
+ }
44
+
45
+ function runOpencodeCli(args, { env, cwd }) {
46
+ const { whichBinary } = require('./paths');
47
+ const bin = whichBinary('opencode') || 'opencode';
48
+ return require('child_process').spawnSync(bin, args, {
49
+ env, cwd, encoding: 'utf-8', timeout: 30000, maxBuffer: 64 * 1024 * 1024,
50
+ shell: process.platform === 'win32' && /\.cmd$/i.test(bin), windowsHide: true,
51
+ });
52
+ }
53
+
28
54
  /**
29
55
  * Browser URL of a workspace, matching the TUI's convention: a localhost/dev
30
56
  * endpoint serves its own web app; everything else lives on the hosted
@@ -181,16 +207,29 @@ async function join({ code, flags = {}, connector, env = process.env, print, dep
181
207
  }
182
208
 
183
209
  // 4. The agent.
184
- const workDir = typeof flags.path === 'string' ? path.resolve(flags.path) : defaultAgentWorkdir(name);
185
210
  const auth = hostAuthEnv(type, env);
186
211
  const agentEnv = { ...auth.env };
187
212
  if (auth.secrets.length === 0) agentEnv[AUTH_MODE_KEY] = CLI_LOGIN;
188
213
 
189
214
  let seed = null;
215
+ // Where the agent works. Claude Code writes a workspace skill (holding the
216
+ // workspace token) into its working directory, so it gets its own; an
217
+ // OpenCode agent keeps that in its agent home and can keep working in the
218
+ // chat's project.
219
+ let defaultDir = null;
190
220
  if (type === 'claude' && host.sessionId) {
191
221
  const transcript = findClaudeTranscript(host.sessionId, claudeConfigDir(env));
192
222
  if (transcript) seed = { session_id: host.sessionId, transcript };
223
+ } else if (type === 'opencode') {
224
+ const chat = findOpencodeChat({ env, cwd: deps.cwd || process.cwd(), run: deps.runOpencode || runOpencodeCli });
225
+ if (chat) {
226
+ seed = { session_id: chat.session_id, directory: chat.directory };
227
+ defaultDir = chat.directory;
228
+ // The OpenCode adapter needs a model on the command line; use the chat's.
229
+ if (chat.model && !agentEnv.OPENCODE_MODEL) agentEnv.OPENCODE_MODEL = chat.model;
230
+ }
193
231
  }
232
+ const workDir = typeof flags.path === 'string' ? path.resolve(flags.path) : (defaultDir || defaultAgentWorkdir(name));
194
233
 
195
234
  connector.addAgent({ name, type, role: 'worker', path: workDir, env: agentEnv });
196
235
  connector.connectWorkspace(name, res.workspaceSlug);
@@ -228,7 +267,9 @@ async function join({ code, flags = {}, connector, env = process.env, print, dep
228
267
  print('');
229
268
  print(`Connected. This agent is now '${name}' in the workspace '${res.workspaceName}': ${url}`);
230
269
  print(`- Runs as: ${runtimeLabel} on ${info.hostname || os.hostname()}, working in ${workDir}`);
231
- if (seed) {
270
+ if (seed && type === 'opencode') {
271
+ print('- Memory: each new workspace thread starts with a transcript of this conversation. This conversation itself is never changed.');
272
+ } else if (seed) {
232
273
  print('- Memory: each new workspace thread starts from a copy of this conversation. This conversation itself is never changed.');
233
274
  } else if (type === 'claude') {
234
275
  print('- Memory: starts fresh (this conversation\'s transcript was not found).');
@@ -238,6 +279,11 @@ async function join({ code, flags = {}, connector, env = process.env, print, dep
238
279
  print(auth.secrets.length
239
280
  ? `- Sign-in: copied ${auth.secrets.join(', ')} from this session into the agent's settings (~/.openagents/daemon.yaml).`
240
281
  : `- Sign-in: uses this machine's ${runtimeLabel} login.`);
282
+ if (type === 'opencode') {
283
+ print(agentEnv.OPENCODE_MODEL
284
+ ? `- Model: ${agentEnv.OPENCODE_MODEL} (the one this conversation uses)`
285
+ : '- Model: none found. Set one before messaging it: agn env opencode --set OPENCODE_MODEL=<provider/model>');
286
+ }
241
287
  print(`- Start at login: ${autostartNote}`);
242
288
  print(`- Undo: agn remove ${name} (and agn autostart --disable to stop starting at login)`);
243
289
  print('');
package/src/paths.js CHANGED
@@ -1095,6 +1095,31 @@ function defaultAgentWorkdir(agentName) {
1095
1095
  return dir;
1096
1096
  }
1097
1097
 
1098
+ /**
1099
+ * The folder an agent's configured `path` names, as an absolute path.
1100
+ *
1101
+ * A path typed in the web form reaches the daemon verbatim, and a bare name
1102
+ * such as `my-agent` used to be stored as-is — relative to whatever the
1103
+ * daemon's cwd happened to be (`/` for a packaged Mac launcher,
1104
+ * C:\WINDOWS\system32 on Windows). Every run then failed on its first write:
1105
+ * `ENOENT: no such file or directory, mkdir 'my-agent/.claude/skills/…'`.
1106
+ *
1107
+ * A relative path is taken from the home directory, where a fresh terminal
1108
+ * starts, and a leading `~` is expanded. Empty input returns null so callers
1109
+ * keep their own default.
1110
+ */
1111
+ function resolveAgentWorkdir(input, home = os.homedir()) {
1112
+ const raw = String(input == null ? '' : input).trim();
1113
+ if (!raw) return null;
1114
+ // An absolute path is returned as typed: normalizing it would rewrite the
1115
+ // separators of a path saved on another OS (`/home/me/proj` reads back as
1116
+ // `\home\me\proj` on Windows) and show the user a folder they never set.
1117
+ if (path.isAbsolute(raw)) return raw;
1118
+ if (raw === '~') return home;
1119
+ if (/^~[\\/]/.test(raw)) return path.join(home, raw.slice(2));
1120
+ return path.join(home, raw);
1121
+ }
1122
+
1098
1123
  /**
1099
1124
  * Reset the two 30s caches that back binary detection. Call this after
1100
1125
  * install / uninstall so a freshly-created bin dir (e.g. ~/.cursor/bin)
@@ -1356,6 +1381,7 @@ module.exports = {
1356
1381
  getRuntimePrefix,
1357
1382
  getCorePrefix,
1358
1383
  defaultAgentWorkdir,
1384
+ resolveAgentWorkdir,
1359
1385
  aiderBinDirs,
1360
1386
  uvToolBinDirs,
1361
1387
  IS_WINDOWS,