@conveno/cli 0.1.1 → 0.2.0-rc.1

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.
@@ -0,0 +1,871 @@
1
+ import { chmodSync, existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { n as connect } from "./dist-DsRTUePN.js";
3
+ import { $ as isAllowed, Ut as spawnRecordPath, Yt as takeAcpLaunchFile, ft as parseAllowPatterns, jt as readSpawnRecord, m as acpTurnsPath, q as formatContinuation, r as ConvenoError, sn as CliKind, tn as updateSpawnRecord, xn as SessionId, yn as RpcErrorCode } from "./dist-_qrCNXUP.js";
4
+ import { randomBytes } from "node:crypto";
5
+ import { Readable, Writable } from "node:stream";
6
+ import { PROTOCOL_VERSION, client, methods, ndJsonStream } from "@agentclientprotocol/sdk";
7
+ import { appendFile } from "node:fs/promises";
8
+ import { t as redact } from "./dist-DcmKjrmu.js";
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ import { i as parseFlags, l as fail, o as cmd, t as COMMANDS, u as localStamp } from "./args-DHkLY6_f.js";
11
+ // ../acp/dist/index.js
12
+ /**
13
+ * Pick the option to answer with. Allowing uses `allow_once` only: `allow_always` would change the
14
+ * CLI's own saved permissions, which is the user's call. Denying uses `reject_once`, and when the
15
+ * agent offers none, `cancelled`, so no `reject_always` rule is saved either.
16
+ */
17
+ function answer(ask, allow) {
18
+ const want = allow ? "allow_once" : "reject_once";
19
+ const option = ask.options.find((o) => o.kind === want);
20
+ return option ? {
21
+ outcome: "selected",
22
+ optionId: option.optionId
23
+ } : { outcome: "cancelled" };
24
+ }
25
+ var AllowListPolicy = class {
26
+ rules;
27
+ constructor(rules) {
28
+ this.rules = rules;
29
+ }
30
+ async decide(ask, _signal) {
31
+ const what = `${ask.title ?? "a tool call"} (${ask.kind ?? "other"})`;
32
+ if (isAllowed(this.rules, {
33
+ kind: ask.kind,
34
+ title: ask.title
35
+ })) {
36
+ const outcome = answer(ask, true);
37
+ if (outcome.outcome === "selected") return {
38
+ allowed: true,
39
+ outcome,
40
+ reason: `allowed ${what} by --allow`
41
+ };
42
+ return {
43
+ allowed: false,
44
+ outcome: answer(ask, false),
45
+ reason: `denied ${what}: allowed by --allow, but the agent offered no allow-once option`
46
+ };
47
+ }
48
+ return {
49
+ allowed: false,
50
+ outcome: answer(ask, false),
51
+ reason: `denied ${what}: nobody watches this worker, and --allow does not cover it`
52
+ };
53
+ }
54
+ };
55
+ /** An agent message being streamed is written out at least this often. */
56
+ const FLUSH_MS = 500;
57
+ const clip = (s) => s.length <= 8e3 ? s : `${s.slice(0, 7990)}\n[clipped]`;
58
+ var TurnLog = class {
59
+ path;
60
+ now;
61
+ entries = [];
62
+ seq = 0;
63
+ pending = "";
64
+ timer;
65
+ size = 0;
66
+ writes = Promise.resolve();
67
+ /** Tool calls seen in this session: their latest title and kind, for permission requests. */
68
+ tools = /* @__PURE__ */ new Map();
69
+ constructor(path, now = () => /* @__PURE__ */ new Date()) {
70
+ this.path = path;
71
+ this.now = now;
72
+ if (path) {
73
+ writeFileSync(path, "", { mode: 384 });
74
+ try {
75
+ chmodSync(path, 384);
76
+ } catch {}
77
+ }
78
+ }
79
+ /** The entries in memory, oldest first. */
80
+ recent(n = 200) {
81
+ return this.entries.slice(-n);
82
+ }
83
+ add(role, text) {
84
+ if (role !== "assistant") this.flush();
85
+ if (text === "") return;
86
+ const entry = {
87
+ seq: ++this.seq,
88
+ role,
89
+ text: clip(redact(text)),
90
+ at: this.now().toISOString()
91
+ };
92
+ this.entries.push(entry);
93
+ if (this.entries.length > 200) this.entries.splice(0, this.entries.length - 200);
94
+ this.write(entry);
95
+ }
96
+ /** Feed one `session/update`. Returns a status line when the update says what the agent is doing. */
97
+ update(u) {
98
+ if (u.sessionUpdate === "agent_message_chunk") {
99
+ const c = u.content;
100
+ if (c.type === "text" && c.text) {
101
+ this.pending += c.text;
102
+ if (this.pending.length >= 8e3) this.flush();
103
+ else this.timer ??= setTimeout(() => this.flush(), FLUSH_MS);
104
+ }
105
+ return;
106
+ }
107
+ if (u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update") {
108
+ const t = u;
109
+ const next = {
110
+ ...this.tools.get(t.toolCallId) ?? {},
111
+ ...t.title ? { title: t.title } : {},
112
+ ...t.kind ? { kind: t.kind } : {}
113
+ };
114
+ this.tools.set(t.toolCallId, next);
115
+ if (this.tools.size > 1e3) {
116
+ const first = this.tools.keys().next().value;
117
+ if (first !== void 0) this.tools.delete(first);
118
+ }
119
+ const title = next.title ?? next.kind ?? "tool";
120
+ if (u.sessionUpdate === "tool_call") {
121
+ this.add("tool", `${title}${next.kind ? ` (${next.kind})` : ""}`);
122
+ return title;
123
+ }
124
+ if (t.status === "completed" || t.status === "failed") this.add("tool", `${title}: ${t.status}`);
125
+ return;
126
+ }
127
+ }
128
+ /** Write out the agent message streamed so far. */
129
+ flush() {
130
+ if (this.timer) clearTimeout(this.timer);
131
+ this.timer = void 0;
132
+ const text = this.pending;
133
+ this.pending = "";
134
+ if (text.trim() !== "") this.add("assistant", text);
135
+ }
136
+ /** Resolves once every entry so far is on disk. */
137
+ async settle() {
138
+ this.flush();
139
+ await this.writes;
140
+ }
141
+ write(entry) {
142
+ const path = this.path;
143
+ if (!path) return;
144
+ const line = `${JSON.stringify(entry)}\n`;
145
+ this.writes = this.writes.then(async () => {
146
+ try {
147
+ if (this.size + line.length > 1e6) {
148
+ const text = this.entries.map((e) => `${JSON.stringify(e)}\n`).join("");
149
+ writeFileSync(`${path}.tmp`, text, { mode: 384 });
150
+ renameSync(`${path}.tmp`, path);
151
+ this.size = text.length;
152
+ return;
153
+ }
154
+ await appendFile(path, line, { mode: 384 });
155
+ this.size += line.length;
156
+ } catch {}
157
+ });
158
+ }
159
+ };
160
+ /** Parse a turns file. Lines that are not entries are skipped. */
161
+ function parseTurns(text) {
162
+ const out = [];
163
+ for (const line of text.split("\n")) {
164
+ if (line.trim() === "") continue;
165
+ try {
166
+ const v = JSON.parse(line);
167
+ if (typeof v.seq === "number" && typeof v.text === "string" && typeof v.at === "string" && (v.role === "user" || v.role === "assistant" || v.role === "tool" || v.role === "system")) out.push({
168
+ seq: v.seq,
169
+ role: v.role,
170
+ text: v.text,
171
+ at: v.at
172
+ });
173
+ } catch {}
174
+ }
175
+ return out;
176
+ }
177
+ const HOST_VERSION = "0.2.0-rc.1";
178
+ /** A stop request file: `conveno stop` writes it next to the spawn record. */
179
+ const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
180
+ function withTimeout(p, ms, what) {
181
+ return new Promise((resolve, reject) => {
182
+ const t = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} did not answer within ${Math.round(ms / 1e3)} s.`)), ms);
183
+ p.then((v) => {
184
+ clearTimeout(t);
185
+ resolve(v);
186
+ }, (e) => {
187
+ clearTimeout(t);
188
+ reject(e);
189
+ });
190
+ });
191
+ }
192
+ const errText = (e) => e instanceof Error ? e.message : String(e);
193
+ /** A JSON-RPC error's own words: an agent that throws gets "Internal error" with the text in `data.details`. */
194
+ const requestReason = (e) => {
195
+ const details = e?.data?.details;
196
+ return typeof details === "string" && details.trim() !== "" ? details.trim() : errText(e);
197
+ };
198
+ const describeStop = (r) => {
199
+ switch (r.kind) {
200
+ case "requested": return `stopped by ${r.by}`;
201
+ case "agent-exit": return `its ACP server exited (${r.signal ? `signal ${r.signal}` : `code ${r.code ?? "none"}`})`;
202
+ case "session-gone": return `its Conveno session ended (${r.detail})`;
203
+ case "failed": return `it failed: ${r.detail}`;
204
+ }
205
+ };
206
+ /**
207
+ * Drive one worker until it stops. Returns the process exit code: 0 for a requested stop, 1 for
208
+ * anything else.
209
+ */
210
+ async function runAcpHost(spec, deps) {
211
+ return new AcpHost(spec, deps).run();
212
+ }
213
+ var AcpHost = class {
214
+ spec;
215
+ deps;
216
+ client;
217
+ log;
218
+ policy;
219
+ turns;
220
+ sessionId;
221
+ acpSessionId;
222
+ conn;
223
+ agent;
224
+ stopReason;
225
+ stopCtl = new AbortController();
226
+ /** Aborted to cancel the current prompt turn; pending permission policies see it too. */
227
+ turnCtl = new AbortController();
228
+ lastPromptFailure;
229
+ /** The status line after a failed prompt, kept until the next prompt starts. */
230
+ failedText;
231
+ denials = [];
232
+ lastStatus;
233
+ timers = [];
234
+ constructor(spec, deps) {
235
+ this.spec = spec;
236
+ this.deps = deps;
237
+ this.client = deps.client;
238
+ this.log = deps.log ?? ((line) => process.stderr.write(`[conveno acp-host] ${line}\n`));
239
+ const rules = parseAllowPatterns(spec.allow);
240
+ this.policy = deps.policy ?? new AllowListPolicy(rules.ok ? rules.rules : []);
241
+ this.turns = new TurnLog(spec.turnsPath, deps.now);
242
+ }
243
+ /** Ask the host to stop. The first reason wins. */
244
+ stop(reason) {
245
+ if (this.stopReason) return;
246
+ this.stopReason = reason;
247
+ this.log(`stopping: ${describeStop(reason)}`);
248
+ this.stopCtl.abort();
249
+ this.turnCtl.abort();
250
+ }
251
+ get stopping() {
252
+ return this.stopReason !== void 0;
253
+ }
254
+ async run() {
255
+ const onSignal = () => this.stop({
256
+ kind: "requested",
257
+ by: "a signal"
258
+ });
259
+ process.once("SIGTERM", onSignal);
260
+ process.once("SIGINT", onSignal);
261
+ try {
262
+ await this.setup();
263
+ await this.loop();
264
+ } catch (e) {
265
+ if (!this.stopping) this.stop({
266
+ kind: "failed",
267
+ detail: errText(e)
268
+ });
269
+ } finally {
270
+ process.off("SIGTERM", onSignal);
271
+ process.off("SIGINT", onSignal);
272
+ await this.teardown();
273
+ }
274
+ return this.stopReason?.kind === "requested" ? 0 : 1;
275
+ }
276
+ async setup() {
277
+ const { spec } = this;
278
+ const timeout = spec.setupTimeoutMs ?? this.deps.setupTimeoutMs ?? 12e4;
279
+ this.agent = await this.deps.startAgent(spec);
280
+ const agent = this.agent;
281
+ this.log(`started ${spec.file} (pid ${agent.pid}) for ${spec.name}`);
282
+ agent.exited.then(({ code, signal }) => {
283
+ this.stop({
284
+ kind: "agent-exit",
285
+ code,
286
+ signal
287
+ });
288
+ });
289
+ updateSpawnRecord(spec.record, {
290
+ pid: process.pid,
291
+ agentPid: agent.pid
292
+ });
293
+ this.every(this.deps.stopPollMs ?? 500, () => {
294
+ const path = stopRequestPath(spec.record);
295
+ if (existsSync(path)) {
296
+ rmSync(path, { force: true });
297
+ this.stop({
298
+ kind: "requested",
299
+ by: "conveno stop"
300
+ });
301
+ }
302
+ });
303
+ const app = client({ name: "conveno" }).onNotification(methods.client.session.update, ({ params }) => this.onUpdate(params)).onRequest(methods.client.session.requestPermission, ({ params }) => this.onPermission(params));
304
+ this.conn = app.connect(ndJsonStream(Writable.toWeb(agent.stdin), Readable.toWeb(agent.stdout)));
305
+ const conn = this.conn;
306
+ const init = await this.untilStopped(withTimeout(conn.agent.request(methods.agent.initialize, {
307
+ protocolVersion: PROTOCOL_VERSION,
308
+ clientCapabilities: {
309
+ fs: {
310
+ readTextFile: false,
311
+ writeTextFile: false
312
+ },
313
+ terminal: false
314
+ },
315
+ clientInfo: {
316
+ name: "conveno",
317
+ version: HOST_VERSION
318
+ }
319
+ }), timeout, "initialize"));
320
+ const agentVersion = init.agentInfo?.version?.trim().slice(0, 64);
321
+ this.log(`initialize: protocol ${init.protocolVersion}, agent ${init.agentInfo?.name ?? "unknown"} ${agentVersion ?? ""}`);
322
+ const created = await this.untilStopped(withTimeout(conn.agent.request(methods.agent.session.new, {
323
+ cwd: spec.cwd,
324
+ mcpServers: spec.mcp ? [{
325
+ name: "conveno",
326
+ command: spec.mcp.command,
327
+ args: spec.mcp.args,
328
+ env: []
329
+ }] : []
330
+ }), timeout, "session/new"));
331
+ this.acpSessionId = created.sessionId;
332
+ this.log(`session/new: ${created.sessionId}`);
333
+ const spawnedBy = SessionId.safeParse(spec.spawnedBy);
334
+ const { session } = await this.client["session.register"]({
335
+ name: spec.name,
336
+ cli: CliKind.parse(spec.cli),
337
+ cwd: spec.cwd,
338
+ pid: process.pid,
339
+ hostPid: process.pid,
340
+ spawned: true,
341
+ acp: true,
342
+ ...spawnedBy.success ? { spawnedBy: spawnedBy.data } : {},
343
+ ...agentVersion ? { cliVersion: agentVersion } : {}
344
+ });
345
+ this.sessionId = session.id;
346
+ updateSpawnRecord(spec.record, {
347
+ pid: process.pid,
348
+ sessionId: session.id,
349
+ agentPid: agent.pid
350
+ });
351
+ this.log(`registered as ${session.name} (${session.id})`);
352
+ await this.client["session.setCliInfo"]({
353
+ pid: process.pid,
354
+ cliSessionId: created.sessionId.slice(0, 200),
355
+ transcriptPath: spec.turnsPath
356
+ }).catch((e) => this.log(`could not report the turn log: ${errText(e)}`));
357
+ this.every(this.deps.heartbeatMs ?? 15e3, () => this.heartbeat());
358
+ }
359
+ async loop() {
360
+ let next = this.spec.task ?? null;
361
+ if (next === null) await this.status("idle", null);
362
+ while (!this.stopping) if (next !== null) {
363
+ await this.prompt(next);
364
+ if (this.stopping) break;
365
+ await this.reportDenials();
366
+ next = await this.endTurn();
367
+ } else next = await this.waitForWork();
368
+ }
369
+ /** Report the end of a turn. Returns the prompt to continue with, or null to wait for work. */
370
+ async endTurn() {
371
+ try {
372
+ const r = await this.client["turn.end"]({
373
+ sessionId: this.me,
374
+ allowContinue: true
375
+ });
376
+ const next = formatContinuation(r.messages, r.orchestrator, r.remaining) || null;
377
+ if (next === null) await this.status(void 0, this.failedText ?? null);
378
+ return next;
379
+ } catch (e) {
380
+ if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
381
+ this.stop({
382
+ kind: "session-gone",
383
+ detail: errText(e)
384
+ });
385
+ return null;
386
+ }
387
+ this.log(`turn.end failed: ${errText(e)}`);
388
+ await this.status("idle", null);
389
+ return null;
390
+ }
391
+ }
392
+ /** One prompt turn. Resolves when the agent answers `session/prompt` or the host stops. */
393
+ async prompt(text) {
394
+ const conn = this.conn;
395
+ const sid = this.acpSessionId;
396
+ if (!conn || !sid) return;
397
+ this.turnCtl = new AbortController();
398
+ this.failedText = void 0;
399
+ this.denials = [];
400
+ this.turns.add("user", text);
401
+ await this.status("busy", null);
402
+ const turn = conn.agent.request(methods.agent.session.prompt, {
403
+ sessionId: sid,
404
+ prompt: [{
405
+ type: "text",
406
+ text
407
+ }]
408
+ });
409
+ try {
410
+ const res = await this.untilStopped(turn);
411
+ this.turns.flush();
412
+ if (res.stopReason !== "end_turn") this.turns.add("system", `Turn ended: ${res.stopReason}.`);
413
+ } catch (e) {
414
+ this.turns.flush();
415
+ if (!this.stopping) {
416
+ const reason = requestReason(e);
417
+ this.turns.add("system", `The prompt failed: ${reason}`);
418
+ this.log(`session/prompt failed: ${reason}`);
419
+ await this.promptFailed(reason);
420
+ return;
421
+ }
422
+ await conn.agent.notify(methods.agent.session.cancel, { sessionId: sid }).catch(() => void 0);
423
+ const grace = this.deps.stopGraceMs ?? 5e3;
424
+ await Promise.race([turn.then((r) => this.turns.add("system", `Turn ended: ${r.stopReason}.`), () => void 0), new Promise((r) => setTimeout(r, grace).unref())]);
425
+ }
426
+ }
427
+ /**
428
+ * Idle: wait until the daemon hands this session messages through `turn.wake`, then return the
429
+ * prompt for them. It asks on every `message.received` or `session.updated` event for this
430
+ * session and every `wakePollMs`. Returns null when the host is stopping.
431
+ */
432
+ async waitForWork() {
433
+ const id = this.me;
434
+ const listenerId = randomBytes(12).toString("base64url");
435
+ let dirty = false;
436
+ let poke;
437
+ const off = this.client.onEvent((e) => {
438
+ if (e.event === "message.received" || e.event === "session.updated" && e.data.session.id === id) {
439
+ dirty = true;
440
+ poke?.();
441
+ }
442
+ });
443
+ const pollMs = this.deps.wakePollMs ?? 3e4;
444
+ try {
445
+ await this.client["events.subscribe"]({
446
+ sessionId: id,
447
+ topics: ["message.received", "session.updated"]
448
+ });
449
+ while (!this.stopping) {
450
+ dirty = false;
451
+ const r = await this.client["turn.wake"]({
452
+ sessionId: id,
453
+ listenerId
454
+ });
455
+ if (r.messages.length > 0) return formatContinuation(r.messages, r.orchestrator, r.remaining);
456
+ if (r.superseded) {
457
+ this.log("turn.wake: superseded; listening again");
458
+ return null;
459
+ }
460
+ if (dirty) continue;
461
+ await new Promise((resolve) => {
462
+ const done = () => {
463
+ clearTimeout(t);
464
+ this.stopCtl.signal.removeEventListener("abort", done);
465
+ poke = void 0;
466
+ resolve();
467
+ };
468
+ const t = setTimeout(done, pollMs);
469
+ poke = done;
470
+ this.stopCtl.signal.addEventListener("abort", done);
471
+ });
472
+ }
473
+ return null;
474
+ } catch (e) {
475
+ if (this.stopping) return null;
476
+ if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
477
+ this.stop({
478
+ kind: "session-gone",
479
+ detail: errText(e)
480
+ });
481
+ return null;
482
+ }
483
+ this.log(`waiting for work failed: ${errText(e)}`);
484
+ await new Promise((r) => setTimeout(r, Math.min(pollMs, 5e3)).unref());
485
+ return null;
486
+ } finally {
487
+ off();
488
+ }
489
+ }
490
+ onUpdate(n) {
491
+ if (n.sessionId !== this.acpSessionId) return;
492
+ const doing = this.turns.update(n.update);
493
+ if (doing !== void 0 && doing !== this.lastStatus) {
494
+ this.lastStatus = doing;
495
+ this.status(void 0, doing);
496
+ }
497
+ }
498
+ async onPermission(p) {
499
+ if (this.turnCtl.signal.aborted) return { outcome: { outcome: "cancelled" } };
500
+ const known = this.turns.tools.get(p.toolCall.toolCallId) ?? {};
501
+ const title = p.toolCall.title ?? known.title;
502
+ const kind = p.toolCall.kind ?? known.kind;
503
+ const ask = {
504
+ toolCallId: p.toolCall.toolCallId,
505
+ ...title ? { title } : {},
506
+ ...kind ? { kind } : {},
507
+ options: p.options
508
+ };
509
+ const signal = this.turnCtl.signal;
510
+ const decision = await Promise.race([this.policy.decide(ask, signal), new Promise((r) => signal.addEventListener("abort", () => r(null), { once: true }))]);
511
+ if (decision === null) return { outcome: { outcome: "cancelled" } };
512
+ this.log(`permission: ${decision.reason}`);
513
+ this.turns.add("system", `Permission ${decision.allowed ? "granted" : "denied"}: ${title ?? kind ?? "tool call"}.`);
514
+ if (!decision.allowed) this.denials.push(`${title ?? "a tool call"} (${kind ?? "other"})`);
515
+ return { outcome: decision.outcome };
516
+ }
517
+ get me() {
518
+ if (!this.sessionId) throw new Error("The session is not registered yet.");
519
+ return this.sessionId;
520
+ }
521
+ async status(status, statusText) {
522
+ if (!this.sessionId) return;
523
+ const text = typeof statusText === "string" ? statusText.slice(0, 200) : statusText;
524
+ if (status === void 0 && text === void 0) return;
525
+ await this.client["session.setStatus"]({
526
+ sessionId: this.sessionId,
527
+ ...status ? { status } : {},
528
+ ...text !== void 0 ? { statusText: text } : {}
529
+ }).catch(() => void 0);
530
+ }
531
+ async heartbeat() {
532
+ if (!this.sessionId) return;
533
+ try {
534
+ await this.client["session.heartbeat"]({ sessionId: this.sessionId });
535
+ } catch (e) {
536
+ if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) this.stop({
537
+ kind: "session-gone",
538
+ detail: errText(e)
539
+ });
540
+ }
541
+ }
542
+ /**
543
+ * The agent refused a prompt. Not signed in is final: the worker could never run, so it stops,
544
+ * and its spawner is told why (the stop notice carries the reason). Any other failure keeps the
545
+ * worker running, shows in its status line, and goes to the spawner once per reason.
546
+ */
547
+ async promptFailed(reason) {
548
+ if (/authentication required|not (logged|signed) in|unauthenticated/i.test(reason)) {
549
+ const detail = `${reason}. Sign in to ${this.spec.cli} on its own, then spawn it again`;
550
+ await this.status("idle", `Failed: ${detail}`);
551
+ this.stop({
552
+ kind: "failed",
553
+ detail
554
+ });
555
+ return;
556
+ }
557
+ this.failedText = `Last prompt failed: ${reason}`;
558
+ await this.status("idle", this.failedText);
559
+ if (reason === this.lastPromptFailure) return;
560
+ this.lastPromptFailure = reason;
561
+ await this.tell(`[conveno] Worker ${this.spec.name} (${this.spec.cli}, over ACP) could not run a prompt: ${reason}. It keeps running and takes the next message.`);
562
+ }
563
+ /** Tell the spawner which tool calls were denied in the turn that just ended. */
564
+ async reportDenials() {
565
+ if (this.denials.length === 0 || !this.spec.spawnedBy) return;
566
+ const list = this.denials.slice(0, 5).map((d) => `- ${d}`);
567
+ if (this.denials.length > 5) list.push(`- and ${this.denials.length - 5} more`);
568
+ this.denials = [];
569
+ await this.tell([
570
+ `[conveno] Worker ${this.spec.name} (${this.spec.cli}, over ACP) was denied these tool calls in its last turn, because nobody watches it and its spawn did not allow them:`,
571
+ ...list,
572
+ "The owner can allow kinds of tool calls with: conveno spawn --acp --allow <kinds>. You may allow read, search and think with spawn_session's allow."
573
+ ].join("\n"));
574
+ }
575
+ /** Send a text message from this session to its spawner. Never throws. */
576
+ async tell(text) {
577
+ const to = this.spec.spawnedBy;
578
+ if (!to || !this.sessionId) return;
579
+ await this.client["message.send"]({
580
+ sessionId: this.sessionId,
581
+ to,
582
+ kind: "text",
583
+ body: { text }
584
+ }).catch((e) => {
585
+ this.log(`could not message the spawner: ${errText(e)}`);
586
+ });
587
+ }
588
+ every(ms, fn) {
589
+ const t = setInterval(() => void fn(), ms);
590
+ t.unref();
591
+ this.timers.push(t);
592
+ }
593
+ /** `p`, or a rejection as soon as the host is asked to stop. */
594
+ untilStopped(p) {
595
+ const signal = this.stopCtl.signal;
596
+ if (signal.aborted) return Promise.reject(/* @__PURE__ */ new Error("stopping"));
597
+ return new Promise((resolve, reject) => {
598
+ const onAbort = () => reject(/* @__PURE__ */ new Error("stopping"));
599
+ signal.addEventListener("abort", onAbort, { once: true });
600
+ p.then((v) => {
601
+ signal.removeEventListener("abort", onAbort);
602
+ resolve(v);
603
+ }, (e) => {
604
+ signal.removeEventListener("abort", onAbort);
605
+ reject(e);
606
+ });
607
+ });
608
+ }
609
+ async teardown() {
610
+ for (const t of this.timers) clearInterval(t);
611
+ const reason = this.stopReason ?? {
612
+ kind: "failed",
613
+ detail: "unknown"
614
+ };
615
+ await this.turns.settle();
616
+ const agent = this.agent;
617
+ if (agent) {
618
+ this.conn?.close();
619
+ agent.stdin.end();
620
+ const grace = this.deps.stopGraceMs ?? 5e3;
621
+ const exited = await Promise.race([agent.exited.then(() => true), new Promise((r) => setTimeout(() => r(false), grace).unref())]);
622
+ agent.killTree();
623
+ if (!exited) this.log(`killed ${this.spec.file} (pid ${agent.pid}) after ${grace} ms`);
624
+ }
625
+ if (this.sessionId) {
626
+ const why = describeStop(reason);
627
+ if (reason.kind !== "session-gone") await this.tell(`[conveno] Worker ${this.spec.name} (${this.spec.cli}, over ACP) stopped: ${why}. Its session is now offline.`);
628
+ await this.client["session.unregister"]({ sessionId: this.sessionId }).catch(() => void 0);
629
+ }
630
+ rmSync(this.spec.record, { force: true });
631
+ rmSync(stopRequestPath(this.spec.record), { force: true });
632
+ this.log(`stopped: ${describeStop(reason)}`);
633
+ }
634
+ };
635
+ /**
636
+ * End `pid` and its descendants. POSIX: the agent leads its own process group (it was started
637
+ * detached), so the whole group gets SIGKILL. Windows has no process groups; `taskkill /T` ends the
638
+ * tree by parent pid. Never throws: the process may be gone already.
639
+ */
640
+ function killProcessTree(pid, platform = process.platform) {
641
+ if (platform === "win32") {
642
+ spawnSync("taskkill", [
643
+ "/PID",
644
+ String(pid),
645
+ "/T",
646
+ "/F"
647
+ ], {
648
+ stdio: "ignore",
649
+ windowsHide: true
650
+ });
651
+ return;
652
+ }
653
+ try {
654
+ process.kill(-pid, "SIGKILL");
655
+ } catch {
656
+ try {
657
+ process.kill(pid, "SIGKILL");
658
+ } catch {}
659
+ }
660
+ }
661
+ /**
662
+ * Start a CLI's ACP server with piped stdio. On POSIX it gets its own process group, so stopping
663
+ * it ends the tools it started too. Whatever happens to the host, the server's stdin closes when
664
+ * the host exits, and an ACP server on stdio exits when its input closes (OpenCode, Copilot and
665
+ * the SDK-based adapters document this), so a crashed host leaves no worker behind.
666
+ */
667
+ function startAgentProcess(opts) {
668
+ const platform = opts.platform ?? process.platform;
669
+ return new Promise((resolve, reject) => {
670
+ const child = spawn(opts.file, [...opts.args], {
671
+ cwd: opts.cwd,
672
+ stdio: [
673
+ "pipe",
674
+ "pipe",
675
+ "pipe"
676
+ ],
677
+ detached: platform !== "win32",
678
+ windowsHide: true,
679
+ env: opts.env ?? process.env,
680
+ ...opts.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
681
+ });
682
+ const exited = new Promise((r) => {
683
+ child.once("exit", (code, signal) => r({
684
+ code,
685
+ signal
686
+ }));
687
+ });
688
+ child.stderr.pipe(opts.stderr ?? process.stderr, { end: false });
689
+ child.stdin.on("error", () => void 0);
690
+ child.once("error", (e) => reject(/* @__PURE__ */ new Error(`Could not start ${opts.file}: ${e.message}`)));
691
+ child.once("spawn", () => {
692
+ const pid = child.pid;
693
+ if (pid === void 0) {
694
+ reject(/* @__PURE__ */ new Error(`${opts.file} has no pid.`));
695
+ return;
696
+ }
697
+ resolve({
698
+ pid,
699
+ stdin: child.stdin,
700
+ stdout: child.stdout,
701
+ exited,
702
+ killTree: () => killProcessTree(pid, platform)
703
+ });
704
+ });
705
+ });
706
+ }
707
+ /**
708
+ * `conveno acp-host <launch file>`: read and delete the launch file, connect to the daemon and
709
+ * drive the worker until it stops. Returns the exit code.
710
+ */
711
+ async function runAcpHostFromFile(path, opts = {}) {
712
+ const spec = takeAcpLaunchFile(path);
713
+ const client = await connect({
714
+ kind: "adapter",
715
+ autoStart: true,
716
+ ...opts.daemonEntry ? { daemonEntry: opts.daemonEntry } : {},
717
+ ...opts.dataDir ? { dataDir: opts.dataDir } : {},
718
+ ...opts.socketPath ? { socketPath: opts.socketPath } : {}
719
+ });
720
+ try {
721
+ return await runAcpHost(spec, {
722
+ client,
723
+ startAgent: (s) => startAgentProcess({
724
+ file: s.file,
725
+ args: s.args,
726
+ cwd: s.cwd,
727
+ ...s.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
728
+ })
729
+ });
730
+ } finally {
731
+ await client.close().catch(() => void 0);
732
+ }
733
+ }
734
+ // src/acp.ts
735
+ /** How long `conveno stop` waits for a worker to end by itself before it ends the process tree. */
736
+ const STOP_WAIT_MS = 1e4;
737
+ /** `conveno acp-host <launch file>`: what `conveno spawn --acp` runs in the background. Not for people. */
738
+ async function runAcpHostCmd(ctx, argv) {
739
+ const [file] = argv;
740
+ if (!file) return fail(ctx, {
741
+ what: "conveno acp-host needs a launch file",
742
+ detail: ["It is started by conveno spawn --acp."],
743
+ fix: `Run ${cmd(ctx.theme, "conveno spawn <cli> --acp")} instead.`,
744
+ exit: 2,
745
+ ref: "e_usage"
746
+ });
747
+ try {
748
+ return await runAcpHostFromFile(file, {
749
+ dataDir: ctx.dataDir,
750
+ ...ctx.socketPath ? { socketPath: ctx.socketPath } : {},
751
+ ...ctx.daemonEntry ? { daemonEntry: ctx.daemonEntry } : {}
752
+ });
753
+ } catch (e) {
754
+ return fail(ctx, {
755
+ what: "The ACP host could not start",
756
+ detail: [e instanceof Error ? e.message : String(e)],
757
+ fix: `Run ${cmd(ctx.theme, "conveno spawn <cli> --acp")} again.`,
758
+ exit: 1,
759
+ ref: "e_spawn"
760
+ });
761
+ }
762
+ }
763
+ function findWorker(ctx, name, command) {
764
+ if (!name) return fail(ctx, {
765
+ what: `conveno ${command} needs a worker name`,
766
+ fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
767
+ exit: 2,
768
+ ref: "e_usage"
769
+ });
770
+ const rec = /^[a-z0-9][a-z0-9._@-]{0,63}$/.test(name) ? readSpawnRecord(spawnRecordPath(ctx.dataDir, name)) : void 0;
771
+ if (!rec) return fail(ctx, {
772
+ what: `No running worker named "${name}"`,
773
+ detail: ["Only sessions started by conveno spawn or spawn_session on this machine are workers."],
774
+ fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
775
+ exit: 1,
776
+ ref: "e_not_found"
777
+ });
778
+ return rec;
779
+ }
780
+ /**
781
+ * `conveno stop <worker>`. An ACP worker gets a stop request: its host sends `session/cancel` for
782
+ * a running turn, ends the agent, reports to the spawner and takes the session offline. A headless
783
+ * one-shot run is ended. A worker in a terminal is the user's to close.
784
+ */
785
+ async function runStop(ctx, argv) {
786
+ const spec = COMMANDS.find((c) => c.name === "stop");
787
+ if (!spec) return 2;
788
+ const parsed = parseFlags(ctx, spec, argv);
789
+ if (typeof parsed === "number") return parsed;
790
+ const [name] = parsed.positionals;
791
+ const rec = findWorker(ctx, name, "stop");
792
+ if (typeof rec === "number") return rec;
793
+ const t = ctx.theme;
794
+ if (!rec.headless) return fail(ctx, {
795
+ what: `${rec.name} runs in a terminal`,
796
+ detail: ["Conveno does not close a terminal you can see."],
797
+ fix: "Exit the CLI in that terminal.",
798
+ exit: 1,
799
+ ref: "e_spawn"
800
+ });
801
+ const alive = () => rec.pid !== void 0 && ctx.isAlive(rec.pid);
802
+ if (rec.acp) {
803
+ writeFileSync(stopRequestPath(spawnRecordPath(ctx.dataDir, rec.name)), "", { mode: 384 });
804
+ const end = Date.now() + STOP_WAIT_MS;
805
+ while (alive() && Date.now() < end) await new Promise((r) => setTimeout(r, 100));
806
+ }
807
+ if (alive() && rec.pid !== void 0) killProcessTree(rec.pid, ctx.platform);
808
+ if (rec.agentPid !== void 0 && ctx.isAlive(rec.agentPid)) killProcessTree(rec.agentPid, ctx.platform);
809
+ ctx.out(`${t.status("ok")} ${t.bold(`Stopped ${rec.name}`)}\n`);
810
+ return 0;
811
+ }
812
+ const ROLE_LABEL = {
813
+ user: "prompt",
814
+ assistant: "agent",
815
+ tool: "tool",
816
+ system: "conveno"
817
+ };
818
+ /**
819
+ * `conveno attach <worker>`: print the recent turns of an ACP worker and follow new ones until it
820
+ * stops or Ctrl+C. Read-only: nothing typed here reaches the worker; message it with send instead.
821
+ */
822
+ async function runAttach(ctx, argv) {
823
+ const spec = COMMANDS.find((c) => c.name === "attach");
824
+ if (!spec) return 2;
825
+ const parsed = parseFlags(ctx, spec, argv);
826
+ if (typeof parsed === "number") return parsed;
827
+ const t = ctx.theme;
828
+ const [name] = parsed.positionals;
829
+ const rec = findWorker(ctx, name, "attach");
830
+ if (typeof rec === "number") return rec;
831
+ if (!rec.acp) return fail(ctx, {
832
+ what: `${rec.name} is not driven over ACP`,
833
+ detail: ["attach follows workers started with conveno spawn --acp."],
834
+ fix: "Watch it in its terminal, or read its log in the data folder.",
835
+ exit: 1,
836
+ ref: "e_spawn"
837
+ });
838
+ const linesFlag = parsed.values.lines;
839
+ const lines = typeof linesFlag === "string" ? Number(linesFlag) : 20;
840
+ if (!Number.isInteger(lines) || lines < 0) return fail(ctx, {
841
+ what: "--lines takes a whole number",
842
+ fix: `Run ${cmd(t, "conveno attach <worker> --lines 50")}.`,
843
+ exit: 2,
844
+ ref: "e_usage"
845
+ });
846
+ const path = acpTurnsPath(ctx.dataDir, rec.name);
847
+ const read = () => existsSync(path) ? parseTurns(readFileSync(path, "utf8")) : [];
848
+ const show = (e) => {
849
+ const head = t.paint("quiet", `${localStamp(e.at)} ${ROLE_LABEL[e.role]}`);
850
+ ctx.out(`${head}\n${e.text}\n\n`);
851
+ };
852
+ let last = 0;
853
+ const first = read();
854
+ for (const e of first.slice(-lines)) show(e);
855
+ last = first.at(-1)?.seq ?? 0;
856
+ if (parsed.values["no-follow"] === true) return 0;
857
+ ctx.err(t.paint("quiet", `Following ${rec.name}. Read-only; Ctrl+C to leave.\n`));
858
+ const record = spawnRecordPath(ctx.dataDir, rec.name);
859
+ for (;;) {
860
+ await new Promise((r) => setTimeout(r, 300));
861
+ for (const e of read()) if (e.seq > last) {
862
+ show(e);
863
+ last = e.seq;
864
+ }
865
+ if (!existsSync(record)) {
866
+ ctx.err(t.paint("quiet", `${rec.name} stopped.\n`));
867
+ return 0;
868
+ }
869
+ }
870
+ }
871
+ export { runAcpHostCmd, runAttach, runStop };