@openagents-org/agent-launcher 0.2.224 → 0.2.225

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.225",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -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. */
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('');