@openagents-org/agent-launcher 0.2.220 → 0.2.222

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.220",
3
+ "version": "0.2.222",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -26,6 +26,7 @@ const { buildClaudeSystemPrompt, buildClaudeSkillMd, buildPinnedSections, worksp
26
26
  const { pinnedFingerprint, sampleRecap } = require('./decision-log');
27
27
  const { defaultAgentWorkdir, whichBinary, whereBinary } = require('../paths');
28
28
  const { isPostinstallStub } = require('../postinstall-stub');
29
+ const { claudeConfigDir, claudeProjectDir, snapshotTranscript } = require('../host-agent');
29
30
 
30
31
  const IS_WINDOWS = process.platform === 'win32';
31
32
 
@@ -101,10 +102,16 @@ class ClaudeAdapter extends BaseAdapter {
101
102
  * @param {object} opts - BaseAdapter opts plus:
102
103
  * @param {Set} [opts.disabledModules]
103
104
  * @param {string} [opts.workingDir]
105
+ * @param {{session_id: string, transcript: string}} [opts.seedSession] -
106
+ * A Claude Code conversation this agent was created from (`agn join`).
107
+ * Each channel's first turn forks it, so the agent starts with what was
108
+ * said there without ever writing to it.
104
109
  */
105
110
  constructor(opts) {
106
111
  super(opts);
107
112
  this.disabledModules = opts.disabledModules || new Set();
113
+ this._seedSession = opts.seedSession && opts.seedSession.session_id && opts.seedSession.transcript
114
+ ? opts.seedSession : null;
108
115
  /** @type {'mcp' | 'skills'} Tool integration mode */
109
116
  this.toolMode = opts.toolMode || 'skills';
110
117
  this._channelSessions = {}; // channel → Claude CLI session_id
@@ -160,7 +167,9 @@ class ClaudeAdapter extends BaseAdapter {
160
167
  delete this._channelProcesses[channel];
161
168
  }
162
169
  if (this._channelSessions[channel]) {
163
- delete this._channelSessions[channel];
170
+ // null, not delete: the channel stays known, so a restart starts
171
+ // it fresh instead of forking the seed conversation again.
172
+ this._channelSessions[channel] = null;
164
173
  try { this._saveSessions(); } catch {}
165
174
  this._log(`Restart: cleared session for channel=${channel}`);
166
175
  } else {
@@ -507,17 +516,48 @@ class ClaudeAdapter extends BaseAdapter {
507
516
 
508
517
  // Resume existing conversation (skipped on retry after stale session)
509
518
  const sessionId = this._channelSessions[channelName];
519
+ let seeded = false;
510
520
  if (sessionId && !skipResume) {
511
521
  cmd.push('--resume', sessionId);
522
+ } else if (!skipResume && !Object.prototype.hasOwnProperty.call(this._channelSessions, channelName)) {
523
+ const seed = this._seedArgs();
524
+ if (seed) { cmd.push(...seed); seeded = true; }
512
525
  }
513
526
 
514
527
  // ── Skills mode: write SKILL.md, no MCP server ──
515
528
  if (this.toolMode === 'skills') {
516
- return this._buildSkillsCmd(cmd, channelName);
529
+ return { ...this._buildSkillsCmd(cmd, channelName), seeded };
517
530
  }
518
531
 
519
532
  // ── MCP mode (default): spawn MCP server ──
520
- return this._buildMcpCmd(cmd, channelName);
533
+ return { ...this._buildMcpCmd(cmd, channelName), seeded };
534
+ }
535
+
536
+ /**
537
+ * `--resume <seed> --fork-session` for a channel's first turn, or null.
538
+ * Claude Code resumes only sessions filed under the cwd it runs in, so the
539
+ * seed's transcript is copied there first (complete lines only: the chat it
540
+ * came from may still be open and writing). Copied at each use, so a new
541
+ * channel starts from the conversation as it is now. A transcript that is
542
+ * gone turns seeding off.
543
+ */
544
+ _seedArgs() {
545
+ const seed = this._seedSession;
546
+ if (!seed) return null;
547
+ try {
548
+ const workDir = this.workingDir || defaultAgentWorkdir(this.agentName);
549
+ const destDir = claudeProjectDir(claudeConfigDir(this.agentEnv || process.env), workDir);
550
+ if (path.resolve(path.dirname(seed.transcript)) !== path.resolve(destDir)) {
551
+ snapshotTranscript(seed.transcript, destDir);
552
+ } else if (!fs.existsSync(seed.transcript)) {
553
+ throw new Error('transcript is gone');
554
+ }
555
+ return ['--resume', seed.session_id, '--fork-session'];
556
+ } catch (e) {
557
+ this._log(`Seed conversation ${seed.session_id} unavailable (${e.message}); new channels start fresh`);
558
+ this._seedSession = null;
559
+ return null;
560
+ }
521
561
  }
522
562
 
523
563
  /**
@@ -1180,7 +1220,7 @@ class ClaudeAdapter extends BaseAdapter {
1180
1220
  */
1181
1221
  async _resetSessionForPromptTooLong(msgChannel) {
1182
1222
  this._log('Prompt too long, clearing session and retrying');
1183
- delete this._channelSessions[msgChannel];
1223
+ this._channelSessions[msgChannel] = null;
1184
1224
  this._saveSessions();
1185
1225
  await this._killPersistentProc(msgChannel);
1186
1226
  try {
@@ -1456,6 +1496,7 @@ class ClaudeAdapter extends BaseAdapter {
1456
1496
 
1457
1497
  let mcpConfigFile = null;
1458
1498
  let cmd;
1499
+ let seeded = false;
1459
1500
 
1460
1501
  const cleanEnv = ClaudeAdapter._buildChildEnv(this.agentEnv || process.env);
1461
1502
 
@@ -1494,6 +1535,7 @@ class ClaudeAdapter extends BaseAdapter {
1494
1535
  });
1495
1536
  cmd = built.cmd;
1496
1537
  mcpConfigFile = built.mcpConfigFile;
1538
+ seeded = !!built.seeded;
1497
1539
  } catch (e) {
1498
1540
  await this.sendError(msgChannel, e.message);
1499
1541
  return;
@@ -1512,7 +1554,7 @@ class ClaudeAdapter extends BaseAdapter {
1512
1554
  ]);
1513
1555
  pp.spawnMode = this._mode;
1514
1556
  pp.spawnModel = this.workspaceModel || null;
1515
- const resumed = attempt === 0 && !!this._channelSessions[msgChannel];
1557
+ const resumed = attempt === 0 && (!!this._channelSessions[msgChannel] || seeded);
1516
1558
  this._log(`Spawned persistent process for ${msgChannel} (attempt ${attempt + 1})`);
1517
1559
 
1518
1560
  let result = await this._sendToPersistentProc(pp, effectiveContent);
@@ -8,30 +8,10 @@
8
8
  * ~/.pi/agent/models.json and auth.json untouched.
9
9
  */
10
10
 
11
- const value = (name) => String(process.env[name] || '').trim()
11
+ import launcherConfig from './pi-provider-config.js'
12
12
 
13
- const PROVIDER_DEFAULTS = {
14
- anthropic: {
15
- baseUrl: 'https://api.anthropic.com',
16
- api: 'anthropic-messages',
17
- },
18
- openai: {
19
- baseUrl: 'https://api.openai.com/v1',
20
- api: 'openai-responses',
21
- },
22
- deepseek: {
23
- baseUrl: 'https://api.deepseek.com/v1',
24
- api: 'openai-completions',
25
- },
26
- google: {
27
- baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
28
- api: 'google-generative-ai',
29
- },
30
- openrouter: {
31
- baseUrl: 'https://openrouter.ai/api/v1',
32
- api: 'openai-completions',
33
- },
34
- }
13
+ const { PROVIDER_DEFAULTS, launcherProviderId } = launcherConfig
14
+ const value = (name) => String(process.env[name] || '').trim()
35
15
 
36
16
  function providerKey(provider) {
37
17
  return value('PI_API_KEY') || {
@@ -78,7 +58,13 @@ export default function configureLauncherProvider(pi) {
78
58
  compat.supportsDeveloperRole = false
79
59
  }
80
60
 
81
- pi.registerProvider(provider, {
61
+ // Pi prefers auth.json credentials over an extension's configured key.
62
+ // Match the adapter's process-local provider id when Launcher supplied a
63
+ // key, while keyless relays can still reuse their existing Pi login.
64
+ const providerId = launcherProviderId({
65
+ provider, model, baseUrl: configuredBaseUrl, apiKey: value('PI_API_KEY'),
66
+ })
67
+ pi.registerProvider(providerId, {
82
68
  baseUrl,
83
69
  api,
84
70
  // Pass the resolved secret directly to the process-local provider. This is
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const PROVIDER_DEFAULTS = {
4
+ anthropic: {
5
+ baseUrl: 'https://api.anthropic.com',
6
+ api: 'anthropic-messages',
7
+ },
8
+ openai: {
9
+ baseUrl: 'https://api.openai.com/v1',
10
+ api: 'openai-responses',
11
+ },
12
+ deepseek: {
13
+ baseUrl: 'https://api.deepseek.com/v1',
14
+ api: 'openai-completions',
15
+ },
16
+ google: {
17
+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
18
+ api: 'google-generative-ai',
19
+ },
20
+ openrouter: {
21
+ baseUrl: 'https://openrouter.ai/api/v1',
22
+ api: 'openai-completions',
23
+ },
24
+ };
25
+
26
+ /** Keep Launcher keys separate from native Pi credentials when we can register the provider. */
27
+ function launcherProviderId({ provider, model, baseUrl, apiKey }) {
28
+ const name = String(provider || '').trim().toLowerCase();
29
+ if (name && String(model || '').trim() && String(apiKey || '').trim() &&
30
+ (String(baseUrl || '').trim().replace(/\/+$/, '') || PROVIDER_DEFAULTS[name]?.baseUrl)) {
31
+ return `openagents-${name}`;
32
+ }
33
+ return provider;
34
+ }
35
+
36
+ module.exports = { PROVIDER_DEFAULTS, launcherProviderId };
@@ -64,6 +64,8 @@ const {
64
64
  MIN_PI_VERSION,
65
65
  } = require('./pi-stream');
66
66
 
67
+ const { launcherProviderId } = require('./pi-provider-config');
68
+
67
69
  const IS_WINDOWS = process.platform === 'win32';
68
70
  const LAUNCHER_PROVIDER_EXTENSION = path.join(__dirname, 'pi-launcher-provider.mjs');
69
71
 
@@ -1384,7 +1386,10 @@ class PiAdapter extends BaseAdapter {
1384
1386
  sessionDir: this._sessionDir,
1385
1387
  sessionId,
1386
1388
  appendSystemPrompt,
1387
- provider: cfg.provider,
1389
+ // A stored Pi login wins over an extension's apiKey for the same
1390
+ // provider. Keep Launcher-key requests in a separate provider namespace
1391
+ // so a native login cannot authenticate a different endpoint.
1392
+ provider: launcherProviderId({ ...cfg, apiKey: launcherKey }),
1388
1393
  model: cfg.model,
1389
1394
  thinking: cfg.thinking,
1390
1395
  sessionName: `${this.agentName}/${channel}`,
package/src/autostart.js CHANGED
@@ -19,15 +19,63 @@ const HOME = process.env.HOME || process.env.USERPROFILE || '';
19
19
 
20
20
  const SERVICE_LABEL = 'org.openagents.connector';
21
21
 
22
+ const DEFAULT_PATH = {
23
+ darwin: '/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin',
24
+ linux: '/usr/local/bin:/usr/bin:/bin',
25
+ };
26
+
27
+ // Written into the service when set: what the daemon needs to find the
28
+ // agents' CLIs and reach the network the way the installing shell did.
29
+ // No credentials: a proxy URL with user:pass@ in it is left out.
30
+ const SERVICE_ENV_KEYS = [
31
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL',
32
+ 'HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'NO_PROXY',
33
+ 'https_proxy', 'http_proxy', 'all_proxy', 'no_proxy',
34
+ 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR',
35
+ 'OPENAGENTS_ENDPOINT',
36
+ ];
37
+
38
+ /**
39
+ * The environment a service is written with, taken from `env`. PATH drops
40
+ * entries that belong only to the installing process (npx's cache, a
41
+ * project's node_modules/.bin, relative entries). Returns `{ env, skipped }`,
42
+ * `skipped` naming variables left out because they carry credentials.
43
+ */
44
+ function serviceEnv(env = process.env) {
45
+ const out = {};
46
+ const skipped = [];
47
+ for (const key of SERVICE_ENV_KEYS) {
48
+ const value = env[key];
49
+ if (typeof value !== 'string' || value === '' || /[\r\n]/.test(value)) continue;
50
+ if (/PROXY$/i.test(key) && value.includes('@')) { skipped.push(key); continue; }
51
+ out[key] = value;
52
+ }
53
+ if (out.PATH) {
54
+ const sep = IS_WINDOWS ? ';' : ':';
55
+ out.PATH = out.PATH.split(sep).filter((d) => d && path.isAbsolute(d)
56
+ && !/[\\/]_npx[\\/]/.test(d) && !/[\\/]node_modules[\\/]\.bin$/.test(d)).join(sep);
57
+ }
58
+ return { env: out, skipped };
59
+ }
60
+
22
61
  /**
23
62
  * Enable autostart on login.
63
+ *
64
+ * @param {string} configDir
65
+ * @param {object} [opts]
66
+ * @param {string} [opts.cliPath] - the CLI entry to run; defaults to this
67
+ * package's. Pass a stable one when this package runs from npx's cache.
68
+ * @param {string} [opts.nodeBin]
69
+ * @param {object} [opts.env] - variables for the service (see serviceEnv);
70
+ * without it only a default PATH is written, as before.
24
71
  */
25
- function enable(configDir) {
26
- const nodeBin = whichBinary('node') || process.execPath;
27
- const cliPath = path.resolve(__dirname, '..', 'bin', 'agent-connector.js');
72
+ function enable(configDir, opts = {}) {
73
+ const nodeBin = opts.nodeBin || whichBinary('node') || process.execPath;
74
+ const cliPath = opts.cliPath || path.resolve(__dirname, '..', 'bin', 'agent-connector.js');
75
+ const env = { PATH: DEFAULT_PATH[process.platform] || DEFAULT_PATH.linux, ...(opts.env || {}) };
28
76
 
29
- if (IS_MACOS) return _enableMacOS(nodeBin, cliPath, configDir);
30
- if (IS_LINUX) return _enableLinux(nodeBin, cliPath, configDir);
77
+ if (IS_MACOS) return _enableMacOS(nodeBin, cliPath, configDir, env);
78
+ if (IS_LINUX) return _enableLinux(nodeBin, cliPath, configDir, env);
31
79
  if (IS_WINDOWS) return _enableWindows(nodeBin, cliPath, configDir);
32
80
  throw new Error(`Autostart not supported on ${process.platform}`);
33
81
  }
@@ -67,14 +115,15 @@ function isEnabled() {
67
115
 
68
116
  // ---- macOS: launchd ----
69
117
 
70
- function _enableMacOS(nodeBin, cliPath, configDir) {
71
- const plistDir = path.join(HOME, 'Library', 'LaunchAgents');
72
- fs.mkdirSync(plistDir, { recursive: true });
118
+ function _xml(v) {
119
+ return String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
120
+ }
73
121
 
74
- const plistPath = path.join(plistDir, `${SERVICE_LABEL}.plist`);
122
+ function renderPlist(nodeBin, cliPath, configDir, env) {
75
123
  const logPath = path.join(configDir, 'daemon.log');
76
-
77
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
124
+ const envXml = Object.entries(env)
125
+ .map(([k, v]) => ` <key>${_xml(k)}</key>\n <string>${_xml(v)}</string>`).join('\n');
126
+ return `<?xml version="1.0" encoding="UTF-8"?>
78
127
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
79
128
  <plist version="1.0">
80
129
  <dict>
@@ -82,8 +131,8 @@ function _enableMacOS(nodeBin, cliPath, configDir) {
82
131
  <string>${SERVICE_LABEL}</string>
83
132
  <key>ProgramArguments</key>
84
133
  <array>
85
- <string>${nodeBin}</string>
86
- <string>${cliPath}</string>
134
+ <string>${_xml(nodeBin)}</string>
135
+ <string>${_xml(cliPath)}</string>
87
136
  <string>up</string>
88
137
  <string>--foreground</string>
89
138
  </array>
@@ -92,16 +141,23 @@ function _enableMacOS(nodeBin, cliPath, configDir) {
92
141
  <key>KeepAlive</key>
93
142
  <true/>
94
143
  <key>StandardOutPath</key>
95
- <string>${logPath}</string>
144
+ <string>${_xml(logPath)}</string>
96
145
  <key>StandardErrorPath</key>
97
- <string>${logPath}</string>
146
+ <string>${_xml(logPath)}</string>
98
147
  <key>EnvironmentVariables</key>
99
148
  <dict>
100
- <key>PATH</key>
101
- <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>
149
+ ${envXml}
102
150
  </dict>
103
151
  </dict>
104
152
  </plist>`;
153
+ }
154
+
155
+ function _enableMacOS(nodeBin, cliPath, configDir, env) {
156
+ const plistDir = path.join(HOME, 'Library', 'LaunchAgents');
157
+ fs.mkdirSync(plistDir, { recursive: true });
158
+
159
+ const plistPath = path.join(plistDir, `${SERVICE_LABEL}.plist`);
160
+ const plist = renderPlist(nodeBin, cliPath, configDir, env);
105
161
 
106
162
  fs.writeFileSync(plistPath, plist, 'utf-8');
107
163
  execSync(`launchctl load -w "${plistPath}"`, { stdio: 'pipe', timeout: 5000 });
@@ -119,26 +175,36 @@ function _disableMacOS() {
119
175
 
120
176
  // ---- Linux: systemd user unit ----
121
177
 
122
- function _enableLinux(nodeBin, cliPath, configDir) {
123
- const unitDir = path.join(HOME, '.config', 'systemd', 'user');
124
- fs.mkdirSync(unitDir, { recursive: true });
125
-
126
- const unitPath = path.join(unitDir, 'openagents-connector.service');
178
+ function _systemdQuote(v) {
179
+ return `"${String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
180
+ }
127
181
 
128
- const unit = `[Unit]
182
+ function renderUnit(nodeBin, cliPath, env) {
183
+ const envLines = Object.entries(env)
184
+ .map(([k, v]) => `Environment=${_systemdQuote(`${k}=${v}`)}`).join('\n');
185
+ return `[Unit]
129
186
  Description=OpenAgents Connector Daemon
130
187
  After=network.target
131
188
 
132
189
  [Service]
133
190
  Type=simple
134
- ExecStart=${nodeBin} ${cliPath} up --foreground
191
+ ExecStart=${_systemdQuote(nodeBin)} ${_systemdQuote(cliPath)} up --foreground
135
192
  Restart=on-failure
136
193
  RestartSec=10
137
- Environment=PATH=/usr/local/bin:/usr/bin:/bin
194
+ ${envLines}
138
195
 
139
196
  [Install]
140
197
  WantedBy=default.target
141
198
  `;
199
+ }
200
+
201
+ function _enableLinux(nodeBin, cliPath, configDir, env) {
202
+ const unitDir = path.join(HOME, '.config', 'systemd', 'user');
203
+ fs.mkdirSync(unitDir, { recursive: true });
204
+
205
+ const unitPath = path.join(unitDir, 'openagents-connector.service');
206
+
207
+ const unit = renderUnit(nodeBin, cliPath, env);
142
208
 
143
209
  fs.writeFileSync(unitPath, unit, 'utf-8');
144
210
  execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 5000 });
@@ -175,4 +241,4 @@ function _disableWindows() {
175
241
  return { enabled: false };
176
242
  }
177
243
 
178
- module.exports = { enable, disable, isEnabled };
244
+ module.exports = { enable, disable, isEnabled, serviceEnv, renderPlist, renderUnit };
package/src/cli-models.js CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  const os = require('os');
19
+ const { stripVTControlCharacters } = require('node:util');
19
20
  // spawn() here is the WSL bridge from ./wsl: same signature as
20
21
  // child_process.spawn, and a straight pass-through unless the resolved CLI
21
22
  // lives on the other side of the Windows/WSL boundary.
@@ -124,12 +125,48 @@ function parseQoderModels(text) {
124
125
  return [...seen.values()].slice(0, MAX_MODELS);
125
126
  }
126
127
 
128
+ /**
129
+ * Pi --list-models prints the configured providers' catalog as a table, not a
130
+ * per-model subscription entitlement check. Qualify ids so identical model
131
+ * names on different signed-in providers remain selectable without ambiguity.
132
+ */
133
+ function parsePiModels(text, env = {}) {
134
+ const selectedProvider = String(env.PI_PROVIDER || '').trim().toLowerCase();
135
+ const seen = new Map();
136
+ let inTable = false;
137
+ for (const raw of stripVTControlCharacters(String(text || '')).split(/\r?\n/)) {
138
+ const fields = raw.trim().split(/\s+/);
139
+ if (fields.join(' ') === 'provider model context max-out thinking images') {
140
+ inTable = true;
141
+ continue;
142
+ }
143
+ if (!inTable || fields.length !== 6 ||
144
+ !/^\d+(?:\.\d+)?[KM]?$/i.test(fields[2]) ||
145
+ !/^\d+(?:\.\d+)?[KM]?$/i.test(fields[3]) ||
146
+ !/^(yes|no)$/.test(fields[4]) || !/^(yes|no)$/.test(fields[5])) continue;
147
+ const [provider, model] = fields;
148
+ if (!/^[\w.-]+$/.test(provider) || !cleanId(model)) continue;
149
+ if (selectedProvider && provider.toLowerCase() !== selectedProvider) continue;
150
+ const id = cleanId(`${provider}/${model}`);
151
+ if (!id || seen.has(id)) continue;
152
+ seen.set(id, { id, label: cleanLabel(`${model} (${provider})`, id) });
153
+ if (seen.size >= MAX_MODELS) break;
154
+ }
155
+ return [...seen.values()];
156
+ }
157
+
127
158
  /**
128
159
  * How each CLI is asked. Claude Code has no command for it; its SDK control
129
160
  * protocol does, and a run that is sent the request and then end-of-input
130
161
  * answers and exits without a prompt ever reaching a model.
131
162
  */
132
163
  const LISTERS = {
164
+ pi: {
165
+ args: ['--no-approve', '--no-extensions', '--no-skills', '--list-models'],
166
+ parse: parsePiModels,
167
+ timeoutMs: 30_000,
168
+ env: { PI_SKIP_VERSION_CHECK: '1', NO_COLOR: '1' },
169
+ },
133
170
  codex: {
134
171
  args: ['debug', 'models'],
135
172
  parse: parseCodexModels,
@@ -279,9 +316,9 @@ async function listCliModels(connector, type, opts = {}) {
279
316
  });
280
317
  // A run killed for taking too long may still have answered: Claude Code
281
318
  // replies before it finishes starting up.
282
- const models = lister.parse(res.stdout);
319
+ const models = lister.parse(res.stdout, agentEnv);
283
320
  if (models.length) return { type, ok: true, models };
284
321
  return fail(res.error || 'The CLI listed no models.');
285
322
  }
286
323
 
287
- module.exports = { listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels };
324
+ module.exports = { listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels, parsePiModels };
package/src/cli.js CHANGED
@@ -594,19 +594,7 @@ function connectKnownWorkspace(connector, name, ref, connectionId) {
594
594
  }
595
595
  }
596
596
 
597
- /**
598
- * Browser URL of a workspace, matching the TUI's convention: a localhost/dev
599
- * endpoint serves its own web app; everything else lives on the hosted
600
- * dashboard. This is what a freshly paired user actually needs next — NOT
601
- * another CLI command.
602
- */
603
- function workspaceWebUrl(slug, endpoint) {
604
- const ep = String(endpoint || '');
605
- const isLocal = ep.includes('localhost') || ep.includes('127.0.0.1');
606
- return isLocal
607
- ? `${ep.replace(/\/+$/, '')}/${slug}`
608
- : `https://workspace.openagents.org/${slug}`;
609
- }
597
+ const { workspaceWebUrl, pairDevice } = require('./join');
610
598
 
611
599
  /**
612
600
  * `agn device <connect|status>` — pair this device (formerly "node") to a
@@ -652,40 +640,7 @@ async function cmdNode(connector, flags, positional) {
652
640
 
653
641
  print('Connecting this device to your workspace...');
654
642
  try {
655
- const res = await connector.redeemNodePairingCode(code, info);
656
- // A code always redeems against ONE workspace; if that workspace is one
657
- // this device already belongs to, this is a re-pair, not a new pairing.
658
- // recordPairing below still runs — it refreshes the (possibly rotated)
659
- // credential in place — but the user should hear "already paired", not
660
- // a duplicate "connected".
661
- const alreadyPaired = priorPairings.some(
662
- (p) => p.node_id === res.nodeId,
663
- );
664
- // recordPairing, not saveNode: this device can be a node in several
665
- // workspaces at once, and a bare save would drop the others' pairings.
666
- // Freeze legacy bindings before another owner adds a connection here.
667
- const prior = priorPairings.filter((p) => p.workspace_id === res.workspaceId);
668
- if (prior.length === 1) for (const agent of connector.config.getAgents()) {
669
- if (!agent.node_id && (agent.network === prior[0].workspace_slug || agent.network === prior[0].workspace_id))
670
- connector.config.updateAgent(agent.name, { node_id: prior[0].node_id });
671
- }
672
- nodeCfg.recordPairing(info.nodeKey, {
673
- node_id: res.nodeId,
674
- owner_email: res.ownerEmail,
675
- workspace_id: res.workspaceId,
676
- workspace_slug: res.workspaceSlug,
677
- workspace_name: res.workspaceName,
678
- endpoint: connector.workspace.endpoint,
679
- token: res.token,
680
- });
681
- // Register the workspace locally so agents created on this node can use it.
682
- connector.config.addNetwork({
683
- id: res.workspaceId,
684
- slug: res.workspaceSlug,
685
- name: res.workspaceName,
686
- endpoint: connector.workspace.endpoint,
687
- token: res.token,
688
- });
643
+ const { res, alreadyPaired } = await pairDevice(connector, code, info, priorPairings);
689
644
  if (alreadyPaired) {
690
645
  print(`Already paired with '${res.workspaceName}' (${res.workspaceSlug}) — refreshed this device's credential.`);
691
646
  } else {
@@ -737,6 +692,20 @@ async function cmdNode(connector, flags, positional) {
737
692
  process.exitCode = 1;
738
693
  }
739
694
 
695
+ /**
696
+ * `agn join <pairing-code>` — run from inside an agent (Claude Code, Codex,
697
+ * ...): connect that agent to the workspace. See join.js.
698
+ */
699
+ async function cmdJoin(connector, flags, positional) {
700
+ const { join } = require('./join');
701
+ process.exitCode = await join({
702
+ code: positional[0] || flags.code,
703
+ flags: { ...flags, autostart: flags['no-autostart'] ? false : flags.autostart },
704
+ connector,
705
+ print,
706
+ });
707
+ }
708
+
740
709
  async function cmdDisconnect(connector, _flags, positional) {
741
710
  const name = positional[0];
742
711
  if (!name) { print('Usage: agn disconnect <agent-name>'); return; }
@@ -1282,6 +1251,8 @@ Commands:
1282
1251
  runtimes List installed runtimes
1283
1252
  device connect <code> Pair this device (formerly "node") to a workspace with a pairing code
1284
1253
  device status Show the workspaces this device is paired with (alias: node)
1254
+ join <code> Run from inside Claude Code, Codex, ...: connect that agent to a workspace
1255
+ [--name <agent-name>] [--type <type>] [--path <dir>] [--no-autostart]
1285
1256
  connect <agent> <token> Connect agent to workspace (or --workspace <slug> for a paired one)
1286
1257
  disconnect <agent> Disconnect agent from workspace
1287
1258
  env <type> [--set K=V] View/set env vars for agent type
@@ -1327,6 +1298,8 @@ async function main() {
1327
1298
  (cmd === 'up' && flags.foreground) ||
1328
1299
  cmd === 'tui' ||
1329
1300
  cmd === 'update' ||
1301
+ // npx …@latest join: already the newest, and its output is read by an agent
1302
+ cmd === 'join' ||
1330
1303
  flags['no-update-check'] ||
1331
1304
  process.env.OPENAGENTS_SKIP_UPDATE_CHECK === '1' ||
1332
1305
  (cmd === 'status' && process.argv.length <= 2 && process.stdin.isTTY);
@@ -1371,6 +1344,7 @@ async function main() {
1371
1344
  search: () => cmdSearch(connector, flags, positional),
1372
1345
  runtimes: () => cmdRuntimes(connector, flags),
1373
1346
  connect: () => cmdConnect(connector, flags, positional),
1347
+ join: () => cmdJoin(connector, flags, positional),
1374
1348
  device: () => cmdNode(connector, flags, positional),
1375
1349
  devices: () => cmdNode(connector, flags, positional),
1376
1350
  node: () => cmdNode(connector, flags, positional), // legacy spelling
package/src/daemon.js CHANGED
@@ -18,6 +18,7 @@ const {
18
18
  } = require('./env');
19
19
  const { configuredModel } = require('./agent-model');
20
20
  const { getEnhancedEnv, whichBinary, IS_WINDOWS, defaultAgentWorkdir } = require('./paths');
21
+ const { hostFreeEnv } = require('./host-agent');
21
22
  const { LogWriter } = require('./log-writer');
22
23
  const { redactDiagnostic } = require('./adapters/health-status');
23
24
  const { installCommandFor } = require('./probe');
@@ -1664,8 +1665,10 @@ async _runNodeCommand(n, cmd) {
1664
1665
 
1665
1666
  const logFd = fs.openSync(logFile, 'a');
1666
1667
 
1667
- // Build env with enhanced PATH (ensures node/npm are findable)
1668
- const env = getEnhancedEnv();
1668
+ // Build env with enhanced PATH (ensures node/npm are findable). Started
1669
+ // from inside an agent's chat (`agn join`), the daemon must not carry
1670
+ // that chat's session variables on to the agents it spawns.
1671
+ const env = getEnhancedEnv(hostFreeEnv(process.env));
1669
1672
  // Ensure the directory containing the node binary is on PATH
1670
1673
  const nodeBinDir = path.dirname(bin);
1671
1674
  if (env.PATH && !env.PATH.includes(nodeBinDir)) {
@@ -2052,6 +2055,8 @@ async _runNodeCommand(n, cmd) {
2052
2055
  // .claude/skills there failed with EPERM. Root it under ~/.openagents.
2053
2056
  workingDir: agentCfg.path || defaultAgentWorkdir(name),
2054
2057
  toolMode: agentCfg.tool_mode || 'skills',
2058
+ // The conversation `agn join` created this agent from (Claude Code).
2059
+ seedSession: agentCfg.seed_session || null,
2055
2060
  // Live runtime/connectivity status → daemon.status.json (Agents list/TUI).
2056
2061
  onStatus: (update) => this._applyAdapterStatus(name, info, update),
2057
2062
  logSink: (level, msg) => this._logAs(`adapter [${name}]`, level, msg),
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Keep the launcher somewhere that lasts. `npx @openagents-org/agent-launcher
5
+ * join <code>` runs this package out of npx's cache, which npm may clear at
6
+ * any time; a daemon or a login service pointing there would stop working
7
+ * when it does. So `join` first puts the package where install.sh puts it,
8
+ * ~/.openagents/nodejs/node_modules, with the same `agn` shims, and runs
9
+ * everything long-lived from there.
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const os = require('os');
14
+ const path = require('path');
15
+
16
+ const PKG = '@openagents-org/agent-launcher';
17
+
18
+ function runningFromNpxCache(dir) {
19
+ return /[\\/]_npx[\\/]/.test(dir);
20
+ }
21
+
22
+ function readVersion(dir) {
23
+ try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version || null; } catch { return null; }
24
+ }
25
+
26
+ /** -1, 0 or 1, comparing dotted numeric versions (pre-release tags ignored). */
27
+ function compareVersions(a, b) {
28
+ const pa = String(a).split('-')[0].split('.').map((n) => parseInt(n, 10) || 0);
29
+ const pb = String(b).split('-')[0].split('.').map((n) => parseInt(n, 10) || 0);
30
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
31
+ const d = (pa[i] || 0) - (pb[i] || 0);
32
+ if (d) return d > 0 ? 1 : -1;
33
+ }
34
+ return 0;
35
+ }
36
+
37
+ /**
38
+ * Make sure a lasting copy of this package exists and return where it is.
39
+ *
40
+ * @param {object} [opts]
41
+ * @param {string} [opts.pkgRoot] - this package's directory
42
+ * @param {string} [opts.home]
43
+ * @param {string} [opts.nodeBin] - node for the shims when there is no portable one
44
+ * @returns {{ cliPath: string, nodeBin: string, copied: boolean, version: string|null }}
45
+ */
46
+ function ensureDurableInstall(opts = {}) {
47
+ const pkgRoot = opts.pkgRoot || path.resolve(__dirname, '..');
48
+ const home = opts.home || os.homedir();
49
+ const prefix = path.join(home, '.openagents', 'nodejs');
50
+ const portableNode = path.join(prefix, 'bin', process.platform === 'win32' ? 'node.exe' : 'node');
51
+ const nodeBin = fs.existsSync(portableNode) ? portableNode : (opts.nodeBin || process.execPath);
52
+
53
+ if (!runningFromNpxCache(pkgRoot)) {
54
+ return { cliPath: path.join(pkgRoot, 'bin', 'agent-connector.js'), nodeBin, copied: false, version: readVersion(pkgRoot) };
55
+ }
56
+
57
+ const modules = path.join(prefix, 'node_modules');
58
+ const target = path.join(modules, ...PKG.split('/'));
59
+ const own = readVersion(pkgRoot);
60
+ const installed = readVersion(target);
61
+ let copied = false;
62
+ if (!installed || (own && compareVersions(installed, own) < 0)) {
63
+ fs.rmSync(target, { recursive: true, force: true });
64
+ fs.mkdirSync(path.dirname(target), { recursive: true });
65
+ fs.cpSync(pkgRoot, target, { recursive: true, dereference: true });
66
+ copied = true;
67
+ }
68
+
69
+ // Runtime dependencies sit next to the package in npx's node_modules.
70
+ const npxModules = path.resolve(pkgRoot, '..', '..');
71
+ let deps = {};
72
+ try { deps = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf-8')).dependencies || {}; } catch {}
73
+ for (const dep of Object.keys(deps)) {
74
+ const from = path.join(npxModules, ...dep.split('/'));
75
+ const to = path.join(modules, ...dep.split('/'));
76
+ if (fs.existsSync(path.join(to, 'package.json')) || !fs.existsSync(from)) continue;
77
+ fs.mkdirSync(path.dirname(to), { recursive: true });
78
+ fs.cpSync(from, to, { recursive: true, dereference: true });
79
+ }
80
+
81
+ // install.sh keeps a package.json at the prefix so a later `npm --prefix`
82
+ // install there does not prune what is not listed in it.
83
+ const prefixPkg = path.join(prefix, 'package.json');
84
+ let manifest = { private: true, dependencies: {} };
85
+ try { manifest = JSON.parse(fs.readFileSync(prefixPkg, 'utf-8')); } catch {}
86
+ manifest.dependencies = { ...(manifest.dependencies || {}) };
87
+ manifest.dependencies[PKG] = readVersion(target) || own || 'latest';
88
+ for (const dep of Object.keys(deps)) {
89
+ if (!manifest.dependencies[dep]) manifest.dependencies[dep] = readVersion(path.join(modules, ...dep.split('/'))) || deps[dep];
90
+ }
91
+ fs.writeFileSync(prefixPkg, JSON.stringify(manifest));
92
+
93
+ writeShims(modules, nodeBin);
94
+ return { cliPath: path.join(target, 'bin', 'agent-connector.js'), nodeBin, copied, version: readVersion(target) };
95
+ }
96
+
97
+ /** `agn`, `openagents` and `agent-connector` in node_modules/.bin, as install.sh writes them. */
98
+ function writeShims(modules, nodeBin) {
99
+ const binDir = path.join(modules, '.bin');
100
+ fs.mkdirSync(binDir, { recursive: true });
101
+ const entry = path.join(modules, ...PKG.split('/'), 'bin', 'agent-connector.js');
102
+ for (const name of ['agn', 'openagents', 'agent-connector']) {
103
+ if (process.platform === 'win32') {
104
+ fs.writeFileSync(path.join(binDir, `${name}.cmd`), `@echo off\r\n"${nodeBin}" "${entry}" %*\r\n`);
105
+ } else {
106
+ const file = path.join(binDir, name);
107
+ // rm first: a symlink into the package's bin would be followed by the
108
+ // write and overwrite the real entry point (see install.sh).
109
+ fs.rmSync(file, { force: true });
110
+ fs.writeFileSync(file, `#!/bin/sh\nexec "${nodeBin}" "${entry}" "$@"\n`, { mode: 0o755 });
111
+ }
112
+ }
113
+ return binDir;
114
+ }
115
+
116
+ module.exports = { ensureDurableInstall, runningFromNpxCache, compareVersions, writeShims };
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The agent a command runs inside of. `agn join` is meant to be run BY an
5
+ * agent (Claude Code, Codex, ...) that a person already has open: it reads
6
+ * which one from the variables that agent sets for the commands it runs, so
7
+ * the workspace agent it creates is the same kind, signed in the same way,
8
+ * and (for Claude Code) starts from the same conversation.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+
15
+ // Checked in order; the first match wins. `session` is the env var holding
16
+ // the host's own session id, when the host exports one.
17
+ const HOSTS = [
18
+ { type: 'claude', label: 'Claude Code', match: (e) => has(e.CLAUDE_CODE_SESSION_ID) || has(e.CLAUDECODE), session: 'CLAUDE_CODE_SESSION_ID' },
19
+ { type: 'codex', label: 'Codex', match: (e) => has(e.CODEX_SESSION_ID) || has(e.CODEX_THREAD_ID), session: 'CODEX_SESSION_ID' },
20
+ { type: 'codebuddy', label: 'CodeBuddy', match: (e) => has(e.CODEBUDDY_SESSION_ID), session: 'CODEBUDDY_SESSION_ID' },
21
+ { type: 'gemini', label: 'Gemini CLI', match: (e) => has(e.GEMINI_CLI), session: 'GEMINI_CLI_SESSION_ID' },
22
+ { type: 'opencode', label: 'OpenCode', match: (e) => has(e.OPENCODE) || has(e.OPENCODE_SESSION_ID), session: 'OPENCODE_SESSION_ID' },
23
+ { type: 'cursor', label: 'Cursor', match: (e) => has(e.CURSOR_AGENT), session: null },
24
+ ];
25
+
26
+ function has(v) { return typeof v === 'string' && v.trim() !== ''; }
27
+
28
+ /** `{ type, label, sessionId }` for the agent running this process, or null. */
29
+ function detectHostAgent(env = process.env) {
30
+ for (const host of HOSTS) {
31
+ if (!host.match(env)) continue;
32
+ const sessionId = host.session && has(env[host.session]) ? env[host.session].trim() : null;
33
+ return { type: host.type, label: host.label, sessionId };
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /** Whether this process runs inside a sandbox that a background daemon would inherit. */
39
+ function sandboxedHost(env = process.env) {
40
+ return has(env.CODEX_SANDBOX) || has(env.CODEX_SANDBOX_NETWORK_DISABLED);
41
+ }
42
+
43
+ // Variables a host sets for the commands it runs that describe ITS session.
44
+ // Handed on to a daemon (and from it to the agents it spawns), they make a
45
+ // spawned CLI believe it runs inside the host's session.
46
+ const HOST_SESSION_KEYS = new Set([
47
+ 'CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_SESSION_ID', 'CLAUDE_AGENT_SDK_VERSION', 'AI_AGENT',
48
+ 'CODEX_SESSION_ID', 'CODEX_THREAD_ID', 'CODEX_CI', 'CODEX_SANDBOX', 'CODEX_SANDBOX_NETWORK_DISABLED', 'CODEX_VERSION',
49
+ 'CODEBUDDY_SESSION_ID', 'CODEBUDDY_TOOL_CALL_ID', 'CODEBUDDY_CONVERSATION_REQUEST_ID',
50
+ 'CODEBUDDY_SESSION_KIND', 'CODEBUDDY_SESSION_NAME', 'CODEBUDDY_SESSION_LOG',
51
+ 'GEMINI_CLI', 'GEMINI_CLI_SESSION_ID', 'OPENCODE_SESSION_ID', 'CURSOR_AGENT', 'CURSOR_TRACE_ID',
52
+ ]);
53
+ // CLAUDE_CODE_* is mostly the host session's own wiring; these say how it signs in.
54
+ const KEPT_CLAUDE_CODE_KEYS = new Set(['CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']);
55
+
56
+ /** `env` without the host session's own variables. */
57
+ function hostFreeEnv(env = process.env) {
58
+ const out = {};
59
+ for (const [key, value] of Object.entries(env)) {
60
+ if (value === undefined || HOST_SESSION_KEYS.has(key)) continue;
61
+ if (key.startsWith('CLAUDE_CODE_') && !KEPT_CLAUDE_CODE_KEYS.has(key)) continue;
62
+ out[key] = value;
63
+ }
64
+ return out;
65
+ }
66
+
67
+ // How each type signs in and where it keeps its state, beyond the keys the
68
+ // registry lists. Copied onto the new agent so it runs the way the host does.
69
+ const AUTH_SETTINGS = {
70
+ claude: [
71
+ 'CLAUDE_CONFIG_DIR', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_OAUTH_TOKEN',
72
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
73
+ 'ANTHROPIC_VERTEX_PROJECT_ID', 'CLOUD_ML_REGION', 'AWS_REGION', 'AWS_PROFILE',
74
+ ],
75
+ codex: ['CODEX_HOME', 'OPENAI_API_KEY', 'OPENAI_BASE_URL'],
76
+ codebuddy: ['CODEBUDDY_CONFIG_DIR', 'CODEBUDDY_API_KEY'],
77
+ gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_GENAI_USE_VERTEXAI'],
78
+ opencode: [],
79
+ cursor: ['CURSOR_API_KEY'],
80
+ };
81
+ const SECRET_RE = /(KEY|TOKEN|SECRET)$/;
82
+
83
+ /**
84
+ * The host's sign-in settings for `type`: `{ env, secrets }`, where `secrets`
85
+ * lists the names (never the values) of credentials among them.
86
+ */
87
+ function hostAuthEnv(type, env = process.env) {
88
+ const out = {};
89
+ const secrets = [];
90
+ for (const key of AUTH_SETTINGS[type] || []) {
91
+ if (!has(env[key])) continue;
92
+ out[key] = env[key];
93
+ if (SECRET_RE.test(key)) secrets.push(key);
94
+ }
95
+ return { env: out, secrets };
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Claude Code transcripts
100
+ // ---------------------------------------------------------------------------
101
+
102
+ function claudeConfigDir(env = process.env) {
103
+ return has(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : path.join(os.homedir(), '.claude');
104
+ }
105
+
106
+ /** Claude Code keeps a cwd's sessions in projects/<cwd with every non-alphanumeric as '-'>. */
107
+ function claudeProjectDir(configDir, cwd) {
108
+ return path.join(configDir, 'projects', String(cwd).replace(/[^A-Za-z0-9]/g, '-'));
109
+ }
110
+
111
+ /** The transcript file of a Claude Code session, searched across projects, or null. */
112
+ function findClaudeTranscript(sessionId, configDir) {
113
+ if (!/^[A-Za-z0-9-]+$/.test(String(sessionId || ''))) return null;
114
+ const projects = path.join(configDir, 'projects');
115
+ let dirs = [];
116
+ try { dirs = fs.readdirSync(projects); } catch { return null; }
117
+ for (const d of dirs) {
118
+ const file = path.join(projects, d, `${sessionId}.jsonl`);
119
+ try { if (fs.statSync(file).isFile()) return file; } catch {}
120
+ }
121
+ return null;
122
+ }
123
+
124
+ /**
125
+ * Copy a transcript into `destDir` under the same session id, keeping only
126
+ * complete lines: the source may be a chat that is still writing to it.
127
+ */
128
+ function snapshotTranscript(src, destDir) {
129
+ const text = fs.readFileSync(src, 'utf-8');
130
+ const end = text.lastIndexOf('\n');
131
+ fs.mkdirSync(destDir, { recursive: true, mode: 0o700 });
132
+ const dest = path.join(destDir, path.basename(src));
133
+ fs.writeFileSync(dest, end >= 0 ? text.slice(0, end + 1) : '', { mode: 0o600 });
134
+ return dest;
135
+ }
136
+
137
+ module.exports = {
138
+ detectHostAgent, sandboxedHost, hostFreeEnv, hostAuthEnv,
139
+ claudeConfigDir, claudeProjectDir, findClaudeTranscript, snapshotTranscript,
140
+ HOST_SESSION_KEYS,
141
+ };
package/src/join.js ADDED
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `agn join <pairing-code>` — connect the agent this command runs inside of.
5
+ *
6
+ * Meant to be pasted into an agent a person already has open (Claude Code,
7
+ * Codex, ...), which runs it with npx. In one step it:
8
+ * 1. puts the launcher somewhere lasting (npx's cache is not),
9
+ * 2. pairs this device with the workspace the code belongs to,
10
+ * 3. creates a workspace agent of the same kind as the host, signed in the
11
+ * way the host is, and — for Claude Code — starting each new workspace
12
+ * thread from a copy of the host's conversation,
13
+ * 4. turns on start-at-login and starts the daemon that runs it.
14
+ * What it prints is written for the host agent to relay to its person.
15
+ */
16
+
17
+ const os = require('os');
18
+ const path = require('path');
19
+
20
+ const nodeCfg = require('./node-config');
21
+ const { AUTH_MODE_KEY, CLI_LOGIN } = require('./env');
22
+ const { defaultAgentWorkdir } = require('./paths');
23
+ const {
24
+ detectHostAgent, sandboxedHost, hostFreeEnv, hostAuthEnv,
25
+ claudeConfigDir, findClaudeTranscript,
26
+ } = require('./host-agent');
27
+
28
+ /**
29
+ * Browser URL of a workspace, matching the TUI's convention: a localhost/dev
30
+ * endpoint serves its own web app; everything else lives on the hosted
31
+ * dashboard.
32
+ */
33
+ function workspaceWebUrl(slug, endpoint) {
34
+ const ep = String(endpoint || '');
35
+ const isLocal = ep.includes('localhost') || ep.includes('127.0.0.1');
36
+ return isLocal
37
+ ? `${ep.replace(/\/+$/, '')}/${slug}`
38
+ : `https://workspace.openagents.org/${slug}`;
39
+ }
40
+
41
+ /**
42
+ * Redeem a pairing code and record the pairing: node.json, plus the workspace
43
+ * as a network in daemon.yaml so agents on this device can use it.
44
+ *
45
+ * @returns {Promise<{ res: object, alreadyPaired: boolean }>}
46
+ */
47
+ async function pairDevice(connector, code, info, priorPairings) {
48
+ const res = await connector.redeemNodePairingCode(code, info);
49
+ // A code always redeems against ONE workspace; if that workspace is one
50
+ // this device already belongs to, this is a re-pair, not a new pairing.
51
+ // recordPairing below still runs — it refreshes the (possibly rotated)
52
+ // credential in place.
53
+ const alreadyPaired = priorPairings.some((p) => p.node_id === res.nodeId);
54
+ // recordPairing, not saveNode: this device can be a node in several
55
+ // workspaces at once, and a bare save would drop the others' pairings.
56
+ // Freeze legacy bindings before another owner adds a connection here.
57
+ const prior = priorPairings.filter((p) => p.workspace_id === res.workspaceId);
58
+ if (prior.length === 1) for (const agent of connector.config.getAgents()) {
59
+ if (!agent.node_id && (agent.network === prior[0].workspace_slug || agent.network === prior[0].workspace_id))
60
+ connector.config.updateAgent(agent.name, { node_id: prior[0].node_id });
61
+ }
62
+ nodeCfg.recordPairing(info.nodeKey, {
63
+ node_id: res.nodeId,
64
+ owner_email: res.ownerEmail,
65
+ workspace_id: res.workspaceId,
66
+ workspace_slug: res.workspaceSlug,
67
+ workspace_name: res.workspaceName,
68
+ endpoint: connector.workspace.endpoint,
69
+ token: res.token,
70
+ });
71
+ connector.config.addNetwork({
72
+ id: res.workspaceId,
73
+ slug: res.workspaceSlug,
74
+ name: res.workspaceName,
75
+ endpoint: connector.workspace.endpoint,
76
+ token: res.token,
77
+ });
78
+ return { res, alreadyPaired };
79
+ }
80
+
81
+ /**
82
+ * `<type>-<host>`, lowercased, made unique among `taken`. A long host name
83
+ * keeps its leading words up to 16 characters ("raphaels-macbook-pro" →
84
+ * "raphaels-macbook").
85
+ */
86
+ function defaultAgentName(type, hostname, taken) {
87
+ const words = String(hostname || '').split('.')[0].toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
88
+ let host = '';
89
+ for (const w of words) {
90
+ const next = host ? `${host}-${w}` : w;
91
+ if (next.length > 16) break;
92
+ host = next;
93
+ }
94
+ if (!host && words.length) host = words[0].slice(0, 16);
95
+ const base = host ? `${type}-${host}` : type;
96
+ let name = base;
97
+ for (let i = 2; taken.has(name); i++) name = `${base}-${i}`;
98
+ return name;
99
+ }
100
+
101
+ const SERVICE_NAMES = { darwin: 'launchd', linux: 'systemd', win32: 'Task Scheduler' };
102
+
103
+ /**
104
+ * @param {object} p
105
+ * @param {string} p.code
106
+ * @param {object} p.flags - name, type, path, autostart (false with --no-autostart)
107
+ * @param {object} p.connector - AgentConnector
108
+ * @param {object} [p.env]
109
+ * @param {(line: string) => void} p.print
110
+ * @param {object} [p.deps] - seams for tests: ensureDurableInstall, autostart, sleep, gatherDeviceInfo
111
+ * @returns {Promise<number>} exit code
112
+ */
113
+ async function join({ code, flags = {}, connector, env = process.env, print, deps = {} }) {
114
+ const ensureDurable = deps.ensureDurableInstall || require('./durable-install').ensureDurableInstall;
115
+ const autostart = deps.autostart || require('./autostart');
116
+ const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
117
+ const gatherInfo = deps.gatherDeviceInfo || nodeCfg.gatherDeviceInfo;
118
+
119
+ if (!code) {
120
+ print('Usage: agn join <pairing-code> [--name <agent-name>] [--type <agent-type>]');
121
+ print('Run it from inside the agent you want to connect (Claude Code, Codex, ...).');
122
+ print('Get a pairing code from your workspace: Connect an agent.');
123
+ return 1;
124
+ }
125
+
126
+ // 1. Which agent is this? Decided before the code is used, so a refusal
127
+ // leaves it valid for another try.
128
+ const detected = detectHostAgent(env);
129
+ const type = flags.type || (detected && detected.type);
130
+ if (!type) {
131
+ print("Could not tell which agent this is running in: no Claude Code, Codex, CodeBuddy, Gemini CLI, OpenCode or Cursor session variables are set.");
132
+ print('Run this from inside that agent, or name its type: agn join <code> --type <type>');
133
+ print('To connect this machine without an agent, use: agn device connect <code>');
134
+ return 1;
135
+ }
136
+ if (!connector.registry.getEntry(type)) {
137
+ print(`Unknown agent type '${type}'. Run \`agn search\` to see the supported types.`);
138
+ return 1;
139
+ }
140
+ const host = detected && detected.type === type ? detected : { type, label: type, sessionId: null };
141
+ if (sandboxedHost(env)) {
142
+ print(`This is running inside ${host.label}'s sandbox. A background service started from here would stay`);
143
+ print('inside it, without network access, so nothing was changed and the code is still valid.');
144
+ print('Run the same command again outside the sandbox (approve running it with full access).');
145
+ return 1;
146
+ }
147
+
148
+ // 2. A lasting copy of the launcher, for the daemon and the login service.
149
+ let durable = null;
150
+ try {
151
+ durable = ensureDurable({ nodeBin: process.execPath });
152
+ } catch (e) {
153
+ print(`Warning: could not install the launcher under ~/.openagents (${e.message}).`);
154
+ print('The agent will run until this machine restarts; install it for good with: curl -fsSL https://openagents.org/install.sh | bash');
155
+ }
156
+
157
+ // 3. Pair this device, under a name for the agent that is free here.
158
+ let info;
159
+ try {
160
+ info = gatherInfo();
161
+ } catch (e) {
162
+ print(`Could not read ${nodeCfg.NODE_FILE}: ${e.message}`);
163
+ return 1;
164
+ }
165
+ const taken = new Set(connector.config.getAgents().map((a) => a.name));
166
+ const name = typeof flags.name === 'string' && flags.name.trim()
167
+ ? flags.name.trim()
168
+ : defaultAgentName(type, info.hostname || os.hostname(), taken);
169
+ if (taken.has(name)) {
170
+ print(`An agent named '${name}' already exists on this device. Run it again with another --name.`);
171
+ return 1;
172
+ }
173
+ const priorPairings = nodeCfg.listPairings().filter((p) => p.node_id);
174
+ let res;
175
+ try {
176
+ ({ res } = await pairDevice(connector, code, info, priorPairings));
177
+ } catch (e) {
178
+ print(`Could not connect: ${e.message}`);
179
+ print('Pairing codes work once and expire after 30 minutes. Get a new one from your workspace.');
180
+ return 1;
181
+ }
182
+
183
+ // 4. The agent.
184
+ const workDir = typeof flags.path === 'string' ? path.resolve(flags.path) : defaultAgentWorkdir(name);
185
+ const auth = hostAuthEnv(type, env);
186
+ const agentEnv = { ...auth.env };
187
+ if (auth.secrets.length === 0) agentEnv[AUTH_MODE_KEY] = CLI_LOGIN;
188
+
189
+ let seed = null;
190
+ if (type === 'claude' && host.sessionId) {
191
+ const transcript = findClaudeTranscript(host.sessionId, claudeConfigDir(env));
192
+ if (transcript) seed = { session_id: host.sessionId, transcript };
193
+ }
194
+
195
+ connector.addAgent({ name, type, role: 'worker', path: workDir, env: agentEnv });
196
+ connector.connectWorkspace(name, res.workspaceSlug);
197
+ connector.config.updateAgent(name, { node_id: res.nodeId, ...(seed ? { seed_session: seed } : {}) });
198
+
199
+ // 5. Start at login, and run now.
200
+ if (connector.getDaemonPid()) {
201
+ connector.stopDaemon();
202
+ for (let i = 0; i < 25 && connector.getDaemonPid(); i++) await sleep(200);
203
+ }
204
+ let autostartNote;
205
+ if (flags.autostart === false) {
206
+ autostartNote = 'off (--no-autostart): after a restart, run `agn up` to bring it back';
207
+ } else if (!durable) {
208
+ autostartNote = 'off: the launcher is not installed for good (see the warning above)';
209
+ } else {
210
+ try {
211
+ const { env: serviceVars, skipped } = autostart.serviceEnv(hostFreeEnv(env));
212
+ autostart.enable(connector._configDir, { cliPath: durable.cliPath, nodeBin: durable.nodeBin, env: serviceVars });
213
+ autostartNote = `on (${SERVICE_NAMES[process.platform] || process.platform})`;
214
+ if (skipped.length) autostartNote += `; ${skipped.join(', ')} left out because it holds a password`;
215
+ } catch (e) {
216
+ autostartNote = `off (${String(e.message || e).split('\n')[0]}): after a restart, run \`agn up\``;
217
+ }
218
+ }
219
+ // A login service may have started the daemon already; start it if not.
220
+ for (let i = 0; i < 15 && !connector.getDaemonPid(); i++) await sleep(200);
221
+ if (!connector.getDaemonPid()) {
222
+ connector.startDaemon(durable ? [durable.cliPath, 'up', '--foreground'] : undefined);
223
+ }
224
+
225
+ // 6. What happened, for the host agent to pass on.
226
+ const url = workspaceWebUrl(res.workspaceSlug, connector.workspace.endpoint);
227
+ const runtimeLabel = host === detected ? host.label : (connector.registry.getEntry(type).label || type);
228
+ print('');
229
+ print(`Connected. This agent is now '${name}' in the workspace '${res.workspaceName}': ${url}`);
230
+ print(`- Runs as: ${runtimeLabel} on ${info.hostname || os.hostname()}, working in ${workDir}`);
231
+ if (seed) {
232
+ print('- Memory: each new workspace thread starts from a copy of this conversation. This conversation itself is never changed.');
233
+ } else if (type === 'claude') {
234
+ print('- Memory: starts fresh (this conversation\'s transcript was not found).');
235
+ } else {
236
+ print(`- Memory: starts fresh (carrying a ${host.label} conversation over is not supported yet).`);
237
+ }
238
+ print(auth.secrets.length
239
+ ? `- Sign-in: copied ${auth.secrets.join(', ')} from this session into the agent's settings (~/.openagents/daemon.yaml).`
240
+ : `- Sign-in: uses this machine's ${runtimeLabel} login.`);
241
+ print(`- Start at login: ${autostartNote}`);
242
+ print(`- Undo: agn remove ${name} (and agn autostart --disable to stop starting at login)`);
243
+ print('');
244
+ print(`Tell the user to open the workspace and message @${name}.`);
245
+ return 0;
246
+ }
247
+
248
+ module.exports = { join, pairDevice, workspaceWebUrl, defaultAgentName };