@cogitator-ai/bridge 0.2.0 → 0.3.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/README.md +156 -8
- package/dist/adapter.d.ts +123 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +2 -0
- package/dist/adapter.js.map +1 -0
- package/dist/adapters/claude.d.ts +90 -0
- package/dist/adapters/claude.d.ts.map +1 -0
- package/dist/adapters/claude.js +359 -0
- package/dist/adapters/claude.js.map +1 -0
- package/dist/adapters/codex.d.ts +58 -0
- package/dist/adapters/codex.d.ts.map +1 -0
- package/dist/adapters/codex.js +330 -0
- package/dist/adapters/codex.js.map +1 -0
- package/dist/adapters/exec.d.ts +57 -0
- package/dist/adapters/exec.d.ts.map +1 -0
- package/dist/adapters/exec.js +149 -0
- package/dist/adapters/exec.js.map +1 -0
- package/dist/adapters/hosted.d.ts +168 -0
- package/dist/adapters/hosted.d.ts.map +1 -0
- package/dist/adapters/hosted.js +361 -0
- package/dist/adapters/hosted.js.map +1 -0
- package/dist/client.d.ts +9 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +17 -3
- package/dist/client.js.map +1 -1
- package/dist/dispatcher.d.ts +67 -17
- package/dist/dispatcher.d.ts.map +1 -1
- package/dist/dispatcher.js +240 -17
- package/dist/dispatcher.js.map +1 -1
- package/dist/host.d.ts +1 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/index.d.ts +13 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/inputs.d.ts +40 -1
- package/dist/inputs.d.ts.map +1 -1
- package/dist/inputs.js +25 -2
- package/dist/inputs.js.map +1 -1
- package/dist/paths.d.ts +6 -0
- package/dist/paths.d.ts.map +1 -1
- package/dist/paths.js +19 -0
- package/dist/paths.js.map +1 -1
- package/dist/protocol.d.ts +5 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +5 -0
- package/dist/protocol.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +6 -1
- package/dist/server.js.map +1 -1
- package/dist/testing/conformance.d.ts +65 -0
- package/dist/testing/conformance.d.ts.map +1 -0
- package/dist/testing/conformance.js +217 -0
- package/dist/testing/conformance.js.map +1 -0
- package/dist/testing/fake-harnesses.d.ts +101 -0
- package/dist/testing/fake-harnesses.d.ts.map +1 -0
- package/dist/testing/fake-harnesses.js +291 -0
- package/dist/testing/fake-harnesses.js.map +1 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +3 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/types.d.ts +3 -39
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/dist/waiter.d.ts +36 -0
- package/dist/waiter.d.ts.map +1 -0
- package/dist/waiter.js +92 -0
- package/dist/waiter.js.map +1 -0
- package/fakes/claude.mjs +450 -0
- package/fakes/codex.mjs +391 -0
- package/fakes/lib.mjs +507 -0
- package/package.json +7 -1
package/fakes/claude.mjs
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* A stand-in for the Claude Code command line as far as the bridge adapters use it: background
|
|
4
|
+
* sessions, their listing, Stop hooks with rewake, `stop` and `rm`. The commands `__open` and
|
|
5
|
+
* `__say` exist only here and play a person at an open window. The behaviour was measured on
|
|
6
|
+
* Claude Code 2.1.292.
|
|
7
|
+
*/
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { readFileSync, rmSync } from 'node:fs';
|
|
10
|
+
import { join, resolve } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import {
|
|
13
|
+
CliError,
|
|
14
|
+
POLL_MS,
|
|
15
|
+
Unsupported,
|
|
16
|
+
abandonWork,
|
|
17
|
+
awaitJson,
|
|
18
|
+
boundLife,
|
|
19
|
+
enqueue,
|
|
20
|
+
flag,
|
|
21
|
+
isAlive,
|
|
22
|
+
isStateName,
|
|
23
|
+
isWithin,
|
|
24
|
+
listRecords,
|
|
25
|
+
listedIn,
|
|
26
|
+
option,
|
|
27
|
+
parseArgs,
|
|
28
|
+
patchJson,
|
|
29
|
+
performTurn,
|
|
30
|
+
print,
|
|
31
|
+
readJson,
|
|
32
|
+
recordTurn,
|
|
33
|
+
renderHelp,
|
|
34
|
+
runCli,
|
|
35
|
+
sleep,
|
|
36
|
+
spawnDetached,
|
|
37
|
+
startShell,
|
|
38
|
+
stateRoot,
|
|
39
|
+
takeNext,
|
|
40
|
+
terminate,
|
|
41
|
+
writeJson,
|
|
42
|
+
} from './lib.mjs';
|
|
43
|
+
|
|
44
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
45
|
+
const VERSION = '2.1.292';
|
|
46
|
+
const DEFAULT_HOOK_TIMEOUT_S = 600;
|
|
47
|
+
const NOT_TRUSTED =
|
|
48
|
+
'Workspace not trusted. Run claude once in this folder and accept the trust prompt';
|
|
49
|
+
|
|
50
|
+
const OPEN_FLAGS = {
|
|
51
|
+
'--settings': option('settings'),
|
|
52
|
+
'-n': option('name'),
|
|
53
|
+
'--name': option('name'),
|
|
54
|
+
};
|
|
55
|
+
const START_FLAGS = {
|
|
56
|
+
...OPEN_FLAGS,
|
|
57
|
+
'--bg': flag('bg'),
|
|
58
|
+
'--background': flag('bg'),
|
|
59
|
+
'--permission-mode': option('permissionMode'),
|
|
60
|
+
'--model': option('model'),
|
|
61
|
+
'--append-system-prompt': option('appendSystemPrompt'),
|
|
62
|
+
'--add-dir': option('addDir'),
|
|
63
|
+
};
|
|
64
|
+
const AGENTS_FLAGS = {
|
|
65
|
+
'--json': flag('json'),
|
|
66
|
+
'--all': flag('all'),
|
|
67
|
+
'--cwd': option('cwd'),
|
|
68
|
+
'--help': flag('help'),
|
|
69
|
+
'-h': flag('help'),
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** What FAKE_CLAUDE_MISSING can take away from the options that start a session */
|
|
73
|
+
const REMOVABLE_START_OPTIONS = [
|
|
74
|
+
['bg', '--bg'],
|
|
75
|
+
['settings', '--settings'],
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
const HELP = [
|
|
79
|
+
'Usage: claude [options] [command] [prompt]',
|
|
80
|
+
'',
|
|
81
|
+
'Claude Code - starts an interactive session by default',
|
|
82
|
+
'',
|
|
83
|
+
'Options:',
|
|
84
|
+
['bg', ' --bg, --background Start the session in the background and return'],
|
|
85
|
+
['settings', ' --settings <file-or-json> A settings JSON file or a JSON string to load'],
|
|
86
|
+
' -n, --name <name> Set a display name for the session',
|
|
87
|
+
' --permission-mode <mode> Permission mode to use for the session',
|
|
88
|
+
' --model <model> Model for the session',
|
|
89
|
+
' --append-system-prompt <text> Append text to the default system prompt',
|
|
90
|
+
' --add-dir <dir> An additional folder to allow tool access to',
|
|
91
|
+
' -v, --version Output the version number',
|
|
92
|
+
' -h, --help Display help for command',
|
|
93
|
+
'',
|
|
94
|
+
'Commands:',
|
|
95
|
+
' agents [options] List sessions',
|
|
96
|
+
' attach <id> Attach to a background session',
|
|
97
|
+
' stop <id> Stop a session',
|
|
98
|
+
' rm <id> Remove a session',
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
const AGENTS_HELP = [
|
|
102
|
+
'Usage: claude agents [options]',
|
|
103
|
+
'',
|
|
104
|
+
'List sessions',
|
|
105
|
+
'',
|
|
106
|
+
'Options:',
|
|
107
|
+
['agents-json', ' --json Print the sessions as a JSON array'],
|
|
108
|
+
' --all Include stopped sessions',
|
|
109
|
+
' --cwd <path> Only sessions in this folder or below it',
|
|
110
|
+
' -h, --help Display help for command',
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
const missing = () => listedIn('FAKE_CLAUDE_MISSING');
|
|
114
|
+
const trustedFile = () => join(stateRoot('claude'), 'trusted.json');
|
|
115
|
+
const sessionsDir = () => join(stateRoot('claude'), 'sessions');
|
|
116
|
+
|
|
117
|
+
/** The state paths of a session. An id that could lead out of the sessions folder is refused */
|
|
118
|
+
function sessionFiles(sessionId) {
|
|
119
|
+
if (!isStateName(sessionId)) throw new Unsupported();
|
|
120
|
+
const base = join(sessionsDir(), sessionId);
|
|
121
|
+
return { record: `${base}.json`, transcript: `${base}.jsonl`, spool: `${base}.in` };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function main(argv) {
|
|
125
|
+
const [command, ...rest] = argv;
|
|
126
|
+
switch (command) {
|
|
127
|
+
case '--version':
|
|
128
|
+
case '-v':
|
|
129
|
+
return print(`${process.env.FAKE_CLAUDE_VERSION || VERSION} (Claude Code)`);
|
|
130
|
+
case '--help':
|
|
131
|
+
case '-h':
|
|
132
|
+
return print(renderHelp(HELP, missing()));
|
|
133
|
+
case 'agents':
|
|
134
|
+
return agents(rest);
|
|
135
|
+
case 'stop':
|
|
136
|
+
return stop(rest);
|
|
137
|
+
case 'rm':
|
|
138
|
+
return remove(rest);
|
|
139
|
+
case '__open':
|
|
140
|
+
return open(rest);
|
|
141
|
+
case '__say':
|
|
142
|
+
return say(rest);
|
|
143
|
+
case '__session':
|
|
144
|
+
return runSession(rest);
|
|
145
|
+
default:
|
|
146
|
+
return background(argv);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function background(argv) {
|
|
151
|
+
const { values, positionals } = parseArgs(argv, START_FLAGS);
|
|
152
|
+
const [prompt] = positionals;
|
|
153
|
+
if (!values.bg || positionals.length !== 1 || prompt.trim() === '') throw new Unsupported();
|
|
154
|
+
for (const [feature, name] of REMOVABLE_START_OPTIONS) {
|
|
155
|
+
if (missing().has(feature) && values[feature] !== undefined) {
|
|
156
|
+
throw new CliError(`error: unknown option '${name}'`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (process.env.FAKE_CLAUDE_BG_FAIL) throw new CliError(process.env.FAKE_CLAUDE_BG_FAIL);
|
|
160
|
+
if (!isTrusted(process.cwd())) throw new CliError(NOT_TRUSTED);
|
|
161
|
+
const session = startSession({
|
|
162
|
+
kind: 'background',
|
|
163
|
+
name: values.name ?? defaultName(prompt),
|
|
164
|
+
settings: values.settings,
|
|
165
|
+
permissionMode: values.permissionMode,
|
|
166
|
+
prompt,
|
|
167
|
+
});
|
|
168
|
+
await print(`backgrounded · ${session.id} · ${session.name}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function open(argv) {
|
|
172
|
+
const { values, positionals } = parseArgs(argv, OPEN_FLAGS);
|
|
173
|
+
if (positionals.length > 0) throw new Unsupported();
|
|
174
|
+
const session = startSession({
|
|
175
|
+
kind: 'interactive',
|
|
176
|
+
name: values.name,
|
|
177
|
+
settings: values.settings,
|
|
178
|
+
});
|
|
179
|
+
await print(session.sessionId);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function isTrusted(folder) {
|
|
183
|
+
return readJson(trustedFile(), []).some((trusted) => isWithin(folder, trusted));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function defaultName(prompt) {
|
|
187
|
+
return prompt.trim().split(/\s+/).slice(0, 3).join('-').toLowerCase();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Writes the record of a new session and starts its process. A background session begins busy
|
|
192
|
+
* with its prompt, an interactive one sits idle until somebody types.
|
|
193
|
+
*/
|
|
194
|
+
function startSession({ kind, name, settings, permissionMode, prompt }) {
|
|
195
|
+
checkSettings(settings);
|
|
196
|
+
const sessionId = randomUUID();
|
|
197
|
+
const files = sessionFiles(sessionId);
|
|
198
|
+
const inBackground = kind === 'background';
|
|
199
|
+
if (prompt !== undefined) enqueue(files.spool, { wokenBy: 'prompt', text: prompt });
|
|
200
|
+
const record = {
|
|
201
|
+
...(inBackground && { id: shortId(sessionId) }),
|
|
202
|
+
sessionId,
|
|
203
|
+
name,
|
|
204
|
+
cwd: process.cwd(),
|
|
205
|
+
kind,
|
|
206
|
+
startedAt: Date.now(),
|
|
207
|
+
pid: spawnDetached(SELF, ['__session', sessionId]),
|
|
208
|
+
status: inBackground ? 'busy' : 'idle',
|
|
209
|
+
...(inBackground && { state: 'working' }),
|
|
210
|
+
settings,
|
|
211
|
+
permissionMode,
|
|
212
|
+
};
|
|
213
|
+
writeJson(files.record, record);
|
|
214
|
+
return record;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const shortId = (sessionId) => sessionId.slice(0, 8);
|
|
218
|
+
|
|
219
|
+
/** The value of `--settings`: a JSON string, or the path of a JSON file */
|
|
220
|
+
function readSettingsOption(value, cwd) {
|
|
221
|
+
const json = value.trimStart().startsWith('{')
|
|
222
|
+
? value
|
|
223
|
+
: readFileSync(resolve(cwd, value), 'utf8');
|
|
224
|
+
return JSON.parse(json);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function checkSettings(value) {
|
|
228
|
+
if (value === undefined) return;
|
|
229
|
+
try {
|
|
230
|
+
readSettingsOption(value, process.cwd());
|
|
231
|
+
} catch (error) {
|
|
232
|
+
throw new CliError(`Error: cannot load --settings: ${error.message}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* What a session inherits from the command that started it. Claude Code does not promise a
|
|
238
|
+
* background session the environment of `claude --bg`: with FAKE_CLAUDE_BG_CLEAN_ENV set the
|
|
239
|
+
* fake keeps only what a service started on its own would have, so a test can prove that
|
|
240
|
+
* nothing depends on more.
|
|
241
|
+
*/
|
|
242
|
+
function sessionBaseEnv() {
|
|
243
|
+
if (!process.env.FAKE_CLAUDE_BG_CLEAN_ENV) return process.env;
|
|
244
|
+
return Object.fromEntries(
|
|
245
|
+
Object.entries(process.env).filter(
|
|
246
|
+
([name]) => ['PATH', 'HOME', 'TMPDIR'].includes(name) || name.startsWith('FAKE_')
|
|
247
|
+
)
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The session process: takes the prompt, typed messages and hook wake-ups in the order they
|
|
253
|
+
* arrived, runs a turn for each and fires the Stop hooks after it.
|
|
254
|
+
*/
|
|
255
|
+
async function runSession(argv) {
|
|
256
|
+
const [sessionId] = argv;
|
|
257
|
+
if (argv.length !== 1) throw new Unsupported();
|
|
258
|
+
const files = sessionFiles(sessionId);
|
|
259
|
+
const record = await awaitJson(files.record);
|
|
260
|
+
if (record === undefined) return;
|
|
261
|
+
const env = {
|
|
262
|
+
...sessionBaseEnv(),
|
|
263
|
+
CLAUDE_CODE_SESSION_ID: sessionId,
|
|
264
|
+
CLAUDE_PROJECT_DIR: record.cwd,
|
|
265
|
+
};
|
|
266
|
+
const session = { record, files, env, hookPids: new Set() };
|
|
267
|
+
boundLife(files.record, () => endSession(files.record));
|
|
268
|
+
for (;;) {
|
|
269
|
+
const message = await nextMessage(files.spool);
|
|
270
|
+
setActivity(session, 'busy');
|
|
271
|
+
const outcome = await performTurn({ input: message.text, cwd: record.cwd, env });
|
|
272
|
+
setActivity(session, 'idle');
|
|
273
|
+
recordTurn(files.transcript, outcome, message.wokenBy);
|
|
274
|
+
await fireStopHooks(session, outcome.answer, message.wokenBy === 'hook');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function nextMessage(spool) {
|
|
279
|
+
for (;;) {
|
|
280
|
+
const message = takeNext(spool);
|
|
281
|
+
if (message !== undefined) return message;
|
|
282
|
+
await sleep(POLL_MS);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function setActivity({ record, files }, status) {
|
|
287
|
+
const state = status === 'busy' ? 'working' : 'done';
|
|
288
|
+
patchJson(files.record, record.kind === 'background' ? { status, state } : { status });
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function endSession(recordFile) {
|
|
292
|
+
abandonWork();
|
|
293
|
+
patchJson(recordFile, {
|
|
294
|
+
pid: undefined,
|
|
295
|
+
status: undefined,
|
|
296
|
+
hookPids: undefined,
|
|
297
|
+
state: 'stopped',
|
|
298
|
+
});
|
|
299
|
+
process.exit(0);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Runs the Stop hooks of a session that just went idle. The session waits for a plain hook,
|
|
304
|
+
* a hook with `asyncRewake` or `async` is left running, also across later turns.
|
|
305
|
+
*/
|
|
306
|
+
async function fireStopHooks(session, answer, wokenByHook) {
|
|
307
|
+
const { record, files } = session;
|
|
308
|
+
const payload = JSON.stringify({
|
|
309
|
+
session_id: record.sessionId,
|
|
310
|
+
transcript_path: files.transcript,
|
|
311
|
+
cwd: record.cwd,
|
|
312
|
+
permission_mode: record.permissionMode ?? 'default',
|
|
313
|
+
hook_event_name: 'Stop',
|
|
314
|
+
stop_hook_active: wokenByHook,
|
|
315
|
+
last_assistant_message: answer,
|
|
316
|
+
});
|
|
317
|
+
for (const hook of stopHooks(record)) {
|
|
318
|
+
const ended = runHook(session, hook, payload);
|
|
319
|
+
if (hook.asyncRewake === true) void ended.then((result) => wake(files, rewakeText(result)));
|
|
320
|
+
else if (hook.async !== true) wake(files, blockingText(await ended));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** The command hooks of the Stop event from `--settings` and the two project settings files */
|
|
325
|
+
function stopHooks(record) {
|
|
326
|
+
const project = join(record.cwd, '.claude');
|
|
327
|
+
const sources = [
|
|
328
|
+
() => record.settings && readSettingsOption(record.settings, record.cwd),
|
|
329
|
+
() => readJson(join(project, 'settings.json')),
|
|
330
|
+
() => readJson(join(project, 'settings.local.json')),
|
|
331
|
+
];
|
|
332
|
+
return sources.flatMap((read) => {
|
|
333
|
+
try {
|
|
334
|
+
return commandHooks(read());
|
|
335
|
+
} catch {
|
|
336
|
+
return [];
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function commandHooks(settings) {
|
|
342
|
+
const groups = settings?.hooks?.Stop;
|
|
343
|
+
if (!Array.isArray(groups)) return [];
|
|
344
|
+
return groups
|
|
345
|
+
.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
|
|
346
|
+
.filter((hook) => hook?.type === 'command' && typeof hook.command === 'string');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function runHook(session, hook, payload) {
|
|
350
|
+
const timeoutS = typeof hook.timeout === 'number' ? hook.timeout : DEFAULT_HOOK_TIMEOUT_S;
|
|
351
|
+
const shell = startShell(hook.command, {
|
|
352
|
+
cwd: session.record.cwd,
|
|
353
|
+
env: session.env,
|
|
354
|
+
input: payload,
|
|
355
|
+
timeoutMs: timeoutS * 1000,
|
|
356
|
+
killSignal: 'SIGTERM',
|
|
357
|
+
});
|
|
358
|
+
if (shell.pid === undefined) return shell.done;
|
|
359
|
+
trackHook(session, (pids) => pids.add(shell.pid));
|
|
360
|
+
return shell.done.finally(() => trackHook(session, (pids) => pids.delete(shell.pid)));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Keeps the pids of the running hooks in the record, for whoever has to clean up after a crash */
|
|
364
|
+
function trackHook(session, change) {
|
|
365
|
+
change(session.hookPids);
|
|
366
|
+
patchJson(session.files.record, { hookPids: [...session.hookPids] });
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const asksForTurn = ({ code, timedOut }) => code === 2 && !timedOut;
|
|
370
|
+
|
|
371
|
+
function blockingText(result) {
|
|
372
|
+
return (asksForTurn(result) && result.stderr.trim()) || undefined;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function rewakeText(result) {
|
|
376
|
+
return asksForTurn(result) ? result.stderr.trim() || result.stdout.trim() : undefined;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function wake(files, text) {
|
|
380
|
+
if (text !== undefined) enqueue(files.spool, { wokenBy: 'hook', text });
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** A record as it stands now: a session whose process is gone counts as stopped */
|
|
384
|
+
function current(record) {
|
|
385
|
+
if (record.pid !== undefined && isAlive(record.pid)) return record;
|
|
386
|
+
return { ...record, pid: undefined, status: undefined, hookPids: undefined, state: 'stopped' };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function listSessions() {
|
|
390
|
+
return listRecords(sessionsDir())
|
|
391
|
+
.map(current)
|
|
392
|
+
.sort((a, b) => a.startedAt - b.startedAt);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Finds a session by its session id or short id, or else the newest one with that name */
|
|
396
|
+
function findSession(argv) {
|
|
397
|
+
const [ref] = argv;
|
|
398
|
+
if (argv.length !== 1) throw new Unsupported();
|
|
399
|
+
const newestFirst = listSessions().reverse();
|
|
400
|
+
const found =
|
|
401
|
+
newestFirst.find(({ sessionId }) => sessionId === ref || shortId(sessionId) === ref) ??
|
|
402
|
+
newestFirst.find(({ name }) => name === ref);
|
|
403
|
+
if (found === undefined) throw new CliError(`No session found for '${ref}'`);
|
|
404
|
+
return found;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function agents(argv) {
|
|
408
|
+
const { values, positionals } = parseArgs(argv, AGENTS_FLAGS);
|
|
409
|
+
if (values.help) return print(renderHelp(AGENTS_HELP, missing()));
|
|
410
|
+
if (values.json && missing().has('agents-json'))
|
|
411
|
+
throw new CliError("error: unknown option '--json'");
|
|
412
|
+
if (!values.json || positionals.length > 0) throw new Unsupported();
|
|
413
|
+
const sessions = listSessions()
|
|
414
|
+
.filter(({ pid }) => values.all || pid !== undefined)
|
|
415
|
+
.filter(({ cwd }) => values.cwd === undefined || isWithin(cwd, values.cwd));
|
|
416
|
+
await print(JSON.stringify(sessions.map(listed), null, 2));
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** What `agents --json` shows of a session: `id` and `state` are there for background ones only */
|
|
420
|
+
function listed({ id, sessionId, name, cwd, kind, startedAt, pid, status, state }) {
|
|
421
|
+
const shown = { id, sessionId, name, cwd, kind, startedAt, pid, status };
|
|
422
|
+
return kind === 'background' ? { ...shown, state } : shown;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function stopSession({ pid }) {
|
|
426
|
+
if (pid !== undefined) await terminate(pid);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function stop(argv) {
|
|
430
|
+
await stopSession(findSession(argv));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function remove(argv) {
|
|
434
|
+
const session = findSession(argv);
|
|
435
|
+
await stopSession(session);
|
|
436
|
+
const files = sessionFiles(session.sessionId);
|
|
437
|
+
rmSync(files.record, { force: true });
|
|
438
|
+
rmSync(files.transcript, { force: true });
|
|
439
|
+
rmSync(files.spool, { recursive: true, force: true });
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
async function say(argv) {
|
|
443
|
+
const [ref, text] = argv;
|
|
444
|
+
if (argv.length !== 2) throw new Unsupported();
|
|
445
|
+
const session = findSession([ref]);
|
|
446
|
+
if (session.pid === undefined) throw new CliError(`Session '${ref}' is not running`);
|
|
447
|
+
enqueue(sessionFiles(session.sessionId).spool, { wokenBy: 'user', text });
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
await runCli('claude', main);
|