opencode-acp-client 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/README.md +220 -2
- package/README.zh.md +199 -0
- package/dist/acp/capabilities.d.ts +168 -0
- package/dist/acp/capabilities.js +240 -0
- package/dist/acp/capabilities.js.map +1 -0
- package/dist/acp/client.d.ts +241 -0
- package/dist/acp/client.js +767 -0
- package/dist/acp/client.js.map +1 -0
- package/dist/acp/types.d.ts +228 -0
- package/dist/acp/types.js +23 -0
- package/dist/acp/types.js.map +1 -0
- package/dist/acp-replay.d.ts +60 -0
- package/dist/acp-replay.js +188 -0
- package/dist/acp-replay.js.map +1 -0
- package/dist/contract.d.ts +435 -0
- package/dist/contract.js +126 -0
- package/dist/contract.js.map +1 -0
- package/dist/daemons.d.ts +39 -0
- package/dist/daemons.js +112 -0
- package/dist/daemons.js.map +1 -0
- package/dist/index.d.ts +268 -0
- package/dist/index.js +1882 -0
- package/dist/index.js.map +1 -0
- package/dist/opencode-bin.d.ts +73 -0
- package/dist/opencode-bin.js +109 -0
- package/dist/opencode-bin.js.map +1 -0
- package/dist/project.d.ts +81 -0
- package/dist/project.js +230 -0
- package/dist/project.js.map +1 -0
- package/dist/server.d.ts +743 -0
- package/dist/server.js +5029 -0
- package/dist/server.js.map +1 -0
- package/dist/session-map.d.ts +89 -0
- package/dist/session-map.js +305 -0
- package/dist/session-map.js.map +1 -0
- package/dist/sessions-command.d.ts +70 -0
- package/dist/sessions-command.js +188 -0
- package/dist/sessions-command.js.map +1 -0
- package/dist/sse.d.ts +40 -0
- package/dist/sse.js +147 -0
- package/dist/sse.js.map +1 -0
- package/dist/state.d.ts +161 -0
- package/dist/state.js +135 -0
- package/dist/state.js.map +1 -0
- package/dist/subagent-sessions.d.ts +71 -0
- package/dist/subagent-sessions.js +107 -0
- package/dist/subagent-sessions.js.map +1 -0
- package/dist/translate/events.d.ts +231 -0
- package/dist/translate/events.js +1244 -0
- package/dist/translate/events.js.map +1 -0
- package/dist/upgrade.d.ts +56 -0
- package/dist/upgrade.js +162 -0
- package/dist/upgrade.js.map +1 -0
- package/package.json +66 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1882 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* CLI entry: `oc-acp-client -- <agent command> [args...]`
|
|
4
|
+
*
|
|
5
|
+
* This is the CLI of an ACP **client**: the process speaks ACP to the agent on
|
|
6
|
+
* stdio and serves the opencode v2 HTTP/SSE surface, so the opencode v2 TUI can
|
|
7
|
+
* be its interface. Any ACP agent works - the agent is whatever follows `--`.
|
|
8
|
+
*
|
|
9
|
+
* The agent command is everything after `--`, so we never have to understand
|
|
10
|
+
* another tool's flag syntax:
|
|
11
|
+
*
|
|
12
|
+
* oc-acp-client -- <agent command> [args...]
|
|
13
|
+
* oc-acp-client -- <agent command> [args...]
|
|
14
|
+
* oc-acp-client --port 4096 -- npx -y @agentclientprotocol/claude-agent-acp
|
|
15
|
+
*
|
|
16
|
+
* Prints the listening URL on stdout as a single JSON line so scripts (and the
|
|
17
|
+
* e2e harness) can read it without guessing a port.
|
|
18
|
+
*
|
|
19
|
+
* Starting the opencode v2 TUI against this server is the default, and the only
|
|
20
|
+
* path where a v2 client is *required*. `--no-tui` (or `--bridge-port`, which
|
|
21
|
+
* implies it) serves the same surface to any other v2 client, the test
|
|
22
|
+
* harness, or looking at the raw `/api/*` by hand. The TUI is the client verified
|
|
23
|
+
* end to end here; any client attaches to the same OpenAPI surface (with the caveat noted
|
|
24
|
+
* at `--bridge-port`: its state roots are its own, not ours).
|
|
25
|
+
*
|
|
26
|
+
* The client binary is selected by `OPENCODE_BIN` (or `opencode` on `PATH`);
|
|
27
|
+
* there is no flag for it.
|
|
28
|
+
*/
|
|
29
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
30
|
+
import { createServer } from 'node:net';
|
|
31
|
+
import { accessSync, constants, createWriteStream, mkdtempSync, readFileSync, realpathSync } from 'node:fs';
|
|
32
|
+
import { homedir, tmpdir } from 'node:os';
|
|
33
|
+
import { createHash } from 'node:crypto';
|
|
34
|
+
import { basename, delimiter, isAbsolute, join, resolve } from 'node:path';
|
|
35
|
+
import { createInterface } from 'node:readline';
|
|
36
|
+
import { fileURLToPath } from 'node:url';
|
|
37
|
+
import { daemonsDir, isAlive, listDaemons, pruneDaemons, registerDaemon, unregisterDaemon } from './daemons.js';
|
|
38
|
+
import { agentBindingLabel, SessionMap, sessionMapPath } from './session-map.js';
|
|
39
|
+
import { PACKAGE_NAME, PACKAGE_VERSION, planUpgrade, runUpgrade } from './upgrade.js';
|
|
40
|
+
import { countSessions, DEFAULT_PAGE, listSessions, renderSessions, } from './sessions-command.js';
|
|
41
|
+
import { BridgeServer } from './server.js';
|
|
42
|
+
import { ENV_BIN, MIN_MAJOR_VERSION, describeVersion, installHint, readOpenCodeVersion, resolveOpenCodeBinary, upgradeHint, } from './opencode-bin.js';
|
|
43
|
+
/**
|
|
44
|
+
* opencode's own subcommands — `opencode --help` lists exactly these. When the
|
|
45
|
+
* user's first bare word is one of them, the command means NATIVE opencode
|
|
46
|
+
* behaviour (`oc-acp-client models -- …` ≡ `opencode models …`): no
|
|
47
|
+
* bridge, no TUI, the argv is handed to the opencode binary as-is and the exit
|
|
48
|
+
* code is its exit code. The directory claim must not touch them — the earlier
|
|
49
|
+
* parser treated `models` as the workspace positional and started a bridge+TUI
|
|
50
|
+
* with `models` in the TUI's argv, which is neither spelling's semantics.
|
|
51
|
+
*/
|
|
52
|
+
/**
|
|
53
|
+
* Words opencode uses as subcommands, kept ONLY to explain the change.
|
|
54
|
+
*
|
|
55
|
+
* This tool used to forward these straight to the opencode binary: `oc-acp-client upgrade`
|
|
56
|
+
* upgraded *opencode*, `auth`/`mcp`/`plugin` managed opencode's local state. That was
|
|
57
|
+
* wrong — the two products share a name prefix and nothing else. `upgrade`/`update` are
|
|
58
|
+
* now this package's own (see `src/upgrade.ts`), and the rest are refused with a hint
|
|
59
|
+
* rather than silently running opencode. `models`, `api` and `session` used to be WRAPPED
|
|
60
|
+
* (answered by the agent through the bridge); that plumbing counted on the bare word
|
|
61
|
+
* reaching opencode's handler, so it is gone with it — the TUI already shows the agent's
|
|
62
|
+
* models, and `/model` is the gesture that picks one.
|
|
63
|
+
*/
|
|
64
|
+
const OPENCODE_OWNED_WORDS = new Set([
|
|
65
|
+
'uninstall',
|
|
66
|
+
'acp',
|
|
67
|
+
'api',
|
|
68
|
+
'debug',
|
|
69
|
+
'auth',
|
|
70
|
+
'mcp',
|
|
71
|
+
'plugin',
|
|
72
|
+
'models',
|
|
73
|
+
'stats',
|
|
74
|
+
'mini',
|
|
75
|
+
'run',
|
|
76
|
+
'session',
|
|
77
|
+
'service',
|
|
78
|
+
'reload',
|
|
79
|
+
'pair',
|
|
80
|
+
'serve',
|
|
81
|
+
]);
|
|
82
|
+
/**
|
|
83
|
+
* opencode subcommands whose ANSWER depends on which server answers them —
|
|
84
|
+
* so a raw passthrough would be wrong: `models` against opencode's own daemon
|
|
85
|
+
* lists the DAEMON's models, not the ACP agent's, and a user comparing that
|
|
86
|
+
* list with what their TUI can actually pick would see two different worlds
|
|
87
|
+
* (the agent's models arrive via the bridge's config-option plumbing). These
|
|
88
|
+
* are WRAPPED: the bridge starts server-only, and the opencode binary runs
|
|
89
|
+
* with `--server <bridge>` so its own official handler renders the answer —
|
|
90
|
+
* same binary, same output format, but the data is the agent's. Everything
|
|
91
|
+
* else (auth, mcp, plugin, upgrade, …) is the user's local opencode business
|
|
92
|
+
* and stays a raw passthrough.
|
|
93
|
+
*/
|
|
94
|
+
const WRAPPED_SUBCOMMANDS = new Set(['models', 'api', 'session']);
|
|
95
|
+
/**
|
|
96
|
+
* Run a WRAPPED opencode subcommand against a throwaway bridge.
|
|
97
|
+
*
|
|
98
|
+
* `models`/`api`/`session` answer from the server they are pointed at, so the
|
|
99
|
+
* native daemon's answers would be a different world than the TUI the user
|
|
100
|
+
* runs. The bridge starts server-only (no TUI), the opencode binary runs with
|
|
101
|
+
* `--server <bridge>` — its own handler renders, byte-identical formatting —
|
|
102
|
+
* and the exit code is mirrored. The agent must be ready first (`models` reads
|
|
103
|
+
* the catalog the agent's initialize advertises), hence the catalog wait; a
|
|
104
|
+
* user-visible delay is inherent to spawning the agent and is the same delay
|
|
105
|
+
* the TUI pays at startup.
|
|
106
|
+
*/
|
|
107
|
+
/**
|
|
108
|
+
* Run a WRAPPED opencode subcommand against a throwaway bridge.
|
|
109
|
+
*
|
|
110
|
+
* `models`/`api`/`session` answer from the server they are pointed at, so the
|
|
111
|
+
* native daemon's answers would be a different world than the TUI the user
|
|
112
|
+
* runs. The bridge starts SERVER-ONLY IN A CHILD PROCESS — ★ not in this
|
|
113
|
+
* process: spawning the opencode binary synchronously (`execFileSync`, so the
|
|
114
|
+
* exit code is ours) blocks this process's event loop, and an in-process HTTP
|
|
115
|
+
* server cannot answer while blocked. Measured: opencode's 5s health probe
|
|
116
|
+
* timed out against a perfectly healthy bridge — the exact bug this child
|
|
117
|
+
* split fixes. The child bridge waits for the agent's catalog (models reads it),
|
|
118
|
+
* then this process runs the opencode binary with `--server <child bridge>`,
|
|
119
|
+
* its own official handler rendering the output, and mirrors the exit code.
|
|
120
|
+
*/
|
|
121
|
+
async function runWrappedSubcommand(args, binary, argv) {
|
|
122
|
+
const bridgePort = await freePort();
|
|
123
|
+
const entry = fileURLToPath(import.meta.url);
|
|
124
|
+
const bridgeEnv = {
|
|
125
|
+
...process.env,
|
|
126
|
+
OPENCODE_ACP_CLIENT_SESSION_MAP: sessionMapPath(),
|
|
127
|
+
OPENCODE_ACP_CLIENT_EAGER_CATALOG: '1',
|
|
128
|
+
};
|
|
129
|
+
// The child bridge runs this same entry with our server-only plumbing.
|
|
130
|
+
const bridge = spawn(process.execPath, [
|
|
131
|
+
entry,
|
|
132
|
+
'--no-tui',
|
|
133
|
+
'--bridge-port',
|
|
134
|
+
String(bridgePort),
|
|
135
|
+
'--bridge-host',
|
|
136
|
+
'127.0.0.1',
|
|
137
|
+
args.directory,
|
|
138
|
+
'--',
|
|
139
|
+
args.agentCommand,
|
|
140
|
+
...args.agentArgs,
|
|
141
|
+
], { stdio: ['ignore', 'inherit', 'inherit'], env: bridgeEnv });
|
|
142
|
+
const url = `http://127.0.0.1:${bridgePort}`;
|
|
143
|
+
process.stderr.write(`[bridge] answering 'opencode ${args.nativeSubcommand}' from ${url}\n`);
|
|
144
|
+
try {
|
|
145
|
+
await waitHealthy(url, 30_000, 500);
|
|
146
|
+
// Only `models` reads the catalog: its answer IS the agent's model
|
|
147
|
+
// advertisement, which arrives with the agent's own startup (dsh ~8s).
|
|
148
|
+
// `api` and `session` answer whatever is there the moment they ask —
|
|
149
|
+
// waiting for a catalog they do not read once made `api GET /api/info`
|
|
150
|
+
// sit through a 60s deadline for an agent that never advertises models
|
|
151
|
+
// (measured: the probe timed out before opencode ever ran).
|
|
152
|
+
if (args.nativeSubcommand === 'models') {
|
|
153
|
+
await waitCatalogReady(url, 60_000, 1_000);
|
|
154
|
+
}
|
|
155
|
+
// The opencode argv, minus the `-- <agent>` tail, plus --server pointing
|
|
156
|
+
// here. A user-typed --server must not survive: exactly one server answers.
|
|
157
|
+
const dash = argv.indexOf('--');
|
|
158
|
+
const userArgs = (dash === -1 ? argv : argv.slice(0, dash)).filter((word, i, all) => !(word === '--server' || all[i - 1] === '--server') && !/^--server=/.test(word));
|
|
159
|
+
execFileSync(binary.path, [...userArgs, '--server', url], {
|
|
160
|
+
stdio: 'inherit',
|
|
161
|
+
killSignal: 'SIGINT',
|
|
162
|
+
});
|
|
163
|
+
process.exitCode = 0;
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
const status = err.status;
|
|
167
|
+
process.exitCode = status === undefined ? 1 : status;
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
bridge.kill('SIGTERM');
|
|
171
|
+
await new Promise((resolve) => {
|
|
172
|
+
const gone = setTimeout(() => {
|
|
173
|
+
bridge.kill('SIGKILL');
|
|
174
|
+
resolve();
|
|
175
|
+
}, 3_000);
|
|
176
|
+
bridge.once('exit', () => {
|
|
177
|
+
clearTimeout(gone);
|
|
178
|
+
resolve();
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
process.exit(process.exitCode ?? 0);
|
|
183
|
+
}
|
|
184
|
+
/** An OS-assigned free TCP port, reserved so the child can race no one. */
|
|
185
|
+
async function freePort() {
|
|
186
|
+
return new Promise((resolve, reject) => {
|
|
187
|
+
const probe = createServer();
|
|
188
|
+
probe.listen(0, '127.0.0.1', () => {
|
|
189
|
+
const address = probe.address();
|
|
190
|
+
const port = typeof address === 'object' && address ? address.port : 0;
|
|
191
|
+
probe.close(() => resolve(port));
|
|
192
|
+
});
|
|
193
|
+
probe.on('error', reject);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** Poll until the child's model catalog is real (not the placeholder). */
|
|
197
|
+
async function waitCatalogReady(url, timeoutMs, stepMs) {
|
|
198
|
+
const deadline = Date.now() + timeoutMs;
|
|
199
|
+
for (;;) {
|
|
200
|
+
try {
|
|
201
|
+
const response = await fetch(`${url}/api/model`);
|
|
202
|
+
if (response.ok) {
|
|
203
|
+
const body = (await response.json());
|
|
204
|
+
// ★ A real row, by id — not by provider. An agent that groups nothing
|
|
205
|
+
// (codex-acp) publishes all of its models under the `acp` provider too, so
|
|
206
|
+
// "some provider is not acp" never became true and this poll ran to its
|
|
207
|
+
// deadline against an agent that had answered at once.
|
|
208
|
+
const rows = body.data ?? [];
|
|
209
|
+
if (rows.some((m) => (m.id ?? m.modelID) !== undefined && (m.id ?? m.modelID) !== 'default'))
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
// transient — the poll loop is the point
|
|
215
|
+
}
|
|
216
|
+
if (Date.now() >= deadline)
|
|
217
|
+
return;
|
|
218
|
+
await new Promise((resolve) => setTimeout(resolve, stepMs));
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Poll the child bridge's health until it answers or the deadline passes. */
|
|
222
|
+
function waitHealthy(url, timeoutMs, stepMs) {
|
|
223
|
+
const deadline = Date.now() + timeoutMs;
|
|
224
|
+
const attempt = async () => {
|
|
225
|
+
try {
|
|
226
|
+
const response = await fetch(`${url}/api/info`);
|
|
227
|
+
if (response.ok)
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
// not up yet
|
|
232
|
+
}
|
|
233
|
+
if (Date.now() >= deadline)
|
|
234
|
+
throw new Error(`the wrapped-bridge never came up at ${url}`);
|
|
235
|
+
await new Promise((resolve) => setTimeout(resolve, stepMs));
|
|
236
|
+
return attempt();
|
|
237
|
+
};
|
|
238
|
+
return attempt();
|
|
239
|
+
}
|
|
240
|
+
function sameDirectory(a, b) {
|
|
241
|
+
const normalise = (path) => {
|
|
242
|
+
try {
|
|
243
|
+
return realpathSync(path);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return resolve(path);
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
return normalise(a) === normalise(b);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* `-c`/`--continue`: the newest remembered session for this directory, and the agent that
|
|
253
|
+
* owns it. The map is now the only source: without a session there is no way to know which
|
|
254
|
+
* agent to ask, so the CLI errors instead of falling back to a blank conversation.
|
|
255
|
+
*/
|
|
256
|
+
export function newestContinueEntry(entries, directory) {
|
|
257
|
+
const matches = entries
|
|
258
|
+
.filter(([, entry]) => entry.agent !== undefined &&
|
|
259
|
+
entry.directory !== undefined &&
|
|
260
|
+
sameDirectory(entry.directory, directory))
|
|
261
|
+
.sort((a, b) => b[1].updatedAt - a[1].updatedAt);
|
|
262
|
+
const top = matches[0];
|
|
263
|
+
return top ? { visibleId: top[0], agent: top[1].agent } : undefined;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Translate a `--session <id>` value into the id the agent will answer to.
|
|
267
|
+
*
|
|
268
|
+
* Exported and pure so the startup contract is assertable at its own layer: the id
|
|
269
|
+
* the TUI shows (`ses_…`) is never the agent's own id (a UUID), and sending it raw
|
|
270
|
+
* to `session/load` is what made a resumed session silently restart empty — the
|
|
271
|
+
* agent answered "Internal error" and the bridge opened a brand-new session under
|
|
272
|
+
* the requested id. The session map holds the pairing; an unknown id passes through
|
|
273
|
+
* as given (the agent's load then answers for whether it exists), so agent-native
|
|
274
|
+
* ids learned elsewhere keep working.
|
|
275
|
+
*/
|
|
276
|
+
export function resolveSessionId(requested, log = () => { }, launch) {
|
|
277
|
+
if (!requested)
|
|
278
|
+
return undefined;
|
|
279
|
+
const map = new SessionMap(() => { });
|
|
280
|
+
if (launch) {
|
|
281
|
+
const owner = map.agentFor(requested);
|
|
282
|
+
const ownLabel = agentBindingLabel({ command: launch.command, args: [...(launch.args ?? [])] });
|
|
283
|
+
if (owner && agentBindingLabel(owner) !== ownLabel) {
|
|
284
|
+
throw new Error(`session ${requested} belongs to '${agentBindingLabel(owner)}', not '${ownLabel}'\n` +
|
|
285
|
+
` One client drives one agent: launch with '${agentBindingLabel(owner)}' ` +
|
|
286
|
+
`(or use -c for this agent's newest conversation).`);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const acpId = map.acpIdFor(requested);
|
|
290
|
+
if (acpId) {
|
|
291
|
+
log(`[bridge] session map: ${requested} is the agent's ${acpId}`);
|
|
292
|
+
return acpId;
|
|
293
|
+
}
|
|
294
|
+
// ★ A `ses_…` id with no map entry is provably unknown, not "maybe an
|
|
295
|
+
// agent-native id": `ses_` is THIS bridge's namespace (the agent mints UUIDs,
|
|
296
|
+
// and an agent-native id pasted from the agent's own UI passes through above).
|
|
297
|
+
// Continuing anyway made the whole resume run against an id the agent has
|
|
298
|
+
// never heard of: session/load answered "Internal error", the failure
|
|
299
|
+
// fallback started a brand-new agent session under that id, and the tab came
|
|
300
|
+
// up titled `[not resumed] <dir>` — measured end to end, twice. Failing here
|
|
301
|
+
// is cheaper and honest: nothing is spawned, nothing is written to the
|
|
302
|
+
// agent's store.
|
|
303
|
+
if (requested.startsWith('ses_')) {
|
|
304
|
+
throw new Error(`unknown session id: ${requested}\n` +
|
|
305
|
+
` This id is in the bridge's namespace but absent from the session map ` +
|
|
306
|
+
`(~/.opencode-acp-client/sessions.json), so no agent session is known for it.\n` +
|
|
307
|
+
` List the ids this machine knows: python3 scripts/list-sessions.py\n` +
|
|
308
|
+
` Or resume the newest conversation in this directory: -c`);
|
|
309
|
+
}
|
|
310
|
+
return requested;
|
|
311
|
+
}
|
|
312
|
+
export function parseArgs(argv) {
|
|
313
|
+
let port = 0;
|
|
314
|
+
let host = '127.0.0.1';
|
|
315
|
+
/** `--bridge-port` was given: the user wants a server, not the TUI. */
|
|
316
|
+
let portSpecified = false;
|
|
317
|
+
/** `--bridge-host` was given (it is only meaningful with a server). */
|
|
318
|
+
let hostSpecified = false;
|
|
319
|
+
// The bridge's workspace: the FIRST bare positional (opencode's own
|
|
320
|
+
// `opencode [flags] [<directory>]` spelling), defaulting to the cwd.
|
|
321
|
+
let directory;
|
|
322
|
+
// Whether the previous argv word was a forwarded flag that may take its value
|
|
323
|
+
// as the next word — a bare word after it belongs to the flag, not to us.
|
|
324
|
+
let lastWasForwardedFlag = false;
|
|
325
|
+
// The first bare word decides the mode: an opencode subcommand means NATIVE
|
|
326
|
+
// opencode behaviour (no bridge, no TUI, argv as-is); anything else may
|
|
327
|
+
// become the workspace directory. Judged once, on the first bare word.
|
|
328
|
+
let nativeCommand = false;
|
|
329
|
+
/** An opencode-owned word we refuse, with a hint (see OPENCODE_OWNED_WORDS). */
|
|
330
|
+
let refusedWord;
|
|
331
|
+
/**
|
|
332
|
+
* opencode flags this bridge replaces. Recorded, not forwarded: `--server` would point the
|
|
333
|
+
* TUI somewhere other than the bridge (which IS the server), and `--standalone` would have
|
|
334
|
+
* it start a server of its own. Silently dropping them made `--server <url>` fall through
|
|
335
|
+
* to the DIRECTORY rule — measured: `chdir '…' -> 'http://example.com'`.
|
|
336
|
+
*/
|
|
337
|
+
const replacedFlags = [];
|
|
338
|
+
/** opencode CLI tools that are not TUI flags at all (see the parse branch). */
|
|
339
|
+
const cliOnlyFlags = [];
|
|
340
|
+
/** `upgrade --check`: look up the version and stop. */
|
|
341
|
+
let upgradeCheck = false;
|
|
342
|
+
/** A version to install, from `upgrade <version>`. */
|
|
343
|
+
let upgradeTarget;
|
|
344
|
+
let nativeSubcommand;
|
|
345
|
+
let sawFirstBare = false;
|
|
346
|
+
let launch = true;
|
|
347
|
+
let logPath;
|
|
348
|
+
let session;
|
|
349
|
+
let continueSession = false;
|
|
350
|
+
let bridgeCommand;
|
|
351
|
+
let psJson = false;
|
|
352
|
+
let sessionsJson = false;
|
|
353
|
+
/** 0 means "every row"; `--all`. */
|
|
354
|
+
let sessionsLimit = DEFAULT_PAGE;
|
|
355
|
+
let sessionsOffset = 0;
|
|
356
|
+
let sessionsDirectory;
|
|
357
|
+
let sessionsAgent;
|
|
358
|
+
/** Explicit table width; `stdout.columns` is undefined when piped. */
|
|
359
|
+
let sessionsWidth;
|
|
360
|
+
/**
|
|
361
|
+
* Words and flags `sessions` did not recognise. Collected, not ignored: `--director`
|
|
362
|
+
* (a typo) used to be swallowed whole and the command printed every session, which
|
|
363
|
+
* looked exactly like "the filter does not work".
|
|
364
|
+
*/
|
|
365
|
+
const sessionsUnknown = [];
|
|
366
|
+
const unknownUpgrade = [];
|
|
367
|
+
let psPrune = false;
|
|
368
|
+
let psKill = false;
|
|
369
|
+
const passThrough = [];
|
|
370
|
+
let index = 0;
|
|
371
|
+
// The contract with the user (the owner's rule): a flag shared with opencode
|
|
372
|
+
// keeps opencode's name AND meaning wherever the two agree (`--directory`,
|
|
373
|
+
// `--session`, `--continue`); where they disagree, the bridge's flag gets a
|
|
374
|
+
// bridge-qualified name (`--bridge-port` etc. — opencode's `--port` is its
|
|
375
|
+
// own server, ours is the ACP bridge); everything unrecognized is opencode's
|
|
376
|
+
// business and passed to the TUI verbatim, in order.
|
|
377
|
+
for (; index < argv.length; index += 1) {
|
|
378
|
+
const arg = argv[index];
|
|
379
|
+
if (arg === '--') {
|
|
380
|
+
index += 1;
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
// Shared name, shared meaning — but the DIRECTORY is now a positional
|
|
384
|
+
// argument, exactly as opencode spells it (`opencode [flags] [<directory>]`).
|
|
385
|
+
// `--directory`/`-C` therefore are NOT ours either: they forward like every
|
|
386
|
+
// other unrecognized word, and the TUI (opencode) consumes them itself. The
|
|
387
|
+
// bridge's own directory comes from the first bare positional before `--` —
|
|
388
|
+
// but only one that is NOT the value of a forwarded flag: a word right after
|
|
389
|
+
// a `--something` belongs to that flag (opencode flags take their value as
|
|
390
|
+
// the next argument), so claiming it as the directory would corrupt the
|
|
391
|
+
// forwarded argv. The one exception is a value the TUI itself would reject:
|
|
392
|
+
// we do not know which flags take values, so the pair rule is the only
|
|
393
|
+
// honest guess — and a directory that follows a flag the user meant to give
|
|
394
|
+
// a value to is the user's call, exactly as opencode would parse it.
|
|
395
|
+
// ★ Refused, not dropped. Both are opencode's way of choosing a server, and this tool
|
|
396
|
+
// IS the server — silently ignoring them is how a flag the user typed stops mattering.
|
|
397
|
+
// The value is consumed first: without that, `--server <url>` left the URL to be
|
|
398
|
+
// claimed as the workspace directory (measured: `chdir '/repo' -> 'http://example.com'`).
|
|
399
|
+
if (arg === '--server' || arg.startsWith('--server=')) {
|
|
400
|
+
if (arg === '--server')
|
|
401
|
+
index += 1;
|
|
402
|
+
replacedFlags.push('--server');
|
|
403
|
+
lastWasForwardedFlag = false;
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (arg === '--standalone') {
|
|
407
|
+
replacedFlags.push('--standalone');
|
|
408
|
+
lastWasForwardedFlag = false;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
// ★ CLI tools, not TUI flags. `--completions` prints a script for opencode's own
|
|
412
|
+
// argument parser and `--wizard` builds a command for its own CLI; forwarding them to
|
|
413
|
+
// the TUI means nothing, and with no `-- <agent>` they fell through to "print help and
|
|
414
|
+
// exit 0" — which looked like success and did nothing.
|
|
415
|
+
if (arg === '--completions' || arg.startsWith('--completions=') || arg === '--wizard') {
|
|
416
|
+
if (arg === '--completions')
|
|
417
|
+
index += 1;
|
|
418
|
+
cliOnlyFlags.push(arg.split('=')[0]);
|
|
419
|
+
lastWasForwardedFlag = false;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (!arg.startsWith('-') && arg !== '' && !lastWasForwardedFlag) {
|
|
423
|
+
// ★ A bare word after `upgrade` is the VERSION, never a directory. Checked before
|
|
424
|
+
// the directory rule below, which claimed `0.4.0` while the flag-style branch near
|
|
425
|
+
// the end of this loop never saw it — the argument is not a flag.
|
|
426
|
+
if (bridgeCommand === 'upgrade') {
|
|
427
|
+
upgradeTarget = arg;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
// The FIRST bare word chooses the mode. A subcommand is native opencode:
|
|
431
|
+
// NO bridge, NO TUI, and every later word is the subcommand's own
|
|
432
|
+
// argument (`opencode session ls`, `opencode api POST …`) — never a
|
|
433
|
+
// directory claim, which an earlier version let a second bare word
|
|
434
|
+
// corrupt. Everything before `--` forwards untouched.
|
|
435
|
+
if (!sawFirstBare) {
|
|
436
|
+
sawFirstBare = true;
|
|
437
|
+
// A bridge-owned subcommand: `ps` lists the bridges this tool started.
|
|
438
|
+
// opencode has no `ps`, so claiming the word cannot shadow its CLI.
|
|
439
|
+
if (arg === 'ps' || arg === 'daemons') {
|
|
440
|
+
bridgeCommand = 'ps';
|
|
441
|
+
lastWasForwardedFlag = false;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
// `sessions` and `ls` are ours too: opencode has both words (`opencode session`),
|
|
445
|
+
// so `ls` only claims the slot when nothing has been parsed as native — the
|
|
446
|
+
// `OPENCODE_SUBCOMMANDS` check below still wins for the bare `opencode` words.
|
|
447
|
+
if (arg === 'sessions' || (arg === 'ls' && !nativeCommand)) {
|
|
448
|
+
bridgeCommand = 'sessions';
|
|
449
|
+
lastWasForwardedFlag = false;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
// Our own updater. It was a passthrough once, which meant `oc-acp-client upgrade`
|
|
453
|
+
// upgraded opencode — a different product on a different version line.
|
|
454
|
+
if (arg === 'upgrade' || arg === 'update') {
|
|
455
|
+
bridgeCommand = 'upgrade';
|
|
456
|
+
lastWasForwardedFlag = false;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (OPENCODE_OWNED_WORDS.has(arg)) {
|
|
460
|
+
// A deliberate refusal. Forwarding these ran opencode's own command — same word,
|
|
461
|
+
// different product — so the failure a user saw was opencode's answer to a
|
|
462
|
+
// question they had not asked. Passing the binary on still works, explicitly.
|
|
463
|
+
refusedWord = arg;
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (nativeCommand) {
|
|
468
|
+
lastWasForwardedFlag = false;
|
|
469
|
+
passThrough.push(arg);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (directory === undefined) {
|
|
473
|
+
// opencode's own rule: a bare positional before `--` is the directory.
|
|
474
|
+
directory = arg;
|
|
475
|
+
lastWasForwardedFlag = false;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
// A second bare word in bridge mode: opencode's own subcommand-style
|
|
479
|
+
// usage after a directory (`opencode /work models`), so it forwards.
|
|
480
|
+
lastWasForwardedFlag = false;
|
|
481
|
+
passThrough.push(arg);
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
// Track whether THIS word completes the value of a forwarded flag, so the
|
|
485
|
+
// NEXT bare word can be judged as a directory on its own merits.
|
|
486
|
+
lastWasForwardedFlag = arg.startsWith('-') && !arg.startsWith('--bridge');
|
|
487
|
+
if (arg === '--session' || arg === '-s' || arg.startsWith('--session=')) {
|
|
488
|
+
session =
|
|
489
|
+
arg === '--session' || arg === '-s' ? String(argv[++index]) : arg.slice('--session='.length);
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
if (arg === '--continue' || arg === '-c') {
|
|
493
|
+
continueSession = true;
|
|
494
|
+
// opencode's own flag must still reach the TUI: IT is the one that loads
|
|
495
|
+
// the remembered session list into its store.
|
|
496
|
+
passThrough.push(arg);
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
// Bridge-only concerns, named so they cannot be confused with opencode's.
|
|
500
|
+
if (arg === '--bridge-port' || arg.startsWith('--bridge-port=')) {
|
|
501
|
+
port = arg === '--bridge-port' ? Number(argv[++index]) : Number(arg.slice('--bridge-port='.length));
|
|
502
|
+
portSpecified = true;
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
if (arg === '--bridge-host' || arg.startsWith('--bridge-host=')) {
|
|
506
|
+
host = arg === '--bridge-host' ? String(argv[++index]) : arg.slice('--bridge-host='.length);
|
|
507
|
+
hostSpecified = true;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (arg === '--bridge-log' || arg.startsWith('--bridge-log=')) {
|
|
511
|
+
logPath = arg === '--bridge-log' ? String(argv[++index]) : arg.slice('--bridge-log='.length);
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (bridgeCommand === 'upgrade') {
|
|
515
|
+
if (arg === '--check')
|
|
516
|
+
upgradeCheck = true;
|
|
517
|
+
else
|
|
518
|
+
unknownUpgrade.push(arg);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (bridgeCommand === 'sessions') {
|
|
522
|
+
if (arg === '--json')
|
|
523
|
+
sessionsJson = true;
|
|
524
|
+
else if (arg === '--all')
|
|
525
|
+
sessionsLimit = 0;
|
|
526
|
+
else if (arg === '--limit')
|
|
527
|
+
sessionsLimit = Number(argv[++index]) || DEFAULT_PAGE;
|
|
528
|
+
else if (arg.startsWith('--limit='))
|
|
529
|
+
sessionsLimit = Number(arg.slice('--limit='.length)) || DEFAULT_PAGE;
|
|
530
|
+
else if (arg === '--offset')
|
|
531
|
+
sessionsOffset = Math.max(0, Number(argv[++index]) || 0);
|
|
532
|
+
else if (arg.startsWith('--offset='))
|
|
533
|
+
sessionsOffset = Math.max(0, Number(arg.slice('--offset='.length)) || 0);
|
|
534
|
+
else if (arg === '--directory' || arg === '-C')
|
|
535
|
+
sessionsDirectory = String(argv[++index] ?? '');
|
|
536
|
+
else if (arg.startsWith('--directory='))
|
|
537
|
+
sessionsDirectory = arg.slice('--directory='.length);
|
|
538
|
+
else if (arg === '--agent' || arg === '-A')
|
|
539
|
+
sessionsAgent = String(argv[++index] ?? '');
|
|
540
|
+
else if (arg.startsWith('--agent='))
|
|
541
|
+
sessionsAgent = arg.slice('--agent='.length);
|
|
542
|
+
else if (arg === '--width')
|
|
543
|
+
sessionsWidth = Number(argv[++index]) || undefined;
|
|
544
|
+
else if (arg.startsWith('--width='))
|
|
545
|
+
sessionsWidth = Number(arg.slice('--width='.length)) || undefined;
|
|
546
|
+
else if (arg === '--next')
|
|
547
|
+
sessionsOffset = -1;
|
|
548
|
+
else {
|
|
549
|
+
sessionsUnknown.push(arg);
|
|
550
|
+
}
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
if (bridgeCommand === 'ps' && (arg === '--json' || arg === '--prune' || arg === '--kill')) {
|
|
554
|
+
if (arg === '--json')
|
|
555
|
+
psJson = true;
|
|
556
|
+
if (arg === '--prune')
|
|
557
|
+
psPrune = true;
|
|
558
|
+
if (arg === '--kill')
|
|
559
|
+
psKill = true;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (arg === '--no-tui') {
|
|
563
|
+
launch = false;
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (arg === '--help' || arg === '-h') {
|
|
567
|
+
printHelp();
|
|
568
|
+
process.exit(0);
|
|
569
|
+
}
|
|
570
|
+
// ★ `--version`/`-v` are OURS. They used to fall through to the TUI, which printed
|
|
571
|
+
// nothing useful and then failed with "missing agent command" — a tool that cannot
|
|
572
|
+
// state its own version. The number is this package's; the opencode binary it pairs
|
|
573
|
+
// with is a separate question and deliberately not mixed in here.
|
|
574
|
+
if (arg === '--version' || arg === '-v') {
|
|
575
|
+
process.stdout.write(`${PACKAGE_NAME} ${PACKAGE_VERSION}\n`);
|
|
576
|
+
process.exit(0);
|
|
577
|
+
}
|
|
578
|
+
// Anything else is opencode's: TUI flags (`--auto`, `--prompt …`,
|
|
579
|
+
// `--log-level …`), `-c`-style shorts, `--flag=value`, subcommands
|
|
580
|
+
// (`models`, `run`, …), or plain arguments. Forwarded verbatim; a value
|
|
581
|
+
// flag followed by a bare word stays a pair because we never look ahead.
|
|
582
|
+
passThrough.push(arg);
|
|
583
|
+
}
|
|
584
|
+
// ★ Specifying a port means "serve, do not start the TUI" (the other-v2
|
|
585
|
+
// client use case). A host alone is not a server request: it only has meaning
|
|
586
|
+
// with a port (or an explicit --no-tui for the random-port server).
|
|
587
|
+
if (portSpecified)
|
|
588
|
+
launch = false;
|
|
589
|
+
if (hostSpecified && !portSpecified && launch) {
|
|
590
|
+
throw new Error('--bridge-host needs --bridge-port (or --no-tui); pass --bridge-port <n> to serve, ' +
|
|
591
|
+
'or drop --bridge-host to start the TUI');
|
|
592
|
+
}
|
|
593
|
+
const [agentCommand, ...agentArgs] = argv.slice(index);
|
|
594
|
+
if (session && continueSession) {
|
|
595
|
+
throw new Error('use either --session/-s or --continue/-c, not both');
|
|
596
|
+
}
|
|
597
|
+
// One client = one agent: a resumed session (or -c) carries its agent in the map,
|
|
598
|
+
// so an agent command alongside it is either redundant or the old ambiguity —
|
|
599
|
+
// refuse it. `--` is for STARTING a new session only.
|
|
600
|
+
if ((session || continueSession) && agentCommand) {
|
|
601
|
+
throw new Error('do not pass an agent command with -s/-c: the session (or -c\'s newest session) ' +
|
|
602
|
+
'fixes the agent; use -- <agent> only to start a new session');
|
|
603
|
+
}
|
|
604
|
+
// ★ A refused opencode word fails HERE, loudly. It used to be forwarded to the opencode
|
|
605
|
+
// binary instead, which answered a question about a different product — and silently, so
|
|
606
|
+
// `oc-acp-client upgrade` moving opencode looked like it had upgraded this package.
|
|
607
|
+
if (cliOnlyFlags.length > 0) {
|
|
608
|
+
const flag = cliOnlyFlags[0];
|
|
609
|
+
throw new Error(`\`${flag}\` is opencode's own CLI tool, not a flag of the TUI this tool drives. ` +
|
|
610
|
+
`Run \`opencode ${flag}\` directly.`);
|
|
611
|
+
}
|
|
612
|
+
if (replacedFlags.length > 0) {
|
|
613
|
+
// ★ A refusal, not a warning. These two choose a SERVER, and this tool is one — a run
|
|
614
|
+
// that ignored them would look like it honoured them, which is the same mistake
|
|
615
|
+
// `--server`'s value-as-directory made in a louder way.
|
|
616
|
+
const flag = replacedFlags[0];
|
|
617
|
+
throw new Error(`\`${flag}\` is not accepted: this tool IS the server the TUI talks to. ` +
|
|
618
|
+
`Run \`opencode ${flag} …\` directly if you want the TUI pointed somewhere else.`);
|
|
619
|
+
}
|
|
620
|
+
if (refusedWord) {
|
|
621
|
+
throw new Error(`\`${refusedWord}\` is opencode's command, not this tool's. ` +
|
|
622
|
+
`Run \`opencode ${refusedWord}\` for it, or see \`oc-acp-client --help\` for ours ` +
|
|
623
|
+
`(sessions, ps, upgrade, update).`);
|
|
624
|
+
}
|
|
625
|
+
// A native subcommand IS opencode: no agent, no bridge, no `--`. The only
|
|
626
|
+
// syntactic difference from the bridge usage, so the check must not demand
|
|
627
|
+
// what that mode never has.
|
|
628
|
+
if (!agentCommand && !nativeCommand && !bridgeCommand && !session && !continueSession) {
|
|
629
|
+
printHelp();
|
|
630
|
+
throw new Error('missing agent command (put it after --)');
|
|
631
|
+
}
|
|
632
|
+
return {
|
|
633
|
+
port,
|
|
634
|
+
host,
|
|
635
|
+
directory: directory ?? process.cwd(),
|
|
636
|
+
nativeCommand,
|
|
637
|
+
nativeSubcommand,
|
|
638
|
+
bridgeCommand,
|
|
639
|
+
psJson,
|
|
640
|
+
sessionsJson,
|
|
641
|
+
sessionsLimit,
|
|
642
|
+
sessionsOffset,
|
|
643
|
+
...(sessionsDirectory ? { sessionsDirectory } : {}),
|
|
644
|
+
...(sessionsAgent ? { sessionsAgent } : {}),
|
|
645
|
+
sessionsUnknown,
|
|
646
|
+
...(refusedWord ? { refusedWord } : {}),
|
|
647
|
+
replacedFlags,
|
|
648
|
+
cliOnlyFlags,
|
|
649
|
+
upgradeCheck,
|
|
650
|
+
...(upgradeTarget ? { upgradeTarget } : {}),
|
|
651
|
+
unknownUpgrade,
|
|
652
|
+
...(sessionsWidth ? { sessionsWidth } : {}),
|
|
653
|
+
psPrune,
|
|
654
|
+
psKill,
|
|
655
|
+
agentCommand,
|
|
656
|
+
agentArgs,
|
|
657
|
+
launch,
|
|
658
|
+
logPath,
|
|
659
|
+
passThrough,
|
|
660
|
+
session,
|
|
661
|
+
continueSession,
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
const PAINT_PLAIN = { heading: (t) => t, flag: (t) => t };
|
|
665
|
+
const PAINT_TTY = {
|
|
666
|
+
// Bold cyan headings, yellow names; legible on light and dark terminals alike.
|
|
667
|
+
heading: (text) => `\u001b[1;36m${text}\u001b[0m`,
|
|
668
|
+
flag: (text) => `\u001b[33m${text}\u001b[0m`,
|
|
669
|
+
};
|
|
670
|
+
function helpPaint() {
|
|
671
|
+
if (process.env['NO_COLOR'] !== undefined)
|
|
672
|
+
return PAINT_PLAIN;
|
|
673
|
+
if (process.env['TERM'] === 'dumb')
|
|
674
|
+
return PAINT_PLAIN;
|
|
675
|
+
return process.stdout.isTTY ? PAINT_TTY : PAINT_PLAIN;
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* One row: a name column and a description, indented two spaces like opencode's. Padding
|
|
679
|
+
* is computed on the PLAIN name, so the columns line up whatever the escapes do.
|
|
680
|
+
*/
|
|
681
|
+
function helpRow(paint, name, description, width) {
|
|
682
|
+
return ` ${paint.flag(name.padEnd(width))} ${description}`;
|
|
683
|
+
}
|
|
684
|
+
/** A whole section's rows, aligned on the longest name; a null name is a continuation. */
|
|
685
|
+
function helpRows(paint, rows) {
|
|
686
|
+
const width = Math.max(...rows.map(([name]) => (name ?? '').length));
|
|
687
|
+
return rows.map(([name, description]) => name === null ? ` ${' '.repeat(width)} ${description}` : helpRow(paint, name, description, width));
|
|
688
|
+
}
|
|
689
|
+
/** The ENVIRONMENT rows: a name and what it does. */
|
|
690
|
+
function environmentRows() {
|
|
691
|
+
return [
|
|
692
|
+
[ENV_BIN, 'The opencode v2 client binary (default: opencode on PATH)'],
|
|
693
|
+
['OPENCODE_ACP_CLIENT_TRACE', 'Log every HTTP request and ACP frame'],
|
|
694
|
+
['OPENCODE_ACP_CLIENT_EVENT_LOG=1', 'Log the session each emitted event names'],
|
|
695
|
+
['OPENCODE_ACP_CLIENT_PROMPT_TIMEOUT_MS', 'Give session/prompt a clock (default: none)'],
|
|
696
|
+
['OPENCODE_ACP_CLIENT_SESSION_MAP', 'Session-id map path'],
|
|
697
|
+
['OPENCODE_ACP_CLIENT_DUMP', "Write session/new's raw response here"],
|
|
698
|
+
];
|
|
699
|
+
}
|
|
700
|
+
export function printHelp() {
|
|
701
|
+
// The forwarded half, quoted from the binary so a new opencode flag appears here without
|
|
702
|
+
// a second copy to maintain. Every flag the bridge intercepts is removed first: whatever
|
|
703
|
+
// survives is genuinely passed through.
|
|
704
|
+
let forwarded = [];
|
|
705
|
+
try {
|
|
706
|
+
const binary = resolveOpenCodeBinary();
|
|
707
|
+
const raw = execFileSync(binary.path, ['--help'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
708
|
+
const cut = raw.search(/^SUBCOMMANDS\s*$/m);
|
|
709
|
+
const body = cut >= 0 ? raw.slice(0, cut) : raw;
|
|
710
|
+
const firstHeading = body.search(/^(FLAGS|GLOBAL FLAGS)\s*$/m);
|
|
711
|
+
// ★ Parsed into (flag, description) PAIRS, not kept as pre-indented text. opencode pads
|
|
712
|
+
// its own two sections to different widths, so pasting them verbatim left the columns
|
|
713
|
+
// ragged next to ours. As pairs they go through the same `helpRows` alignment we use,
|
|
714
|
+
// and the result reads as one table.
|
|
715
|
+
const lines = (firstHeading >= 0 ? body.slice(firstHeading) : body).split('\n');
|
|
716
|
+
const rows = [];
|
|
717
|
+
for (const line of lines) {
|
|
718
|
+
if (/^(FLAGS|GLOBAL FLAGS)\s*$/.test(line))
|
|
719
|
+
continue;
|
|
720
|
+
if (!/^\s+--/.test(line))
|
|
721
|
+
continue;
|
|
722
|
+
// ` --flag <arg> Description` — the flag column ends where three or more spaces
|
|
723
|
+
// begin (opencode pads with at least two, the description never starts with space).
|
|
724
|
+
// opencode spells the argument as a bare word (`--server string`, `--prompt string`)
|
|
725
|
+
// or in angle brackets (`--completions <bash|…>`); either way the name is everything
|
|
726
|
+
// up to the two-space gap that starts the description.
|
|
727
|
+
const match = /^\s+(--\S+(?:\s+(?:string|<[^>]*>))?)\s{2,}(.+)$/.exec(line);
|
|
728
|
+
const name = match?.[1];
|
|
729
|
+
const description = match?.[2];
|
|
730
|
+
if (!name || !description)
|
|
731
|
+
continue;
|
|
732
|
+
// A flag this tool takes over never reaches the TUI, so it does not belong in the list.
|
|
733
|
+
if (/^--(server|standalone|session|continue|help|version|wizard|completions)\b/.test(name))
|
|
734
|
+
continue;
|
|
735
|
+
rows.push([name, description]);
|
|
736
|
+
}
|
|
737
|
+
forwarded = rows;
|
|
738
|
+
}
|
|
739
|
+
catch {
|
|
740
|
+
forwarded = [['', `(opencode's flags are unavailable: no ${ENV_BIN ? `$${ENV_BIN}` : 'opencode'} on PATH)`]];
|
|
741
|
+
}
|
|
742
|
+
const paint = helpPaint();
|
|
743
|
+
const H = (text) => paint.heading(text);
|
|
744
|
+
process.stdout.write([
|
|
745
|
+
H('DESCRIPTION'),
|
|
746
|
+
' The opencode v2 TUI, driving any ACP agent. The bridge replaces the opencode',
|
|
747
|
+
' server: the TUI talks to it, and it talks ACP to the agent given after `--`.',
|
|
748
|
+
'',
|
|
749
|
+
H('USAGE'),
|
|
750
|
+
' oc-acp-client [flags] [<directory>] -- <agent command> [args…]',
|
|
751
|
+
' oc-acp-client -s <session> | -c [flags]',
|
|
752
|
+
' oc-acp-client sessions | ps | upgrade | --help | --version',
|
|
753
|
+
'',
|
|
754
|
+
H('FLAGS'),
|
|
755
|
+
...helpRows(paint, [
|
|
756
|
+
['--help, -h', 'Show this help'],
|
|
757
|
+
['-- <cmd> [args…]', 'The ACP agent to spawn. One client drives one agent; -s/-c read the agent from the session map instead'],
|
|
758
|
+
['--continue, -c', 'Continue the most recent session this tool advanced'],
|
|
759
|
+
['--session, -s <id>', "Continue this session; the `ses_…` id is translated to the agent's own"],
|
|
760
|
+
// ★ Each line says what the flag is FOR, not just what it switches off:
|
|
761
|
+
// `--no-tui` is how a script gets a ready line, and `--bridge-port` is how something
|
|
762
|
+
// else gets a stable address. "implies --no-tui" alone made the first look like a way
|
|
763
|
+
// to pin a port.
|
|
764
|
+
//
|
|
765
|
+
// ★ No client is named here on purpose. Attaching a client to this bridge DOES work at
|
|
766
|
+
// the protocol level, but the TUI state roots (`XDG_STATE_HOME`, `OPENCODE_DB`, …) are
|
|
767
|
+
// injected into the child we spawn, and no other client can be given them — so its
|
|
768
|
+
// tabs are not isolated per agent while ours are. Until that is solved, pointing
|
|
769
|
+
// users at it would be advertising a trap.
|
|
770
|
+
['--bridge-port <n>', 'Pin the port instead of choosing a free one; no TUI'],
|
|
771
|
+
['--bridge-host <a>', 'Listen address (default 127.0.0.1; 0.0.0.0 accepts other machines, and the bridge has no auth)'],
|
|
772
|
+
['--bridge-log <p>', 'Bridge log path (default: stderr, or a file under TMPDIR once the TUI starts)'],
|
|
773
|
+
['--no-tui', 'Serve HTTP/SSE only; prints a ready line carrying the chosen port, for a script to read'],
|
|
774
|
+
['--version, -v', "Show this package's version"],
|
|
775
|
+
]),
|
|
776
|
+
'',
|
|
777
|
+
" The flags below are opencode's and reach the TUI unchanged.",
|
|
778
|
+
...helpRows(paint, forwarded),
|
|
779
|
+
'',
|
|
780
|
+
'',
|
|
781
|
+
H('SUBCOMMANDS'),
|
|
782
|
+
...helpRows(paint, [
|
|
783
|
+
// The two read DIFFERENT stores and answer different questions: `sessions` is the
|
|
784
|
+
// history (finished conversations included), `ps` is the live process table. One
|
|
785
|
+
// line each that says which, because "the processes this tool started" could be
|
|
786
|
+
// read as "the sessions it started".
|
|
787
|
+
['sessions', 'History: conversations this tool remembers, newest first'],
|
|
788
|
+
['ps', 'Now: bridge processes running right now (pid, port, age)'],
|
|
789
|
+
['upgrade, update', 'Move this package to a newer version'],
|
|
790
|
+
]),
|
|
791
|
+
'',
|
|
792
|
+
H('ENVIRONMENT'),
|
|
793
|
+
...helpRows(paint, environmentRows()),
|
|
794
|
+
'',
|
|
795
|
+
'The ready line (one JSON object on stdout) is printed when stdout is not a',
|
|
796
|
+
'terminal — scripts read the port from it — and always with --no-tui.',
|
|
797
|
+
'',
|
|
798
|
+
].join('\n'));
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Is the agent command runnable?
|
|
802
|
+
*
|
|
803
|
+
* The agent is spawned lazily — on the first prompt — so without this check a
|
|
804
|
+
* typo would be discovered only after the TUI had taken over the terminal, and
|
|
805
|
+
* it would look like a dead composer rather than a bad command. Checking first
|
|
806
|
+
* turns that into one readable line before anything starts.
|
|
807
|
+
*
|
|
808
|
+
* Deliberately does **not run** the command: an arbitrary ACP agent may not
|
|
809
|
+
* support any probe flag, and one that ignores argv simply waits on stdin
|
|
810
|
+
* (which is the trap that made `--dump-config` discovery unworkable).
|
|
811
|
+
*/
|
|
812
|
+
export function findExecutable(command, env = process.env, cwd = process.cwd()) {
|
|
813
|
+
const executable = (path) => {
|
|
814
|
+
try {
|
|
815
|
+
accessSync(path, constants.X_OK);
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
// A path (relative or absolute) is checked as given, never searched for.
|
|
823
|
+
// A *relative* one is resolved against the directory the agent will run in,
|
|
824
|
+
// not against wherever we happened to be started — the agent is spawned with
|
|
825
|
+
// the workspace directory as its cwd, so `tests/agent.mjs` means that file
|
|
826
|
+
// inside the workspace.
|
|
827
|
+
if (command.includes('/')) {
|
|
828
|
+
const target = isAbsolute(command) ? command : resolve(cwd, command);
|
|
829
|
+
return executable(target) ? target : undefined;
|
|
830
|
+
}
|
|
831
|
+
for (const dir of (env.PATH ?? '').split(delimiter)) {
|
|
832
|
+
if (!dir)
|
|
833
|
+
continue;
|
|
834
|
+
const candidate = join(dir, command);
|
|
835
|
+
if (executable(candidate))
|
|
836
|
+
return candidate;
|
|
837
|
+
}
|
|
838
|
+
return undefined;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Decide what to do about the client, then optionally start it.
|
|
842
|
+
*
|
|
843
|
+
* Returns the child to wait on, or undefined when we should just serve.
|
|
844
|
+
* Exits the process when the answer is "you need a v2 client and we cannot get
|
|
845
|
+
* one" — never silently, and never by installing anything unattended.
|
|
846
|
+
*/
|
|
847
|
+
async function handleClient(args, url, resolvedSession, epilogueTarget, log, onFatal) {
|
|
848
|
+
const binary = resolveOpenCodeBinary();
|
|
849
|
+
let version = await readOpenCodeVersion(binary);
|
|
850
|
+
log(`[bridge] ${describeVersion(binary, version)}`);
|
|
851
|
+
if (version?.supported) {
|
|
852
|
+
if (!args.launch)
|
|
853
|
+
return undefined;
|
|
854
|
+
return launchClient(args, binary, url, resolvedSession, epilogueTarget, log, onFatal);
|
|
855
|
+
}
|
|
856
|
+
// At this point the client is missing or too old.
|
|
857
|
+
const reason = version ? `found v${version.major}, need v${MIN_MAJOR_VERSION}+` : 'not found';
|
|
858
|
+
// A readable way out. The URL must be the **v2** installer: the unversioned
|
|
859
|
+
// one serves v1, which this gate would reject again a minute later.
|
|
860
|
+
const install = version
|
|
861
|
+
? `upgrade it: ${upgradeHint(binary)} — or install opencode v2: ${installHint()}`
|
|
862
|
+
: `install opencode v2: ${installHint()}`;
|
|
863
|
+
if (!args.launch) {
|
|
864
|
+
// Server-only: no TUI is launched here, so this is advice, not a failure.
|
|
865
|
+
log(`[bridge] warning: opencode v2 ${reason} (${binary.path}); continuing as a server`);
|
|
866
|
+
log(`[bridge] ${install}`);
|
|
867
|
+
return undefined;
|
|
868
|
+
}
|
|
869
|
+
log(`[bridge] opencode v2 ${reason} (${binary.path})`);
|
|
870
|
+
log(`[bridge] ${install}`);
|
|
871
|
+
// No TUI exists yet (it is started at the end of this function), so the
|
|
872
|
+
// terminal is free — and a missing client is exactly the case where the user
|
|
873
|
+
// needs to read this line, not go hunting for the log file.
|
|
874
|
+
process.stderr.write(`[bridge] ${install}\n`);
|
|
875
|
+
// Nothing to upgrade when there is no binary at all.
|
|
876
|
+
if (!version)
|
|
877
|
+
process.exit(1);
|
|
878
|
+
if (!process.stdin.isTTY) {
|
|
879
|
+
// Never install unattended: there may be no human, and no consent.
|
|
880
|
+
log('[bridge] refusing to install unattended (stdin is not a terminal)');
|
|
881
|
+
process.exit(1);
|
|
882
|
+
}
|
|
883
|
+
const agreed = await confirm(`Upgrade the opencode v2 client now? (${upgradeHint(binary)}) [y/N] `);
|
|
884
|
+
if (!agreed) {
|
|
885
|
+
log(`[bridge] aborted; run: ${upgradeHint(binary)}`);
|
|
886
|
+
process.exit(1);
|
|
887
|
+
}
|
|
888
|
+
const code = await runToCompletion(binary.path, ['upgrade'], log);
|
|
889
|
+
if (code !== 0) {
|
|
890
|
+
log(`[bridge] upgrade exited with ${code}`);
|
|
891
|
+
process.exit(1);
|
|
892
|
+
}
|
|
893
|
+
version = await readOpenCodeVersion(binary);
|
|
894
|
+
log(`[bridge] after upgrade: ${describeVersion(binary, version)}`);
|
|
895
|
+
if (!version?.supported) {
|
|
896
|
+
log('[bridge] still not v' + MIN_MAJOR_VERSION + '+ after upgrading; giving up');
|
|
897
|
+
process.exit(1);
|
|
898
|
+
}
|
|
899
|
+
return launchClient(args, binary, url, resolvedSession, epilogueTarget, log, onFatal);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Arguments for the launched client.
|
|
903
|
+
*
|
|
904
|
+
* Pure and exported so the `--session` can be asserted: leaving it out looks
|
|
905
|
+
* fine — the TUI still renders — but the composer then sits on
|
|
906
|
+
* `session/undefined` and Enter does nothing at all.
|
|
907
|
+
*/
|
|
908
|
+
export function clientArgs(args, url, session) {
|
|
909
|
+
// `--server` connects to the bridge; `--standalone` would instead ask the
|
|
910
|
+
// client to run its own private server, so the two must not be combined.
|
|
911
|
+
//
|
|
912
|
+
// `--session`/`--continue` reach the TUI through passThrough when the user
|
|
913
|
+
// passed them — opencode's own flags, opencode's own meaning. The explicit
|
|
914
|
+
// `session` argument is the bridge-side resume (same spelling, resolved by
|
|
915
|
+
// the caller) and wins over a stray forwarded one.
|
|
916
|
+
// ★ Say it out loud. These two are NOT forwarded (the bridge is the server, and a private
|
|
917
|
+
// one would compete with it), and dropping them in silence is how `--server <url>` used to
|
|
918
|
+
// become the workspace directory instead of an error.
|
|
919
|
+
const forwarded = args.passThrough.filter((a) => a !== '--server' && a !== '--standalone');
|
|
920
|
+
const argv = ['--server', url, ...(session ? ['--session', session] : []), ...forwarded];
|
|
921
|
+
// The TUI needs a directory to key its workspace state on. The user may have
|
|
922
|
+
// named one themselves — a bare positional, or opencode's own --directory/-C,
|
|
923
|
+
// both of which arrived via passThrough — and then the TUI takes it; the
|
|
924
|
+
// bridge's own copy (which is what `--` uses as its default when nothing was
|
|
925
|
+
// named) is appended only when the forwarded argv names no directory at all.
|
|
926
|
+
const namesDirectory = forwarded.some((a, i) => a === '--directory' || a === '-C' || a?.startsWith('--directory=') || a === '--')
|
|
927
|
+
? true
|
|
928
|
+
: forwarded.some((a) => a !== undefined && !a.startsWith('-'));
|
|
929
|
+
if (!namesDirectory)
|
|
930
|
+
argv.push(args.directory);
|
|
931
|
+
return argv;
|
|
932
|
+
}
|
|
933
|
+
function launchClient(args, binary, url, resolvedSession, epilogueTarget, log, onFatal) {
|
|
934
|
+
// ★ The TUI gets the id the USER TYPED (`ses_…`), never the translated agent
|
|
935
|
+
// id: the epilogue prints the TUI's session id, and handing it the UUID meant
|
|
936
|
+
// the `Continue` line showed the agent's internal id — which the user should
|
|
937
|
+
// not see, and which --session would refuse on the next run (it is not in the
|
|
938
|
+
// map's keys). The bridge adopted the session from the map either way.
|
|
939
|
+
const argv = clientArgs(args, url, args.session);
|
|
940
|
+
log(`[bridge] launching: ${binary.path} ${argv.join(' ')}`);
|
|
941
|
+
// ★ stdin stays a SOCKET inherited from us (a TTY): a `pipe` here strips the
|
|
942
|
+
// TTY-ness the TUI probes for size and mouse support, and it rendered a small
|
|
943
|
+
// window glued to the top-left corner of the terminal. The epilogue rewrite
|
|
944
|
+
// therefore does NOT tap the live stream — it reads the TUI's *scrollback*
|
|
945
|
+
// after exit (the frame is history by then) and rewrites only the final
|
|
946
|
+
// `Continue` line, so the interactive path is untouched end to end.
|
|
947
|
+
// ★ Session isolation from a native opencode install. The v2 TUI persists its tab
|
|
948
|
+
// layout (and its own session db) under the XDG state/data roots; sharing them with
|
|
949
|
+
// the native install meant a native TUI showed OUR tabs — and clicking one failed,
|
|
950
|
+
// because those sessions live behind this bridge, not in opencode's own daemon or
|
|
951
|
+
// db. Measured: ~/.local/state/opencode/latest/tui/tabs.json held both worlds.
|
|
952
|
+
// Giving our TUI its own XDG roots keeps both worlds apart: our tabs stay ours,
|
|
953
|
+
// the native install's tabs stay its own.
|
|
954
|
+
const isolated = isolatedTuiRoots({
|
|
955
|
+
command: args.agentCommand ?? binary.path,
|
|
956
|
+
args: args.agentArgs,
|
|
957
|
+
});
|
|
958
|
+
const child = spawn(binary.path, argv, {
|
|
959
|
+
stdio: 'inherit',
|
|
960
|
+
...(isolated ? { env: { ...process.env, ...isolated } } : {}),
|
|
961
|
+
});
|
|
962
|
+
// Attached here rather than at the call site: `spawn` reports a failure on a
|
|
963
|
+
// later tick, and a caller that attached afterwards could miss it and sit
|
|
964
|
+
// serving a TUI that never appeared.
|
|
965
|
+
child.on('error', (err) => onFatal(`failed to launch the opencode v2 TUI: ${err.message}`));
|
|
966
|
+
// The epilogue rewrite is NOT attached here: it must run after the child's
|
|
967
|
+
// stdio has closed ('close', not 'exit'), and the caller owns that event.
|
|
968
|
+
return child;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* The environment our TUI runs under, so a native `opencode` install and this
|
|
972
|
+
* product never share state — and the TUI cannot disturb the native install.
|
|
973
|
+
*
|
|
974
|
+
* The seams, each measured against the shipped binary (`opencode debug paths`,
|
|
975
|
+
* v2.0.31) rather than assumed:
|
|
976
|
+
* XDG_STATE_HOME → `…/tui/tabs.json` (TAB LAYOUT) and locks. Shared, a
|
|
977
|
+
* native TUI listed our tabs and could not open them
|
|
978
|
+
* (their sessions exist only behind the bridge).
|
|
979
|
+
* XDG_DATA_HOME → `opencode.db`, log, snapshot, shell, repos. Shared,
|
|
980
|
+
* the two worlds' session dbs interleave.
|
|
981
|
+
* XDG_CONFIG_HOME → deliberately NOT redirected: TUI config (tui.json,
|
|
982
|
+
* plugins, themes) is shared with the user's install.
|
|
983
|
+
* OPENCODE_DB → the db file outright: a second belt even if an
|
|
984
|
+
* XDG root is ignored. (Measured: honoured.)
|
|
985
|
+
* OPENCODE_DISABLE_AUTOUPDATE → our TUI must not upgrade itself mid-run; a
|
|
986
|
+
* silent version bump is what produced the "Server at
|
|
987
|
+
* … has version X; this client is Y" warnings.
|
|
988
|
+
* OPENCODE_DISABLE_FILEWATCHER → two TUIs watching one worktree duplicate file
|
|
989
|
+
* events; ours need not watch at all.
|
|
990
|
+
* OPENCODE_CONFIG_DIR → ONLY when OPENCODE_ACP_CLIENT_ISOLATED_CONFIG=1: a
|
|
991
|
+
* private config root. Off by default on purpose —
|
|
992
|
+
* it would also hide the user's own providers/plugins
|
|
993
|
+
* from OUR TUI, which is not what "isolation" should
|
|
994
|
+
* cost. Measured nuance: `OPENCODE_CONFIG_DIR` adds a
|
|
995
|
+
* config root but does not stop the user-level one
|
|
996
|
+
* from loading, so this is a containment, not a wall.
|
|
997
|
+
* ★ The root is named after the agent command (see `agentStateSlug`): two agents
|
|
998
|
+
* never share a tabs.json, so a dsh launch cannot restore an opencode tab (reported
|
|
999
|
+
* 2026-10-19 — the mixed tabs also mixed model catalogs). One client = one agent;
|
|
1000
|
+
* another agent is another launch, with its own tab set.
|
|
1001
|
+
*
|
|
1002
|
+
* `OPENCODE_ACP_CLIENT_SHARED_STATE=1` restores the old shared behaviour for anyone
|
|
1003
|
+
* who wants one opencode world.
|
|
1004
|
+
*
|
|
1005
|
+
* Not used, each checked: `OPENCODE_TUI_CHANNEL` (the channel is a BUILD constant;
|
|
1006
|
+
* setting it changed no path), `OPENCODE_TEST_HOME` (moves only `home`, not data or
|
|
1007
|
+
* state), `OPENCODE_CONFIG`/`OPENCODE_CONFIG_CONTENT` (append/override, not a root).
|
|
1008
|
+
*/
|
|
1009
|
+
export function agentStateSlug(command, args = []) {
|
|
1010
|
+
const hash = createHash('sha256').update(JSON.stringify([command, ...args])).digest('hex').slice(0, 8);
|
|
1011
|
+
// `node /path/agent.mjs …` should read as the script, not as a path: the root
|
|
1012
|
+
// directory is user-visible and a full path would be truncated to noise.
|
|
1013
|
+
const runner = basename(command);
|
|
1014
|
+
const script = ['node', 'bun', 'deno', 'python', 'python3', 'npx'].includes(runner) && args[0]
|
|
1015
|
+
? basename(args[0]).replace(/\.[^.]+$/, '')
|
|
1016
|
+
: undefined;
|
|
1017
|
+
const words = `${script ?? runner}-${(script ? args.slice(1) : args).join('-')}`
|
|
1018
|
+
.replace(/[^a-zA-Z0-9._-]+/g, '-')
|
|
1019
|
+
.replace(/-+/g, '-')
|
|
1020
|
+
.replace(/^-|-$/g, '')
|
|
1021
|
+
.slice(0, 40);
|
|
1022
|
+
return `${words || 'agent'}-${hash}`;
|
|
1023
|
+
}
|
|
1024
|
+
export function isolatedTuiRoots(binding) {
|
|
1025
|
+
if (process.env['OPENCODE_ACP_CLIENT_SHARED_STATE'] === '1')
|
|
1026
|
+
return undefined;
|
|
1027
|
+
// ★ One client = one agent: the TUI's tab layout (tabs.json), db and locks live
|
|
1028
|
+
// under a root named after the agent command. Sharing one root let a dsh launch
|
|
1029
|
+
// restore an opencode tab, and the model picker then answered with the wrong
|
|
1030
|
+
// agent's catalog (reported 2026-10-19). Separate roots make that impossible:
|
|
1031
|
+
// each agent's TUI only ever sees the tabs it created.
|
|
1032
|
+
const base = join(homedir(), '.opencode-acp-client', 'opencode');
|
|
1033
|
+
const root = binding ? join(base, agentStateSlug(binding.command, binding.args)) : base;
|
|
1034
|
+
const env = {
|
|
1035
|
+
XDG_STATE_HOME: join(root, 'state'),
|
|
1036
|
+
XDG_DATA_HOME: join(root, 'data'),
|
|
1037
|
+
// ★ Config is SHARED with the user's install (the same tui.json, plugins and
|
|
1038
|
+
// themes a native opencode uses): redirecting XDG_CONFIG_HOME made every
|
|
1039
|
+
// per-agent root carry its own copy, so changing one setting meant editing N
|
|
1040
|
+
// files. State/data stay per agent; the optional isolated config root below
|
|
1041
|
+
// is the only containment. No symlinks: not redirecting is the one-source-of-
|
|
1042
|
+
// truth version of "link them all to ~/.config/opencode/tui.json".
|
|
1043
|
+
OPENCODE_DB: join(root, 'data', 'opencode.db'),
|
|
1044
|
+
OPENCODE_DISABLE_AUTOUPDATE: '1',
|
|
1045
|
+
OPENCODE_DISABLE_FILEWATCHER: '1',
|
|
1046
|
+
};
|
|
1047
|
+
if (process.env['OPENCODE_ACP_CLIENT_ISOLATED_CONFIG'] === '1') {
|
|
1048
|
+
env['OPENCODE_CONFIG_DIR'] = join(root, 'config-root');
|
|
1049
|
+
}
|
|
1050
|
+
return env;
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* The command the user ran, rebuilt for the TUI's exit epilogue.
|
|
1054
|
+
*
|
|
1055
|
+
* The owner's rule: the `Continue` line must read like the invocation that
|
|
1056
|
+
* started THIS process — `oc-acp-client …` when installed as the bin,
|
|
1057
|
+
* `node dist/index.js …` when run from a checkout (the actual entry file, not
|
|
1058
|
+
* some invented wrapper). process.argv carries resolved paths; the shapes are:
|
|
1059
|
+
* - bin: argv[1] = <prefix>/bin/oc-acp-client → basename
|
|
1060
|
+
* - node: argv[1] = <...>/dist/index.js → `node <path>`
|
|
1061
|
+
* (relative to cwd when the entry sits under it — how a checkout
|
|
1062
|
+
* is normally launched — absolute otherwise)
|
|
1063
|
+
* The remaining words are the user's own argv, verbatim.
|
|
1064
|
+
*/
|
|
1065
|
+
export function invocationCommand() {
|
|
1066
|
+
const entry = process.argv[1] ?? 'oc-acp-client';
|
|
1067
|
+
if (/\.m?js$/.test(entry)) {
|
|
1068
|
+
const cwd = process.cwd();
|
|
1069
|
+
const rel = entry.startsWith(cwd + '/') ? entry.slice(cwd.length + 1) : entry;
|
|
1070
|
+
return `node ${rel}`;
|
|
1071
|
+
}
|
|
1072
|
+
return basename(entry);
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* The user's typed command with the resume id in place: an existing
|
|
1076
|
+
* `--session <id>` / `-s <id>` value is REPLACED (never appended — appending
|
|
1077
|
+
* produced `… --session ses_x … --session ses_y`, the owner's report), and a
|
|
1078
|
+
* `-c`/`--continue` becomes `--session <id>` too, because "continue" would
|
|
1079
|
+
* reopen whatever is newest at copy-time, not necessarily THIS conversation.
|
|
1080
|
+
* The id is the VISIBLE one (`ses_…`): the bridge translates it on the next
|
|
1081
|
+
* run. The TUI's own epilogue id cannot be used — on a resumed session it is
|
|
1082
|
+
* the AGENT's id (the bridge hands the TUI the translated UUID), which the
|
|
1083
|
+
* user should not have to see or copy.
|
|
1084
|
+
*/
|
|
1085
|
+
export function resumeCommand(sessionId) {
|
|
1086
|
+
// Bridge plumbing flags are dropped from the rebuilt line: they are
|
|
1087
|
+
// environment details (a --bridge-log carries an absolute temp path that
|
|
1088
|
+
// alone can push the line past the terminal's width), and a hand-typed
|
|
1089
|
+
// resume never includes them.
|
|
1090
|
+
const BRIDGE_FLAGS = new Set([
|
|
1091
|
+
'--bridge-port',
|
|
1092
|
+
'--bridge-host',
|
|
1093
|
+
'--bridge-log',
|
|
1094
|
+
'--no-tui',
|
|
1095
|
+
]);
|
|
1096
|
+
const typed = process.argv.slice(2).filter((word, i, all) => !BRIDGE_FLAGS.has(word) &&
|
|
1097
|
+
!(i > 0 && BRIDGE_FLAGS.has(all[i - 1] ?? '')) &&
|
|
1098
|
+
!/^--bridge-(port|host|log)=/.test(word));
|
|
1099
|
+
// One client = one agent: the resume line does NOT carry `-- <agent>` — `-s`
|
|
1100
|
+
// infers the agent from the session map. Drop the separator and everything after
|
|
1101
|
+
// it; the remaining words are our own flags and opencode pass-throughs.
|
|
1102
|
+
const dash = typed.indexOf('--');
|
|
1103
|
+
const words = [invocationCommand(), ...(dash === -1 ? typed : typed.slice(0, dash))];
|
|
1104
|
+
const out = [];
|
|
1105
|
+
let resumed = false;
|
|
1106
|
+
// `-s`, not `--session`: the owner's ask — the Continue line reads like a
|
|
1107
|
+
// hand-typed command, and the short spelling is what one actually types.
|
|
1108
|
+
const RESUME_FLAG = '-s';
|
|
1109
|
+
for (let i = 0; i < words.length; i += 1) {
|
|
1110
|
+
const word = words[i];
|
|
1111
|
+
if (word === '--session' || word === '-s') {
|
|
1112
|
+
out.push(RESUME_FLAG, sessionId);
|
|
1113
|
+
resumed = true;
|
|
1114
|
+
i += 1; // drop the old id
|
|
1115
|
+
continue;
|
|
1116
|
+
}
|
|
1117
|
+
const eq = /^--session=(.*)$/.exec(word);
|
|
1118
|
+
if (eq) {
|
|
1119
|
+
out.push(RESUME_FLAG, sessionId);
|
|
1120
|
+
resumed = true;
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
if (word === '-c' || word === '--continue') {
|
|
1124
|
+
out.push(RESUME_FLAG, sessionId);
|
|
1125
|
+
resumed = true;
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
if (word === '--' && !resumed) {
|
|
1129
|
+
// No resume flag in the invocation (the common case: the user started a
|
|
1130
|
+
// fresh conversation). Insert one before the agent separator so the
|
|
1131
|
+
// copied line reopens THIS session instead of a blank new one.
|
|
1132
|
+
out.push(RESUME_FLAG, sessionId, '--');
|
|
1133
|
+
resumed = true;
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
out.push(word);
|
|
1137
|
+
}
|
|
1138
|
+
// No `--` at all (a native-style argv) — append at the end.
|
|
1139
|
+
if (!resumed)
|
|
1140
|
+
out.push(RESUME_FLAG, sessionId);
|
|
1141
|
+
return out.join(' ');
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* The exit wordmark that replaces opencode's own.
|
|
1145
|
+
*
|
|
1146
|
+
* The TUI prints its epilogue as `wordmark(4 rows) + blank + Session + Continue
|
|
1147
|
+
* + blank`, so the four rows above the trailing blank are its logo. We are not
|
|
1148
|
+
* allowed to change opencode's binary, but we CAN overwrite those rows on the
|
|
1149
|
+
* way out — the same technique the `Continue` rewrite already uses, just eight
|
|
1150
|
+
* rows up instead of two. The result is that the screen the user comes back to
|
|
1151
|
+
* names THIS product.
|
|
1152
|
+
*
|
|
1153
|
+
* Width budget: 8 + 10 glyphs at 3 columns each joined by one space is 73
|
|
1154
|
+
* columns with the two-space indent; anything narrower gets a single styled
|
|
1155
|
+
* line (the four logo rows are cleared either way).
|
|
1156
|
+
*/
|
|
1157
|
+
/**
|
|
1158
|
+
* The exit wordmark: the TUI's own "opencode" rows, VERBATIM, plus our product
|
|
1159
|
+
* name in the same alphabet.
|
|
1160
|
+
*
|
|
1161
|
+
* Copying the glyph grammar but redrawing the letters was not enough — the owner
|
|
1162
|
+
* could not recognize `opencode` any more ("at least keep those letters
|
|
1163
|
+
* unchanged", with screenshots). So the first half is the TUI's own `logo.left`
|
|
1164
|
+
* and `logo.right` strings and its own `wordmark()` painter, byte for byte; the
|
|
1165
|
+
* second half spells `acp client` with the same 4-column alphabet (interior `_`
|
|
1166
|
+
* cells for the shadow, `^`/`~` accents), in the bright half's palette.
|
|
1167
|
+
*/
|
|
1168
|
+
const NATIVE_OPEN = [
|
|
1169
|
+
' ',
|
|
1170
|
+
'█▀▀█ █▀▀█ █▀▀█ █▀▀▄',
|
|
1171
|
+
'█__█ █__█ █^^^ █__█',
|
|
1172
|
+
'▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀~~▀',
|
|
1173
|
+
];
|
|
1174
|
+
const NATIVE_CODE = [
|
|
1175
|
+
' ▄ ',
|
|
1176
|
+
'█▀▀▀ █▀▀█ █▀▀█ █▀▀█',
|
|
1177
|
+
'█___ █__█ █__█ █^^^',
|
|
1178
|
+
'▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀',
|
|
1179
|
+
];
|
|
1180
|
+
/** The letters the native logo does not have, in the same 4-column grammar. */
|
|
1181
|
+
const EXTRA_GLYPHS = {
|
|
1182
|
+
a: [' ', '▀▀▀█', '█__█', '▀▀▀▀'],
|
|
1183
|
+
c: [' ', '█▀▀▀', '█___', '▀▀▀▀'],
|
|
1184
|
+
p: [' ', '█▀▀█', '█__█', '▀▀▀ '],
|
|
1185
|
+
l: [' ', '█ ', '█ ', '▀▀▀▀'],
|
|
1186
|
+
i: [' ▄ ', ' █ ', ' █ ', ' ▀▀ '],
|
|
1187
|
+
e: [' ', '█▀▀█', '█^^^', '▀▀▀▀'],
|
|
1188
|
+
n: [' ', '█▀▀▄', '█__█', '▀~~▀'],
|
|
1189
|
+
t: [' ', '███ ', ' █ ', ' ▀▀ '],
|
|
1190
|
+
' ': [' ', ' ', ' ', ' '],
|
|
1191
|
+
};
|
|
1192
|
+
const WORDMARK_ACP = 'acp';
|
|
1193
|
+
const WORDMARK_CLIENT = 'client';
|
|
1194
|
+
const WORDMARK_FG = '\x1b[90m';
|
|
1195
|
+
const WORDMARK_BRIGHT = '\x1b[39m';
|
|
1196
|
+
const WORDMARK_SHADOW = '\x1b[38;5;235m';
|
|
1197
|
+
const WORDMARK_BG = '\x1b[48;5;235m';
|
|
1198
|
+
const WORDMARK_SHADOW_BRIGHT = '\x1b[38;5;238m';
|
|
1199
|
+
const WORDMARK_BG_BRIGHT = '\x1b[48;5;238m';
|
|
1200
|
+
const WORDMARK_RESET = '\x1b[0m';
|
|
1201
|
+
/** The TUI's own `wordmark()` painter, character for character. */
|
|
1202
|
+
function drawGlyph(line, fg, shadow, bg) {
|
|
1203
|
+
return [...line]
|
|
1204
|
+
.map((char) => {
|
|
1205
|
+
if (char === '_')
|
|
1206
|
+
return `${bg} ${WORDMARK_RESET}`;
|
|
1207
|
+
if (char === '^')
|
|
1208
|
+
return `${fg}${bg}▀${WORDMARK_RESET}`;
|
|
1209
|
+
if (char === '~')
|
|
1210
|
+
return `${shadow}▀${WORDMARK_RESET}`;
|
|
1211
|
+
if (char === ' ')
|
|
1212
|
+
return ' ';
|
|
1213
|
+
return `${fg}${char}${WORDMARK_RESET}`;
|
|
1214
|
+
})
|
|
1215
|
+
.join('');
|
|
1216
|
+
}
|
|
1217
|
+
function glyphRow(text, row) {
|
|
1218
|
+
return [...text].map((char) => EXTRA_GLYPHS[char]?.[row] ?? ' ').join(' ');
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Four rows: the native wordmark, a space, then `acp client`. 91 columns with
|
|
1222
|
+
* the indent; a narrower terminal gets one plain line instead (the rows would
|
|
1223
|
+
* wrap and the cursor arithmetic would land somewhere else).
|
|
1224
|
+
*/
|
|
1225
|
+
export function epilogueWordmark(columns) {
|
|
1226
|
+
// `open` (19) + a space + `code` (19) + gap + `acp` (14) + gap + `client` (29),
|
|
1227
|
+
// plus the two-space indent. The two gaps are the SAME width — a one-space gap
|
|
1228
|
+
// after the bright `code` read as no gap at all, while the 4-column space glyph
|
|
1229
|
+
// the first version used made `acp client` look like two words apart.
|
|
1230
|
+
const gap = ' ';
|
|
1231
|
+
const width = 2 +
|
|
1232
|
+
(NATIVE_OPEN[1].length * 2 + 1) +
|
|
1233
|
+
gap.length +
|
|
1234
|
+
(WORDMARK_ACP.length * 5 - 1) +
|
|
1235
|
+
gap.length +
|
|
1236
|
+
(WORDMARK_CLIENT.length * 5 - 1);
|
|
1237
|
+
if (columns < width + 1) {
|
|
1238
|
+
return [` ${WORDMARK_BRIGHT}opencode acp client${WORDMARK_RESET}`];
|
|
1239
|
+
}
|
|
1240
|
+
return [0, 1, 2, 3].map((row) => ` ${drawGlyph(NATIVE_OPEN[row], WORDMARK_FG, WORDMARK_SHADOW, WORDMARK_BG)} ` +
|
|
1241
|
+
`${drawGlyph(NATIVE_CODE[row], WORDMARK_BRIGHT, WORDMARK_SHADOW_BRIGHT, WORDMARK_BG_BRIGHT)}` +
|
|
1242
|
+
gap +
|
|
1243
|
+
// `acp` in the dark half's palette (the owner's ask: same as `open`), and
|
|
1244
|
+
// `client` in the bright one, keeping the native dark/bright rhythm.
|
|
1245
|
+
`${drawGlyph(glyphRow(WORDMARK_ACP, row), WORDMARK_FG, WORDMARK_SHADOW, WORDMARK_BG)}` +
|
|
1246
|
+
gap +
|
|
1247
|
+
`${drawGlyph(glyphRow(WORDMARK_CLIENT, row), WORDMARK_BRIGHT, WORDMARK_SHADOW_BRIGHT, WORDMARK_BG_BRIGHT)}`);
|
|
1248
|
+
}
|
|
1249
|
+
function formatAge(startedAt) {
|
|
1250
|
+
const seconds = Math.max(0, Math.round((Date.now() - startedAt) / 1000));
|
|
1251
|
+
if (seconds < 60)
|
|
1252
|
+
return `${seconds}s`;
|
|
1253
|
+
const minutes = Math.round(seconds / 60);
|
|
1254
|
+
if (minutes < 60)
|
|
1255
|
+
return `${minutes}m`;
|
|
1256
|
+
const hours = Math.round(minutes / 60);
|
|
1257
|
+
if (hours < 48)
|
|
1258
|
+
return `${hours}h`;
|
|
1259
|
+
return `${Math.round(hours / 24)}d`;
|
|
1260
|
+
}
|
|
1261
|
+
/** This package's version, for the daemon registry (best effort). */
|
|
1262
|
+
function productVersion() {
|
|
1263
|
+
try {
|
|
1264
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
1265
|
+
return pkg.version ?? 'unknown';
|
|
1266
|
+
}
|
|
1267
|
+
catch {
|
|
1268
|
+
return 'unknown';
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* `oc-acp-client ps` — every bridge this tool recorded, newest first.
|
|
1273
|
+
*
|
|
1274
|
+
* Stale entries (a pid that no longer exists) are exactly the cleanup signal:
|
|
1275
|
+
* a bridge that exits cleanly removes its own record, so a leftover means
|
|
1276
|
+
* something killed it without running the shutdown path — and its agent may
|
|
1277
|
+
* still be alive holding a backend's session lock. `--prune` forgets those
|
|
1278
|
+
* records; `--kill` is the explicit, never-automatic way to stop live ones.
|
|
1279
|
+
*/
|
|
1280
|
+
/**
|
|
1281
|
+
* `sessions` — every remembered conversation, newest first.
|
|
1282
|
+
*
|
|
1283
|
+
* Reads the same map the bridge writes, so it works with no bridge and no agent running.
|
|
1284
|
+
* `--limit`/`--offset` page it (`--next` is sugar for "offset by one page"); `--all`
|
|
1285
|
+
* prints everything and `--json` gives the rows unformatted.
|
|
1286
|
+
*/
|
|
1287
|
+
function runSessionsCommand(args) {
|
|
1288
|
+
if (args.sessionsUnknown.length > 0) {
|
|
1289
|
+
// ★ Not a warning and not a silent default. `--director` (one letter short) used to be
|
|
1290
|
+
// swallowed and the command printed every session, which reads exactly like "the
|
|
1291
|
+
// filter does not work" — the failure hides the flag AND the feature.
|
|
1292
|
+
process.stderr.write(` unknown option${args.sessionsUnknown.length > 1 ? 's' : ''} for \`sessions\`: ` +
|
|
1293
|
+
`${args.sessionsUnknown.join(' ')}\n` +
|
|
1294
|
+
' known: --limit N, --offset N, --all, --directory S, --agent A, --width N, --json\n');
|
|
1295
|
+
process.exitCode = 2;
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
const map = new SessionMap(() => { });
|
|
1299
|
+
const filter = {
|
|
1300
|
+
...(args.sessionsDirectory ? { directory: args.sessionsDirectory } : {}),
|
|
1301
|
+
...(args.sessionsAgent ? { agent: args.sessionsAgent } : {}),
|
|
1302
|
+
};
|
|
1303
|
+
const total = countSessions(map, filter);
|
|
1304
|
+
const limit = args.sessionsLimit === 0 ? Math.max(total, 1) : args.sessionsLimit;
|
|
1305
|
+
const offset = args.sessionsOffset >= 0 ? args.sessionsOffset : 0;
|
|
1306
|
+
const rows = listSessions(map, { ...filter, limit, offset });
|
|
1307
|
+
if (args.sessionsJson) {
|
|
1308
|
+
process.stdout.write(`${JSON.stringify({ total, offset, limit, sessions: rows }, null, 2)}\n`);
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
if (total === 0) {
|
|
1312
|
+
process.stdout.write(' no sessions remembered yet.\n');
|
|
1313
|
+
return;
|
|
1314
|
+
}
|
|
1315
|
+
if (rows.length === 0) {
|
|
1316
|
+
process.stdout.write(` nothing at offset ${offset} (${total} remembered)\n`);
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
// `stdout.columns` is undefined whenever the output is piped, which is exactly when a
|
|
1320
|
+
// wide table is most useful; `--width` covers that.
|
|
1321
|
+
const width = args.sessionsWidth ?? process.stdout.columns ?? 100;
|
|
1322
|
+
process.stdout.write(`${renderSessions(rows, { width })}\n\n`);
|
|
1323
|
+
const shown = `${offset + 1}-${offset + rows.length} of ${total}`;
|
|
1324
|
+
if (offset + rows.length < total) {
|
|
1325
|
+
process.stdout.write(` ${shown} — next page: --offset ${offset + rows.length}\n`);
|
|
1326
|
+
}
|
|
1327
|
+
else {
|
|
1328
|
+
process.stdout.write(` ${shown}\n`);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
/**
|
|
1332
|
+
* `upgrade` / `update` — move this package, not opencode.
|
|
1333
|
+
*
|
|
1334
|
+
* `--check` reports what it found and stops; without it the installer runs, with the same
|
|
1335
|
+
* method that installed the current copy (see `detectManager`).
|
|
1336
|
+
*/
|
|
1337
|
+
async function runUpgradeCommand(args) {
|
|
1338
|
+
if (args.unknownUpgrade.length > 0) {
|
|
1339
|
+
process.stderr.write(` unknown option${args.unknownUpgrade.length > 1 ? 's' : ''} for \`upgrade\`: ` +
|
|
1340
|
+
`${args.unknownUpgrade.join(' ')}\n usage: upgrade [<version>] [--check]\n`);
|
|
1341
|
+
process.exitCode = 2;
|
|
1342
|
+
return;
|
|
1343
|
+
}
|
|
1344
|
+
const { plan, found } = planUpgrade(args.upgradeTarget);
|
|
1345
|
+
if (!found) {
|
|
1346
|
+
process.stderr.write(` ${PACKAGE_NAME} is not published to the registry this npm points at, so there is\n` +
|
|
1347
|
+
` nothing to upgrade to from here. Install from the repo to track its main branch.\n`);
|
|
1348
|
+
process.exitCode = 1;
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
process.stdout.write(` ${PACKAGE_NAME} ${plan.current} → ${plan.latest}\n`);
|
|
1352
|
+
process.stdout.write(` method: ${plan.manager} (${plan.reason})\n`);
|
|
1353
|
+
if (plan.upToDate) {
|
|
1354
|
+
process.stdout.write(` already up to date\n`);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (args.upgradeCheck) {
|
|
1358
|
+
process.stdout.write(` would run: ${plan.command.join(' ')}\n`);
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
process.exitCode = await runUpgrade(plan, (line) => process.stdout.write(`${line}\n`));
|
|
1362
|
+
}
|
|
1363
|
+
function runPsCommand(args) {
|
|
1364
|
+
const entries = listDaemons();
|
|
1365
|
+
const alive = entries.filter((entry) => entry.alive);
|
|
1366
|
+
const stale = entries.filter((entry) => !entry.alive);
|
|
1367
|
+
if (args.psKill) {
|
|
1368
|
+
for (const entry of alive) {
|
|
1369
|
+
try {
|
|
1370
|
+
process.kill(entry.record.pid, 'SIGTERM');
|
|
1371
|
+
process.stdout.write(` sent SIGTERM to ${entry.record.pid}\n`);
|
|
1372
|
+
}
|
|
1373
|
+
catch (err) {
|
|
1374
|
+
process.stdout.write(` could not signal ${entry.record.pid}: ${String(err)}\n`);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
if (args.psJson) {
|
|
1379
|
+
process.stdout.write(`${JSON.stringify({
|
|
1380
|
+
daemons: entries.map((entry) => ({ ...entry.record, alive: entry.alive })),
|
|
1381
|
+
alive: alive.length,
|
|
1382
|
+
stale: stale.length,
|
|
1383
|
+
}, undefined, 2)}\n`);
|
|
1384
|
+
}
|
|
1385
|
+
else if (entries.length === 0) {
|
|
1386
|
+
process.stdout.write(' no bridge processes recorded.\n');
|
|
1387
|
+
}
|
|
1388
|
+
else {
|
|
1389
|
+
const header = ['PID', 'STATE', 'AGE', 'AGENT', 'DIRECTORY', 'URL'];
|
|
1390
|
+
const rows = entries.map((entry) => [
|
|
1391
|
+
String(entry.record.pid),
|
|
1392
|
+
entry.alive ? 'alive' : 'stale',
|
|
1393
|
+
formatAge(entry.record.startedAt),
|
|
1394
|
+
[entry.record.agent, ...(entry.record.agentArgs ?? [])].join(' '),
|
|
1395
|
+
entry.record.directory,
|
|
1396
|
+
entry.record.url,
|
|
1397
|
+
]);
|
|
1398
|
+
const widths = header.map((title, index) => Math.max(title.length, ...rows.map((row) => (row[index] ?? '').length)));
|
|
1399
|
+
const render = (row) => ' ' + row.map((cell, index) => (cell ?? '').padEnd(widths[index])).join(' ').trimEnd();
|
|
1400
|
+
process.stdout.write(`${render(header)}\n`);
|
|
1401
|
+
for (const row of rows)
|
|
1402
|
+
process.stdout.write(`${render(row)}\n`);
|
|
1403
|
+
process.stdout.write(`\n ${alive.length} alive, ${stale.length} stale` +
|
|
1404
|
+
(stale.length > 0 ? ' (--prune forgets stale records)' : '') +
|
|
1405
|
+
'\n');
|
|
1406
|
+
}
|
|
1407
|
+
if (args.psPrune) {
|
|
1408
|
+
const removed = pruneDaemons();
|
|
1409
|
+
process.stdout.write(` pruned ${removed} stale record(s)\n`);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Fix the TUI's exit epilogue so the `Continue` line resumes THIS product.
|
|
1414
|
+
*
|
|
1415
|
+
* ★ Why not a stdout pipe: the TUI probes the stdio it is handed for TTY-ness
|
|
1416
|
+
* (terminal size, mouse). A piped stdout is not a TTY, and the measured result
|
|
1417
|
+
* was a small window glued to the terminal's top-left corner — the full-screen
|
|
1418
|
+
* layout collapsed to a fallback size. stdio therefore stays inherited, and the
|
|
1419
|
+
* rewrite happens AFTER the child exits.
|
|
1420
|
+
*
|
|
1421
|
+
* ★ The geometry is exact: the epilogue ends with `Continue …\n\n` (a trailing
|
|
1422
|
+
* blank line), so when the TUI finishes the cursor sits TWO rows below the
|
|
1423
|
+
* `Continue` row. `ESC[2A` lands on it, `CR + ESC[2K` clears the row, and the
|
|
1424
|
+
* replacement is printed with the blank restored.
|
|
1425
|
+
*
|
|
1426
|
+
* ★ The four logo rows sit ABOVE the Session row, i.e. eight rows above the
|
|
1427
|
+
* cursor, and they are replaced in the same pass (`ESC[8A`, four rows, then
|
|
1428
|
+
* `ESC[4B` back to the cursor's original row). Every opencode v2 build we
|
|
1429
|
+
* support prints that wordmark; the version gate already refuses <2.
|
|
1430
|
+
*
|
|
1431
|
+
* ★ Guards: only on a TTY, and only when the bridge served a session (the
|
|
1432
|
+
* epilogue exists). The line must not wrap — a wrapped row breaks the two-row
|
|
1433
|
+
* geometry — so an over-long one is SHORTENED, not abandoned: the full command
|
|
1434
|
+
* first, then a form without the agent tail (`oc-acp-client -s ses_…`).
|
|
1435
|
+
* Abandoning it (an earlier shape) left the native `opencode -s …` line, which
|
|
1436
|
+
* the owner reported as the rewrite "not working" — measured on a 130-column
|
|
1437
|
+
* terminal where the full line was 149 columns.
|
|
1438
|
+
*/
|
|
1439
|
+
function rewriteEpilogue(epilogueTarget, log) {
|
|
1440
|
+
const out = process.stdout;
|
|
1441
|
+
if (!out.isTTY) {
|
|
1442
|
+
log('[bridge] epilogue left as-is: stdout is not a TTY');
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
// A probe for the geometry itself: leave the TUI's epilogue untouched so a
|
|
1446
|
+
// capture shows exactly what it printed (used while measuring the wordmark
|
|
1447
|
+
// rows; harmless otherwise, and cheaper than guessing).
|
|
1448
|
+
if (process.env['OPENCODE_ACP_CLIENT_EPILOGUE_PROBE'] === '1') {
|
|
1449
|
+
log('[bridge] epilogue left as-is: probe mode');
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
const sessionId = epilogueTarget();
|
|
1453
|
+
if (!sessionId) {
|
|
1454
|
+
// Nothing to resume, so there is no Continue line to write — but the TUI has still
|
|
1455
|
+
// printed its own epilogue, and on a screen with no transcript it lands on top of
|
|
1456
|
+
// whatever was there before the client started (measured in tmux: the native TUI
|
|
1457
|
+
// exits from the welcome screen leaving its block over the user's old prompt lines).
|
|
1458
|
+
// Clear from the cursor down so the terminal is tidy; this only touches the visible
|
|
1459
|
+
// area, never the scrollback.
|
|
1460
|
+
out.write('\r\x1b[J');
|
|
1461
|
+
log('[bridge] epilogue cleared: no session was named this run');
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
const columns = out.columns ?? 80;
|
|
1465
|
+
const line = epilogueLine(sessionId, columns);
|
|
1466
|
+
if (!line) {
|
|
1467
|
+
log(`[bridge] epilogue left as-is: even '${shortResumeCommand(sessionId)}' would wrap in ${columns} columns`);
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
// ★ Replace the wordmark above the `Continue` row too. The TUI's epilogue is
|
|
1471
|
+
// `logo(4 rows) + blank + Session + Continue + blank`, so the logo is exactly
|
|
1472
|
+
// eight rows above where the cursor sits now. We cannot change opencode's
|
|
1473
|
+
// binary, but overwriting its own rows is the same trick this function already
|
|
1474
|
+
// uses for the Continue line — and it makes the screen the user returns to
|
|
1475
|
+
// name THIS product instead of the TUI it borrowed.
|
|
1476
|
+
const wordmark = epilogueWordmark(columns);
|
|
1477
|
+
// ★ Anchored on the Continue row, never on an absolute offset. The epilogue is
|
|
1478
|
+
// `logo + blank + Session + Continue + blank`, and the TUI's logo is four rows
|
|
1479
|
+
// whose FIRST is all spaces — the row that scrolls away when the block sits at
|
|
1480
|
+
// the bottom of the screen. Measured in tmux: moving up eight rows from the
|
|
1481
|
+
// cursor landed on the blank row in a tall screen but one row ABOVE the top in
|
|
1482
|
+
// a 42-row pane, which lost our first row and shifted everything up. The three
|
|
1483
|
+
// visible logo rows are always `cursor-7 .. cursor-5`, so those are the rows we
|
|
1484
|
+
// write, and `cursor-2` is always the Continue row.
|
|
1485
|
+
// One write for the whole block: it cannot interleave with itself, and it ends
|
|
1486
|
+
// on the Continue line (no trailing newlines, which could scroll a bottom-row
|
|
1487
|
+
// block).
|
|
1488
|
+
const logoRows = [...wordmark];
|
|
1489
|
+
// The TUI's block is four rows; the top row is mostly blank, so if the screen
|
|
1490
|
+
// scrolled it is the row that went off (and clipping it is what the native logo
|
|
1491
|
+
// does too). Pad regardless: the cursor arithmetic must not depend on the
|
|
1492
|
+
// fallback having produced fewer rows.
|
|
1493
|
+
while (logoRows.length < 4)
|
|
1494
|
+
logoRows.push('');
|
|
1495
|
+
// ★ Ends with a newline: without it the user's shell prompt was printed on the
|
|
1496
|
+
// same line as `Continue` (owner's screenshot). The two newlines restore the
|
|
1497
|
+
// blank line the TUI itself leaves after the block.
|
|
1498
|
+
out.write(`\x1b[8A${logoRows.map((row) => `\r\x1b[2K${row}\n`).join('')}\x1b[2B` +
|
|
1499
|
+
`\r\x1b[2K${line}\n`);
|
|
1500
|
+
log(`[bridge] epilogue rewritten: ${line}`);
|
|
1501
|
+
}
|
|
1502
|
+
/**
|
|
1503
|
+
* The replacement `Continue` row, or undefined when even the shortest form would
|
|
1504
|
+
* wrap.
|
|
1505
|
+
*
|
|
1506
|
+
* Exported and pure because the width rule has a measured history: an over-long
|
|
1507
|
+
* line was once ABANDONED (leaving the TUI's native `opencode -s …` — read by the
|
|
1508
|
+
* owner as "the rewrite is broken"), and the fix was to shorten it instead. A
|
|
1509
|
+
* wrapped row also breaks the `ESC[2A` geometry, which is why the length check is
|
|
1510
|
+
* a hard filter rather than best effort. ` Continue ` is the client's own
|
|
1511
|
+
* prefix and is part of the measurement.
|
|
1512
|
+
*/
|
|
1513
|
+
export function epilogueLine(sessionId, columns) {
|
|
1514
|
+
const command = [resumeCommand(sessionId), shortResumeCommand(sessionId)].find((candidate) => ` Continue ${candidate}`.length < columns);
|
|
1515
|
+
return command ? ` Continue ${command}` : undefined;
|
|
1516
|
+
}
|
|
1517
|
+
/** The narrow-terminal fallback: the launcher and the id, nothing else. */
|
|
1518
|
+
function shortResumeCommand(sessionId) {
|
|
1519
|
+
return `${invocationCommand()} -s ${sessionId}`;
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* The id the exit epilogue's `Continue` line should name, in order of how sure
|
|
1523
|
+
* we are about it. Pure and exported so the ordering itself can be tested; the
|
|
1524
|
+
* three sources and why they rank this way:
|
|
1525
|
+
*
|
|
1526
|
+
* 1. `prompted` — the session the user actually TYPED into this run. The one
|
|
1527
|
+
* signal the bridge owns outright (it is set at the top of the prompt
|
|
1528
|
+
* handler), so nothing outranks it.
|
|
1529
|
+
* 2. `intent` — the session the user ASKED to resume (`--session <id>`, or the
|
|
1530
|
+
* id `-c` resolved to). This is intent, not inference. Measured: with
|
|
1531
|
+
* several restored tabs the client hydrates each one in turn, and the
|
|
1532
|
+
* last-read heuristic named a DIFFERENT tab than the one the user resumed.
|
|
1533
|
+
* 3. `viewed` — the last session the client hydrated/read. A resume with no
|
|
1534
|
+
* typing and no flag lands here; it beats leaving the TUI's native
|
|
1535
|
+
* `opencode -s <id>` line in place (which names neither this product nor
|
|
1536
|
+
* an id the native daemon knows), but a prefetch can end up last, so it
|
|
1537
|
+
* never outranks intent.
|
|
1538
|
+
*/
|
|
1539
|
+
export function epilogueSessionCandidates(sources) {
|
|
1540
|
+
return [sources.prompted, sources.intent, sources.viewed].filter((id) => typeof id === 'string' && id.length > 0);
|
|
1541
|
+
}
|
|
1542
|
+
export function epilogueSessionId(sources) {
|
|
1543
|
+
return epilogueSessionCandidates(sources)[0];
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* The epilogue may only name an id the NEXT start can resolve.
|
|
1547
|
+
*
|
|
1548
|
+
* Measured by the owner (2026-10-18): after a real conversation the line said
|
|
1549
|
+
* `-s ses_eb55…`, and the next start answered "unknown session id" — the session had a
|
|
1550
|
+
* record, but its map pairing was filed under a different (pre-adoption) id. That
|
|
1551
|
+
* particular bug is fixed at the source, but a session that never reached an agent (a
|
|
1552
|
+
* POST with no prompt) still has no pairing, and the `viewed` tier can name it. So the
|
|
1553
|
+
* candidate list is filtered by `resolveSessionId`: never print a line that cannot work.
|
|
1554
|
+
*/
|
|
1555
|
+
export function firstResolvableSessionId(candidates, resolve = (id) => resolveSessionId(id)) {
|
|
1556
|
+
for (const candidate of candidates) {
|
|
1557
|
+
if (!candidate)
|
|
1558
|
+
continue;
|
|
1559
|
+
try {
|
|
1560
|
+
resolve(candidate);
|
|
1561
|
+
return candidate;
|
|
1562
|
+
}
|
|
1563
|
+
catch {
|
|
1564
|
+
// Provably unknown (`ses_…` with no map entry): try the next tier instead of
|
|
1565
|
+
// printing a Continue line that is guaranteed to fail.
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
return undefined;
|
|
1569
|
+
}
|
|
1570
|
+
function confirm(question) {
|
|
1571
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
1572
|
+
return new Promise((resolve) => {
|
|
1573
|
+
rl.question(question, (answer) => {
|
|
1574
|
+
rl.close();
|
|
1575
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
1576
|
+
});
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
function runToCompletion(command, argv, log) {
|
|
1580
|
+
return new Promise((resolve) => {
|
|
1581
|
+
const child = spawn(command, argv, { stdio: 'inherit' });
|
|
1582
|
+
child.on('error', (err) => {
|
|
1583
|
+
log(`[bridge] ${command} failed: ${err.message}`);
|
|
1584
|
+
resolve(1);
|
|
1585
|
+
});
|
|
1586
|
+
child.on('close', (code) => resolve(code ?? 1));
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Where our own logs go.
|
|
1591
|
+
*
|
|
1592
|
+
* When the TUI is started (the default) it takes over the terminal, and any
|
|
1593
|
+
* stray write — even one log line — tears its rendering. So in that mode the
|
|
1594
|
+
* default sink is a file rather than stderr, and the path is printed once,
|
|
1595
|
+
* before the TUI starts, while the terminal is still ours.
|
|
1596
|
+
*/
|
|
1597
|
+
function makeLogSink(args) {
|
|
1598
|
+
const path = args.logPath ?? (args.launch ? join(mkdtempSync(join(tmpdir(), 'acp-bridge-')), 'bridge.log') : undefined);
|
|
1599
|
+
if (!path)
|
|
1600
|
+
return { log: (line) => process.stderr.write(`${line}\n`), where: 'stderr' };
|
|
1601
|
+
const stream = createWriteStream(path, { flags: 'a' });
|
|
1602
|
+
// Everything that writes to the terminal must go through here, or it tears the TUI's
|
|
1603
|
+
// rendering. `sse.ts` logs its frames with `console.error` directly, and the default sink
|
|
1604
|
+
// in server.ts is `process.stderr`: in the single-entry mode both land on the same
|
|
1605
|
+
// terminal the TUI is drawing on, and every broadcast damages the screen — which is what
|
|
1606
|
+
// made a shell card's content disappear while the rest of the row survived. The split
|
|
1607
|
+
// setups never showed it because their bridge wrote to another window. Redirecting the
|
|
1608
|
+
// console here covers those two and anything added later.
|
|
1609
|
+
const forward = (level, parts) => {
|
|
1610
|
+
stream.write(`${level} ${parts.map((p) => (typeof p === 'string' ? p : String(p))).join(' ')}\n`);
|
|
1611
|
+
};
|
|
1612
|
+
console.error = (...parts) => forward('[stderr]', parts);
|
|
1613
|
+
console.log = (...parts) => forward('[stdout]', parts);
|
|
1614
|
+
return { log: (line) => stream.write(`${line}\n`), where: path };
|
|
1615
|
+
}
|
|
1616
|
+
async function main() {
|
|
1617
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1618
|
+
// `ps`: no agent, no TUI, no opencode binary — just the registry.
|
|
1619
|
+
if (args.bridgeCommand === 'upgrade') {
|
|
1620
|
+
await runUpgradeCommand(args);
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
if (args.bridgeCommand === 'sessions') {
|
|
1624
|
+
runSessionsCommand(args);
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
if (args.bridgeCommand === 'ps') {
|
|
1628
|
+
runPsCommand(args);
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
// A NATIVE opencode subcommand (`models`, `acp`, `api`, `plugin`, `run`, …):
|
|
1632
|
+
// the command means opencode itself, so behave as the binary would — argv
|
|
1633
|
+
// as-is, the binary's own output on our stdio, its exit code as ours. No
|
|
1634
|
+
// bridge is started (nothing speaks ACP), no TUI (the subcommand is not the
|
|
1635
|
+
// TUI), no agent requirement (that is why this check precedes the agent
|
|
1636
|
+
// preflight: `oc-acp-client models` must work without an `-- <agent>`
|
|
1637
|
+
// argument at all).
|
|
1638
|
+
if (args.nativeCommand) {
|
|
1639
|
+
const binary = resolveOpenCodeBinary();
|
|
1640
|
+
const dashIndex = process.argv.indexOf('--');
|
|
1641
|
+
const argv = process.argv.slice(2, dashIndex === -1 ? undefined : dashIndex);
|
|
1642
|
+
if (args.nativeSubcommand && WRAPPED_SUBCOMMANDS.has(args.nativeSubcommand) && args.agentCommand) {
|
|
1643
|
+
// A WRAPPED subcommand: the answer must come from THIS product's server —
|
|
1644
|
+
// the agent's models, the agent's sessions — not opencode's own daemon.
|
|
1645
|
+
// Start the bridge server-only, run the opencode binary with --server
|
|
1646
|
+
// pointing at it (its own official handler renders the output), mirror
|
|
1647
|
+
// the exit code, shut the bridge down. No TUI: the subcommand is not
|
|
1648
|
+
// the TUI. An agent is REQUIRED here — without `-- <agent>` there is
|
|
1649
|
+
// nothing to answer about, and the raw passthrough below handles that.
|
|
1650
|
+
await runWrappedSubcommand(args, binary, argv);
|
|
1651
|
+
}
|
|
1652
|
+
try {
|
|
1653
|
+
execFileSync(binary.path, argv, { stdio: 'inherit', killSignal: 'SIGINT' });
|
|
1654
|
+
process.exit(0);
|
|
1655
|
+
}
|
|
1656
|
+
catch (err) {
|
|
1657
|
+
// execFileSync throws on a non-zero exit; the child's stdio is already
|
|
1658
|
+
// ours, so only the exit code is left to mirror.
|
|
1659
|
+
const status = err.status;
|
|
1660
|
+
process.exit(status === undefined ? 1 : status);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
const { log, where } = makeLogSink(args);
|
|
1664
|
+
// Machine-facing noise ON A TERMINAL: the launch path inherits the terminal,
|
|
1665
|
+
// and this line (like the ready JSON) was left on the primary screen, where it
|
|
1666
|
+
// reappeared under the TUI on exit. Print it only when something is capturing
|
|
1667
|
+
// the stream (a script, a log) or when serving without a TUI.
|
|
1668
|
+
if (!args.launch || !process.stderr.isTTY)
|
|
1669
|
+
process.stderr.write(`[bridge] logs: ${where}\n`);
|
|
1670
|
+
// One client = one agent: with -s the session's map entry names the agent; with -c
|
|
1671
|
+
// the newest remembered session for this directory does. No `--` is needed (or
|
|
1672
|
+
// accepted) in either case. A new session still needs `-- <agent>`.
|
|
1673
|
+
if (args.session || args.continueSession) {
|
|
1674
|
+
const map = new SessionMap(() => undefined);
|
|
1675
|
+
if (args.session) {
|
|
1676
|
+
const owner = map.agentFor(args.session);
|
|
1677
|
+
if (!owner) {
|
|
1678
|
+
const known = map.acpIdFor(args.session) !== undefined;
|
|
1679
|
+
throw new Error(known
|
|
1680
|
+
? `session ${args.session} predates the agent binding; start a new session with -- <agent>`
|
|
1681
|
+
: `cannot infer the agent for ${args.session}: it is not in the session map; ` +
|
|
1682
|
+
`start a new session with -- <agent>`);
|
|
1683
|
+
}
|
|
1684
|
+
args.agentCommand = owner.command;
|
|
1685
|
+
args.agentArgs = [...owner.args];
|
|
1686
|
+
}
|
|
1687
|
+
else {
|
|
1688
|
+
const entry = newestContinueEntry(map.entries(), args.directory);
|
|
1689
|
+
if (!entry) {
|
|
1690
|
+
throw new Error(`no session to continue in ${args.directory}; start a new one with -- <agent>`);
|
|
1691
|
+
}
|
|
1692
|
+
args.agentCommand = entry.agent.command;
|
|
1693
|
+
args.agentArgs = [...entry.agent.args];
|
|
1694
|
+
args.session = entry.visibleId;
|
|
1695
|
+
log(`[bridge] -c -> ${entry.visibleId} (${agentBindingLabel(entry.agent)})`);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
// Fail fast on an agent command that cannot run (see findExecutable). Fatal
|
|
1699
|
+
// when we are about to start the TUI — there is a human waiting for one — and
|
|
1700
|
+
// advice-only when serving, where the operator may be wiring things up.
|
|
1701
|
+
if (args.agentCommand === undefined) {
|
|
1702
|
+
throw new Error('missing agent command (put it after --)');
|
|
1703
|
+
}
|
|
1704
|
+
if (!findExecutable(args.agentCommand, process.env, args.directory)) {
|
|
1705
|
+
const problem = `agent command not found: ${args.agentCommand}`;
|
|
1706
|
+
if (args.launch) {
|
|
1707
|
+
throw new Error(`${problem} (put a runnable command after --, or pass --no-tui to serve without one)`);
|
|
1708
|
+
}
|
|
1709
|
+
log(`[bridge] warning: ${problem}; continuing as a server`);
|
|
1710
|
+
}
|
|
1711
|
+
// `--session <id>` takes the id the TUI shows (`ses_…`) — but the agent only
|
|
1712
|
+
// answers to its OWN id (a UUID), and the two never match. The session map is
|
|
1713
|
+
// exactly the visible→agent pairing, written on every session this bridge
|
|
1714
|
+
// serves, so translate before resuming. An id the map does not know is
|
|
1715
|
+
// passed through as given: the agent's session/load answers for whether it
|
|
1716
|
+
// exists — that keeps `--session <agent-uuid>` working for ids learned
|
|
1717
|
+
// elsewhere (dsh's web UI shows those).
|
|
1718
|
+
const launchBinding = args.agentCommand
|
|
1719
|
+
? { command: args.agentCommand, args: args.agentArgs }
|
|
1720
|
+
: undefined;
|
|
1721
|
+
const resolvedSession = resolveSessionId(args.session, log, launchBinding);
|
|
1722
|
+
// Resolve the client version before the bridge starts so `/api/info` reports the
|
|
1723
|
+
// same version the TUI will compare against itself. The fallback (direct
|
|
1724
|
+
// BridgeServer construction) is only for tests/desktop with no launcher.
|
|
1725
|
+
const clientBinary = resolveOpenCodeBinary();
|
|
1726
|
+
const clientVersion = await readOpenCodeVersion(clientBinary);
|
|
1727
|
+
const clientVersionLabel = clientVersion
|
|
1728
|
+
? `${clientVersion.major}.${clientVersion.minor}.${clientVersion.patch}`
|
|
1729
|
+
: undefined;
|
|
1730
|
+
const server = new BridgeServer({
|
|
1731
|
+
command: args.agentCommand,
|
|
1732
|
+
args: args.agentArgs,
|
|
1733
|
+
directory: args.directory,
|
|
1734
|
+
host: args.host,
|
|
1735
|
+
port: args.port,
|
|
1736
|
+
clientVersion: clientVersionLabel,
|
|
1737
|
+
resumeSession: resolvedSession,
|
|
1738
|
+
resumeVisibleSessionId: args.session,
|
|
1739
|
+
eagerCatalog: process.env['OPENCODE_ACP_CLIENT_EAGER_CATALOG'] === '1',
|
|
1740
|
+
continueMode: false,
|
|
1741
|
+
onLog: log,
|
|
1742
|
+
});
|
|
1743
|
+
const { host, port } = await server.listen();
|
|
1744
|
+
const url = `http://${host}:${port}`;
|
|
1745
|
+
// Same rule as the log line: the ready line is for scripts that need the port.
|
|
1746
|
+
// On a terminal the user never reads it, and it was part of the exit noise.
|
|
1747
|
+
if (!args.launch || !process.stdout.isTTY) {
|
|
1748
|
+
process.stdout.write(`${JSON.stringify({
|
|
1749
|
+
type: 'ready',
|
|
1750
|
+
url,
|
|
1751
|
+
directory: args.directory,
|
|
1752
|
+
agent: args.agentCommand,
|
|
1753
|
+
})}\n`);
|
|
1754
|
+
}
|
|
1755
|
+
// Record this bridge so `ps` can find it even if the process is killed later
|
|
1756
|
+
// (the record is removed on a clean shutdown; a leftover IS the stale signal).
|
|
1757
|
+
registerDaemon({
|
|
1758
|
+
directory: args.directory,
|
|
1759
|
+
agent: args.agentCommand,
|
|
1760
|
+
agentArgs: args.agentArgs ?? [],
|
|
1761
|
+
url,
|
|
1762
|
+
version: productVersion(),
|
|
1763
|
+
});
|
|
1764
|
+
// Shutdown discipline. Installed before anything that can take real time:
|
|
1765
|
+
// a Ctrl-C during a slow (or broken) agent startup must still stop us, or the
|
|
1766
|
+
// agent child is orphaned with nobody left to dispose it.
|
|
1767
|
+
//
|
|
1768
|
+
// `client` is the opencode v2 TUI and the only child this process spawns itself;
|
|
1769
|
+
// every agent and shell the server owns is disposed by `server.close()`. Both
|
|
1770
|
+
// go through explicit PIDs — never a name-based kill.
|
|
1771
|
+
let client;
|
|
1772
|
+
let shuttingDown = false;
|
|
1773
|
+
let signalGrace;
|
|
1774
|
+
const shutdown = async (reason, code = 0, options = {}) => {
|
|
1775
|
+
if (shuttingDown)
|
|
1776
|
+
return;
|
|
1777
|
+
shuttingDown = true;
|
|
1778
|
+
if (signalGrace) {
|
|
1779
|
+
clearTimeout(signalGrace);
|
|
1780
|
+
signalGrace = undefined;
|
|
1781
|
+
}
|
|
1782
|
+
log(`[bridge] ${reason}, shutting down`);
|
|
1783
|
+
if (!options.keepClient)
|
|
1784
|
+
client?.kill(reason === 'SIGINT' ? 'SIGINT' : 'SIGTERM');
|
|
1785
|
+
await server.close();
|
|
1786
|
+
unregisterDaemon();
|
|
1787
|
+
process.exit(code);
|
|
1788
|
+
};
|
|
1789
|
+
// ★ A signal reaches the TUI too (same process group), and the TUI exits through
|
|
1790
|
+
// its own quit path — the path that prints the `Continue` epilogue this product
|
|
1791
|
+
// rewrites. Exiting here first raced that: measured on Ctrl-C, the native
|
|
1792
|
+
// `Continue opencode -s …` line appeared with no rewrite. Wait for the child's
|
|
1793
|
+
// 'close' (which owns the rewrite), with a grace period so a TUI that ignores
|
|
1794
|
+
// the signal cannot leave us serving forever.
|
|
1795
|
+
const onSignal = (reason) => {
|
|
1796
|
+
if (shuttingDown)
|
|
1797
|
+
return;
|
|
1798
|
+
if (!client) {
|
|
1799
|
+
void shutdown(reason);
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
log(`[bridge] ${reason}, waiting for the TUI to exit`);
|
|
1803
|
+
if (signalGrace)
|
|
1804
|
+
return;
|
|
1805
|
+
signalGrace = setTimeout(() => {
|
|
1806
|
+
signalGrace = undefined;
|
|
1807
|
+
void shutdown(reason);
|
|
1808
|
+
}, 5_000);
|
|
1809
|
+
};
|
|
1810
|
+
// The shutdown path covers SIGINT/SIGTERM and the TUI exiting; this covers any
|
|
1811
|
+
// other orderly exit (a throw, `process.exit` from a wrapped subcommand path).
|
|
1812
|
+
process.on('exit', () => unregisterDaemon());
|
|
1813
|
+
process.on('SIGINT', () => onSignal('SIGINT'));
|
|
1814
|
+
process.on('SIGTERM', () => onSignal('SIGTERM'));
|
|
1815
|
+
// SIGHUP is how a terminal session ends (closing the window, tmux kill-session,
|
|
1816
|
+
// the parent shell dying). Without a handler the bridge dies INSTANTLY and its
|
|
1817
|
+
// agent children are orphaned — measured: 14 orphaned dsh processes held the
|
|
1818
|
+
// workspace's one-writer lock and every later session/load answered "Internal
|
|
1819
|
+
// error", so resumed conversations came up blank until the orphans were
|
|
1820
|
+
// reaped by hand. The handler gives the same orderly teardown as Ctrl-C.
|
|
1821
|
+
process.on('SIGHUP', () => onSignal('SIGHUP'));
|
|
1822
|
+
// Give ACP a moment to advertise its models before the TUI can read them,
|
|
1823
|
+
// otherwise it submits the placeholder and the session breaks.
|
|
1824
|
+
if (args.launch)
|
|
1825
|
+
await server.waitForCatalog();
|
|
1826
|
+
// What the exit epilogue names: see `epilogueSessionId` for the ordering and
|
|
1827
|
+
// the measurements behind it. `args.session` is the id the USER typed (the
|
|
1828
|
+
// visible one), and `continueSession.visibleId` is the visible pair for the id
|
|
1829
|
+
// `-c` resolved to; both are what `--session` accepts on the next run.
|
|
1830
|
+
const resumeTarget = args.session;
|
|
1831
|
+
// Kept in a named binding because the close handler below (which owns the
|
|
1832
|
+
// epilogue rewrite) needs the same closure.
|
|
1833
|
+
const epilogueTarget = () => firstResolvableSessionId(epilogueSessionCandidates({
|
|
1834
|
+
prompted: server.promptedSessionId(),
|
|
1835
|
+
intent: resumeTarget,
|
|
1836
|
+
viewed: server.viewedSessionId(),
|
|
1837
|
+
}));
|
|
1838
|
+
client = await handleClient(args, url, resolvedSession, epilogueTarget, log, (message) => {
|
|
1839
|
+
// A TUI that never started must not leave us serving nothing.
|
|
1840
|
+
log(`[bridge] ${message}`);
|
|
1841
|
+
void shutdown('TUI launch failed', 1);
|
|
1842
|
+
});
|
|
1843
|
+
if (client) {
|
|
1844
|
+
// The TUI owns the session: when it exits, so do we, and its exit code is
|
|
1845
|
+
// the useful one. This is what leaves no adapter behind.
|
|
1846
|
+
// ★ 'close' (stdio drained), not 'exit': the epilogue is written by the TUI's
|
|
1847
|
+
// own scrollback writer, and rewriting on 'exit' interleaved with it —
|
|
1848
|
+
// measured: the first wordmark row was lost and the block shifted up by one.
|
|
1849
|
+
client.on('close', (code) => {
|
|
1850
|
+
rewriteEpilogue(epilogueTarget, log);
|
|
1851
|
+
void shutdown('the TUI exited', code ?? 0);
|
|
1852
|
+
});
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
/**
|
|
1856
|
+
* Whether this file is the program being run.
|
|
1857
|
+
*
|
|
1858
|
+
* `process.argv[1]` is a *symlink* path when the command is installed as a bin
|
|
1859
|
+
* (`/…/bin/oc-acp-client`), while `import.meta.url` is the real file, so
|
|
1860
|
+
* comparing the strings directly makes the CLI a no-op that exits 0. Resolve
|
|
1861
|
+
* both sides before comparing.
|
|
1862
|
+
*/
|
|
1863
|
+
function isDirectInvocation() {
|
|
1864
|
+
const entry = process.argv[1];
|
|
1865
|
+
if (!entry)
|
|
1866
|
+
return false;
|
|
1867
|
+
try {
|
|
1868
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
1869
|
+
}
|
|
1870
|
+
catch {
|
|
1871
|
+
// A missing entry (e.g. `node -e`) is simply not a direct invocation.
|
|
1872
|
+
return false;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
const invokedDirectly = isDirectInvocation();
|
|
1876
|
+
if (invokedDirectly || process.env.OPENCODE_ACP_CLIENT_RUN === '1') {
|
|
1877
|
+
main().catch((err) => {
|
|
1878
|
+
process.stderr.write(`oc-acp-client: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
1879
|
+
process.exit(1);
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
//# sourceMappingURL=index.js.map
|