@conveno/cli 0.2.0-rc.9 → 0.2.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.
Files changed (30) hide show
  1. package/README.md +3 -5
  2. package/dist/{acp-BVk6rmXR.js → acp-BUddItzP.js} +39 -7
  3. package/dist/{agy-relay-D8eZcLuc.js → agy-relay-BZ3d_-FS.js} +4 -2
  4. package/dist/{args-B3Cj2Ie4.js → args-CtyKPZuN.js} +29 -8
  5. package/dist/bin.js +16 -2
  6. package/dist/daemon.js +4 -3139
  7. package/dist/{daemonError-C05GqdhQ.js → daemonError-CDgEtvy7.js} +1 -1
  8. package/dist/dist-BNhTPp5p.js +4509 -0
  9. package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
  10. package/dist/{dist-DaIpdMke.js → dist-CFsDqevs.js} +51 -9
  11. package/dist/dist-CNdqmI3E.js +1065 -0
  12. package/dist/{dist-STNJjbNH.js → dist-CSSvrcKr.js} +1516 -599
  13. package/dist/{dist-BjdBeCHy.js → dist-D6Xoip5W.js} +63 -17
  14. package/dist/{dist-D_O_JLLq.js → dist-DAVtixeC.js} +19 -5
  15. package/dist/{dist-MK-cK1JY.js → dist-DTMnNySx.js} +39 -19
  16. package/dist/{hook-CDF1A8AY.js → hook-BA-tI6Oc.js} +101 -7
  17. package/dist/hook-entry-BwzBtAnd.js +1346 -0
  18. package/dist/hook-entry-Cgt5ZH1s.js +1 -0
  19. package/dist/{main-Kv31Qxro.js → main-kKnLA7Hj.js} +58 -21
  20. package/dist/{pick-DLp6w_-z.js → pick-BsMvXuDo.js} +1 -1
  21. package/dist/run-PQBzaHv1.js +8193 -0
  22. package/dist/{runtime-xjPzIGmp.js → runtime-0FMqklYn.js} +171 -119
  23. package/dist/{uninstall-8AHErPRN.js → uninstall-DcxkIDpk.js} +356 -56
  24. package/dist/{watch-D0KIPowJ.js → watch-BIepRTXJ.js} +29 -7
  25. package/package.json +14 -15
  26. package/dist/dist-CVdpCNJo.js +0 -793
  27. package/dist/dist-DzpERiRx.js +0 -624
  28. package/dist/hook-entry-BTJK7aO0.js +0 -2500
  29. package/dist/hook-entry-D6zup0QV.js +0 -1
  30. package/dist/run-BPtFUGtu.js +0 -5609
@@ -1,624 +0,0 @@
1
- import { n as connect } from "./dist-D_O_JLLq.js";
2
- import { Jt as takeAcpLaunchFile, Q as isAllowed, en as updateSpawnRecord, ft as parseAllowPatterns, gn as RpcErrorCode, i as DEFAULT_ALLOW_RULES, on as CliKind, q as formatContinuation, r as ConvenoError, yn as SessionId } from "./dist-STNJjbNH.js";
3
- import { randomBytes } from "node:crypto";
4
- import { existsSync, rmSync } from "node:fs";
5
- import { Readable, Writable } from "node:stream";
6
- import { PROTOCOL_VERSION, client, methods, ndJsonStream } from "@agentclientprotocol/sdk";
7
- import { spawn, spawnSync } from "node:child_process";
8
- // ../acp/dist/index.js
9
- /**
10
- * Pick the option to answer with. Allowing uses `allow_once` only: `allow_always` would change the
11
- * CLI's own saved permissions, which is the user's call. Denying uses `reject_once`, and when the
12
- * agent offers none, `cancelled`, so no `reject_always` rule is saved either.
13
- */
14
- function answer(ask, allow) {
15
- const want = allow ? "allow_once" : "reject_once";
16
- const option = ask.options.find((o) => o.kind === want);
17
- return option ? {
18
- outcome: "selected",
19
- optionId: option.optionId
20
- } : { outcome: "cancelled" };
21
- }
22
- var AllowListPolicy = class {
23
- rules;
24
- constructor(rules) {
25
- this.rules = rules;
26
- }
27
- async decide(ask, _signal) {
28
- const what = `${ask.title ?? "a tool call"} (${ask.kind ?? "other"})`;
29
- if (isAllowed(this.rules, {
30
- kind: ask.kind,
31
- title: ask.title
32
- })) {
33
- const outcome = answer(ask, true);
34
- if (outcome.outcome === "selected") return {
35
- allowed: true,
36
- outcome,
37
- reason: `allowed ${what} by the allow list`
38
- };
39
- return {
40
- allowed: false,
41
- outcome: answer(ask, false),
42
- reason: `denied ${what}: allowed by the allow list, but the agent offered no allow-once option`
43
- };
44
- }
45
- return {
46
- allowed: false,
47
- outcome: answer(ask, false),
48
- reason: `denied ${what}: the allow list does not cover it`
49
- };
50
- }
51
- };
52
- /** Calls remembered at most; the oldest are dropped. */
53
- const TOOLS_MAX = 1e3;
54
- var ToolTracker = class {
55
- /** Tool calls seen in this session: their latest title and kind. */
56
- tools = /* @__PURE__ */ new Map();
57
- /** Feed one `session/update`. Returns a status line when the agent starts a tool call. */
58
- update(u) {
59
- if (u.sessionUpdate !== "tool_call" && u.sessionUpdate !== "tool_call_update") return;
60
- const t = u;
61
- const next = {
62
- ...this.tools.get(t.toolCallId) ?? {},
63
- ...t.title ? { title: t.title } : {},
64
- ...t.kind ? { kind: t.kind } : {}
65
- };
66
- this.tools.set(t.toolCallId, next);
67
- if (this.tools.size > TOOLS_MAX) {
68
- const first = this.tools.keys().next().value;
69
- if (first !== void 0) this.tools.delete(first);
70
- }
71
- return u.sessionUpdate === "tool_call" ? next.title ?? next.kind ?? "tool" : void 0;
72
- }
73
- };
74
- const HOST_VERSION = "0.2.0-rc.9";
75
- /** A stop request file: `conveno stop` writes it next to the spawn record. */
76
- const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
77
- function withTimeout(p, ms, what) {
78
- return new Promise((resolve, reject) => {
79
- const t = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} did not answer within ${Math.round(ms / 1e3)} s.`)), ms);
80
- p.then((v) => {
81
- clearTimeout(t);
82
- resolve(v);
83
- }, (e) => {
84
- clearTimeout(t);
85
- reject(e);
86
- });
87
- });
88
- }
89
- const errText = (e) => e instanceof Error ? e.message : String(e);
90
- /** A JSON-RPC error's own words: an agent that throws gets "Internal error" with the text in `data.details`. */
91
- const requestReason = (e) => {
92
- const details = e?.data?.details;
93
- return typeof details === "string" && details.trim() !== "" ? details.trim() : errText(e);
94
- };
95
- const describeStop = (r) => {
96
- switch (r.kind) {
97
- case "requested": return `stopped by ${r.by}`;
98
- case "agent-exit": return `its ACP server exited (${r.signal ? `signal ${r.signal}` : `code ${r.code ?? "none"}`})`;
99
- case "session-gone": return `its Conveno session ended (${r.detail})`;
100
- case "failed": return `it failed: ${r.detail}`;
101
- }
102
- };
103
- /**
104
- * Drive one worker until it stops. Returns the process exit code: 0 for a requested stop, 1 for
105
- * anything else.
106
- */
107
- async function runAcpHost(spec, deps) {
108
- return new AcpHost(spec, deps).run();
109
- }
110
- var AcpHost = class {
111
- spec;
112
- deps;
113
- client;
114
- log;
115
- policy;
116
- tools = new ToolTracker();
117
- sessionId;
118
- acpSessionId;
119
- conn;
120
- agent;
121
- stopReason;
122
- stopCtl = new AbortController();
123
- /** Aborted to cancel the current prompt turn; pending permission policies see it too. */
124
- turnCtl = new AbortController();
125
- lastPromptFailure;
126
- /** The status line after a failed prompt, kept until the next prompt starts. */
127
- failedText;
128
- denials = [];
129
- lastStatus;
130
- timers = [];
131
- constructor(spec, deps) {
132
- this.spec = spec;
133
- this.deps = deps;
134
- this.client = deps.client;
135
- this.log = deps.log ?? ((line) => process.stderr.write(`[conveno acp-host] ${line}\n`));
136
- const rules = parseAllowPatterns(spec.allow);
137
- const narrowed = rules.ok && rules.rules.length > 0 ? rules.rules : DEFAULT_ALLOW_RULES;
138
- this.policy = deps.policy ?? new AllowListPolicy(narrowed);
139
- }
140
- /** Ask the host to stop. The first reason wins. */
141
- stop(reason) {
142
- if (this.stopReason) return;
143
- this.stopReason = reason;
144
- this.log(`stopping: ${describeStop(reason)}`);
145
- this.stopCtl.abort();
146
- this.turnCtl.abort();
147
- }
148
- get stopping() {
149
- return this.stopReason !== void 0;
150
- }
151
- async run() {
152
- const onSignal = () => this.stop({
153
- kind: "requested",
154
- by: "a signal"
155
- });
156
- process.once("SIGTERM", onSignal);
157
- process.once("SIGINT", onSignal);
158
- try {
159
- await this.setup();
160
- await this.loop();
161
- } catch (e) {
162
- if (!this.stopping) this.stop({
163
- kind: "failed",
164
- detail: errText(e)
165
- });
166
- } finally {
167
- process.off("SIGTERM", onSignal);
168
- process.off("SIGINT", onSignal);
169
- await this.teardown();
170
- }
171
- return this.stopReason?.kind === "requested" ? 0 : 1;
172
- }
173
- async setup() {
174
- const { spec } = this;
175
- const timeout = spec.setupTimeoutMs ?? this.deps.setupTimeoutMs ?? 12e4;
176
- this.agent = await this.deps.startAgent(spec);
177
- const agent = this.agent;
178
- this.log(`started ${spec.file} (pid ${agent.pid}) for ${spec.name}`);
179
- agent.exited.then(({ code, signal }) => {
180
- this.stop({
181
- kind: "agent-exit",
182
- code,
183
- signal
184
- });
185
- });
186
- updateSpawnRecord(spec.record, {
187
- pid: process.pid,
188
- agentPid: agent.pid
189
- });
190
- this.every(this.deps.stopPollMs ?? 500, () => {
191
- const path = stopRequestPath(spec.record);
192
- if (existsSync(path)) {
193
- rmSync(path, { force: true });
194
- this.stop({
195
- kind: "requested",
196
- by: "conveno stop"
197
- });
198
- }
199
- });
200
- const app = client({ name: "conveno" }).onNotification(methods.client.session.update, ({ params }) => this.onUpdate(params)).onRequest(methods.client.session.requestPermission, ({ params }) => this.onPermission(params));
201
- this.conn = app.connect(ndJsonStream(Writable.toWeb(agent.stdin), Readable.toWeb(agent.stdout)));
202
- const conn = this.conn;
203
- const init = await this.untilStopped(withTimeout(conn.agent.request(methods.agent.initialize, {
204
- protocolVersion: PROTOCOL_VERSION,
205
- clientCapabilities: {
206
- fs: {
207
- readTextFile: false,
208
- writeTextFile: false
209
- },
210
- terminal: false
211
- },
212
- clientInfo: {
213
- name: "conveno",
214
- version: HOST_VERSION
215
- }
216
- }), timeout, "initialize"));
217
- const agentVersion = init.agentInfo?.version?.trim().slice(0, 64);
218
- this.log(`initialize: protocol ${init.protocolVersion}, agent ${init.agentInfo?.name ?? "unknown"} ${agentVersion ?? ""}`);
219
- const created = await this.untilStopped(withTimeout(conn.agent.request(methods.agent.session.new, {
220
- cwd: spec.cwd,
221
- mcpServers: spec.mcp ? [{
222
- name: "conveno",
223
- command: spec.mcp.command,
224
- args: spec.mcp.args,
225
- env: []
226
- }] : []
227
- }), timeout, "session/new"));
228
- this.acpSessionId = created.sessionId;
229
- this.log(`session/new: ${created.sessionId}`);
230
- const mode = spec.fullAccessMode;
231
- if (mode && created.modes?.availableModes.some((m) => m.id === mode)) await this.untilStopped(withTimeout(conn.agent.request(methods.agent.session.setMode, {
232
- sessionId: created.sessionId,
233
- modeId: mode
234
- }), timeout, "session/set_mode")).then(() => this.log(`mode: ${mode}`), (e) => this.log(`could not set mode ${mode}: ${errText(e)}`));
235
- const spawnedBy = SessionId.safeParse(spec.spawnedBy);
236
- const { session } = await this.client["session.register"]({
237
- name: spec.name,
238
- cli: CliKind.parse(spec.cli),
239
- cwd: spec.cwd,
240
- pid: process.pid,
241
- hostPid: process.pid,
242
- spawned: true,
243
- acp: true,
244
- ...spawnedBy.success ? { spawnedBy: spawnedBy.data } : {},
245
- ...agentVersion ? { cliVersion: agentVersion } : {}
246
- });
247
- this.sessionId = session.id;
248
- updateSpawnRecord(spec.record, {
249
- pid: process.pid,
250
- sessionId: session.id,
251
- agentPid: agent.pid
252
- });
253
- this.log(`registered as ${session.name} (${session.id})`);
254
- this.every(this.deps.heartbeatMs ?? 15e3, () => this.heartbeat());
255
- }
256
- async loop() {
257
- let next = this.spec.task ?? null;
258
- if (next === null) await this.status("idle", null);
259
- while (!this.stopping) if (next !== null) {
260
- await this.prompt(next);
261
- if (this.stopping) break;
262
- await this.reportDenials();
263
- next = await this.endTurn();
264
- } else next = await this.waitForWork();
265
- }
266
- /** Report the end of a turn. Returns the prompt to continue with, or null to wait for work. */
267
- async endTurn() {
268
- try {
269
- const r = await this.client["turn.end"]({
270
- sessionId: this.me,
271
- allowContinue: true
272
- });
273
- const next = formatContinuation(r.messages, r.orchestrator, r.remaining) || null;
274
- if (next === null) await this.status(void 0, this.failedText ?? null);
275
- return next;
276
- } catch (e) {
277
- if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
278
- this.stop({
279
- kind: "session-gone",
280
- detail: errText(e)
281
- });
282
- return null;
283
- }
284
- this.log(`turn.end failed: ${errText(e)}`);
285
- await this.status("idle", null);
286
- return null;
287
- }
288
- }
289
- /** One prompt turn. Resolves when the agent answers `session/prompt` or the host stops. */
290
- async prompt(text) {
291
- const conn = this.conn;
292
- const sid = this.acpSessionId;
293
- if (!conn || !sid) return;
294
- this.turnCtl = new AbortController();
295
- this.failedText = void 0;
296
- this.denials = [];
297
- await this.status("busy", null);
298
- const turn = conn.agent.request(methods.agent.session.prompt, {
299
- sessionId: sid,
300
- prompt: [{
301
- type: "text",
302
- text
303
- }]
304
- });
305
- try {
306
- await this.untilStopped(turn);
307
- } catch (e) {
308
- if (!this.stopping) {
309
- const reason = requestReason(e);
310
- this.log(`session/prompt failed: ${reason}`);
311
- await this.promptFailed(reason);
312
- return;
313
- }
314
- await conn.agent.notify(methods.agent.session.cancel, { sessionId: sid }).catch(() => void 0);
315
- const grace = this.deps.stopGraceMs ?? 5e3;
316
- await Promise.race([turn.then(() => void 0, () => void 0), new Promise((r) => setTimeout(r, grace).unref())]);
317
- }
318
- }
319
- /**
320
- * Idle: wait until the daemon hands this session messages through `turn.wake`, then return the
321
- * prompt for them. It asks on every `message.received` or `session.updated` event for this
322
- * session and every `wakePollMs`. Returns null when the host is stopping.
323
- */
324
- async waitForWork() {
325
- const id = this.me;
326
- const listenerId = randomBytes(12).toString("base64url");
327
- let dirty = false;
328
- let poke;
329
- const off = this.client.onEvent((e) => {
330
- if (e.event === "message.received" || e.event === "session.updated" && e.data.session.id === id) {
331
- dirty = true;
332
- poke?.();
333
- }
334
- });
335
- const pollMs = this.deps.wakePollMs ?? 3e4;
336
- try {
337
- await this.client["events.subscribe"]({
338
- sessionId: id,
339
- topics: ["message.received", "session.updated"]
340
- });
341
- while (!this.stopping) {
342
- dirty = false;
343
- const r = await this.client["turn.wake"]({
344
- sessionId: id,
345
- listenerId
346
- });
347
- if (r.messages.length > 0) return formatContinuation(r.messages, r.orchestrator, r.remaining);
348
- if (r.superseded) {
349
- this.log("turn.wake: superseded; listening again");
350
- return null;
351
- }
352
- if (dirty) continue;
353
- await new Promise((resolve) => {
354
- const done = () => {
355
- clearTimeout(t);
356
- this.stopCtl.signal.removeEventListener("abort", done);
357
- poke = void 0;
358
- resolve();
359
- };
360
- const t = setTimeout(done, pollMs);
361
- poke = done;
362
- this.stopCtl.signal.addEventListener("abort", done);
363
- });
364
- }
365
- return null;
366
- } catch (e) {
367
- if (this.stopping) return null;
368
- if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
369
- this.stop({
370
- kind: "session-gone",
371
- detail: errText(e)
372
- });
373
- return null;
374
- }
375
- this.log(`waiting for work failed: ${errText(e)}`);
376
- await new Promise((r) => setTimeout(r, Math.min(pollMs, 5e3)).unref());
377
- return null;
378
- } finally {
379
- off();
380
- }
381
- }
382
- onUpdate(n) {
383
- if (n.sessionId !== this.acpSessionId) return;
384
- const doing = this.tools.update(n.update);
385
- if (doing !== void 0 && doing !== this.lastStatus) {
386
- this.lastStatus = doing;
387
- this.status(void 0, doing);
388
- }
389
- }
390
- async onPermission(p) {
391
- if (this.turnCtl.signal.aborted) return { outcome: { outcome: "cancelled" } };
392
- const known = this.tools.tools.get(p.toolCall.toolCallId) ?? {};
393
- const title = p.toolCall.title ?? known.title;
394
- const kind = p.toolCall.kind ?? known.kind;
395
- const ask = {
396
- toolCallId: p.toolCall.toolCallId,
397
- ...title ? { title } : {},
398
- ...kind ? { kind } : {},
399
- options: p.options
400
- };
401
- const signal = this.turnCtl.signal;
402
- const decision = await Promise.race([this.policy.decide(ask, signal), new Promise((r) => signal.addEventListener("abort", () => r(null), { once: true }))]);
403
- if (decision === null) return { outcome: { outcome: "cancelled" } };
404
- this.log(`permission: ${decision.reason}`);
405
- if (!decision.allowed) this.denials.push(`${title ?? "a tool call"} (${kind ?? "other"})`);
406
- return { outcome: decision.outcome };
407
- }
408
- get me() {
409
- if (!this.sessionId) throw new Error("The session is not registered yet.");
410
- return this.sessionId;
411
- }
412
- async status(status, statusText) {
413
- if (!this.sessionId) return;
414
- const text = typeof statusText === "string" ? statusText.slice(0, 200) : statusText;
415
- if (status === void 0 && text === void 0) return;
416
- await this.client["session.setStatus"]({
417
- sessionId: this.sessionId,
418
- ...status ? { status } : {},
419
- ...text !== void 0 ? { statusText: text } : {}
420
- }).catch(() => void 0);
421
- }
422
- async heartbeat() {
423
- if (!this.sessionId) return;
424
- try {
425
- await this.client["session.heartbeat"]({ sessionId: this.sessionId });
426
- } catch (e) {
427
- if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) this.stop({
428
- kind: "session-gone",
429
- detail: errText(e)
430
- });
431
- }
432
- }
433
- /**
434
- * The agent refused a prompt. Not signed in is final: the worker could never run, so it stops,
435
- * and its spawner is told why (the stop notice carries the reason). Any other failure keeps the
436
- * worker running, shows in its status line, and goes to the spawner once per reason.
437
- */
438
- async promptFailed(reason) {
439
- if (/authentication required|not (logged|signed) in|unauthenticated/i.test(reason)) {
440
- const detail = `${reason}. Sign in to ${this.spec.cli} on its own, then spawn it again`;
441
- await this.status("idle", `Failed: ${detail}`);
442
- this.stop({
443
- kind: "failed",
444
- detail
445
- });
446
- return;
447
- }
448
- this.failedText = `Last prompt failed: ${reason}`;
449
- await this.status("idle", this.failedText);
450
- if (reason === this.lastPromptFailure) return;
451
- this.lastPromptFailure = reason;
452
- 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.`);
453
- }
454
- /** Tell the spawner which tool calls were denied in the turn that just ended. */
455
- async reportDenials() {
456
- if (this.denials.length === 0 || !this.spec.spawnedBy) return;
457
- const list = this.denials.slice(0, 5).map((d) => `- ${d}`);
458
- if (this.denials.length > 5) list.push(`- and ${this.denials.length - 5} more`);
459
- this.denials = [];
460
- await this.tell([
461
- `[conveno] Worker ${this.spec.name} (${this.spec.cli}, over ACP) was denied these tool calls in its last turn, because its spawn limited it to an allow list:`,
462
- ...list,
463
- "The allow list it was spawned with does not cover them. Spawn it again with a wider allow list, or none for full access."
464
- ].join("\n"));
465
- }
466
- /** Send a text message from this session to its spawner. Never throws. */
467
- async tell(text) {
468
- const to = this.spec.spawnedBy;
469
- if (!to || !this.sessionId) return;
470
- await this.client["message.send"]({
471
- sessionId: this.sessionId,
472
- to,
473
- kind: "text",
474
- body: { text }
475
- }).catch((e) => {
476
- this.log(`could not message the spawner: ${errText(e)}`);
477
- });
478
- }
479
- every(ms, fn) {
480
- const t = setInterval(() => void fn(), ms);
481
- t.unref();
482
- this.timers.push(t);
483
- }
484
- /** `p`, or a rejection as soon as the host is asked to stop. */
485
- untilStopped(p) {
486
- const signal = this.stopCtl.signal;
487
- if (signal.aborted) return Promise.reject(/* @__PURE__ */ new Error("stopping"));
488
- return new Promise((resolve, reject) => {
489
- const onAbort = () => reject(/* @__PURE__ */ new Error("stopping"));
490
- signal.addEventListener("abort", onAbort, { once: true });
491
- p.then((v) => {
492
- signal.removeEventListener("abort", onAbort);
493
- resolve(v);
494
- }, (e) => {
495
- signal.removeEventListener("abort", onAbort);
496
- reject(e);
497
- });
498
- });
499
- }
500
- async teardown() {
501
- for (const t of this.timers) clearInterval(t);
502
- const reason = this.stopReason ?? {
503
- kind: "failed",
504
- detail: "unknown"
505
- };
506
- const agent = this.agent;
507
- if (agent) {
508
- this.conn?.close();
509
- agent.stdin.end();
510
- const grace = this.deps.stopGraceMs ?? 5e3;
511
- const exited = await Promise.race([agent.exited.then(() => true), new Promise((r) => setTimeout(() => r(false), grace).unref())]);
512
- agent.killTree();
513
- if (!exited) this.log(`killed ${this.spec.file} (pid ${agent.pid}) after ${grace} ms`);
514
- }
515
- if (this.sessionId) {
516
- const why = describeStop(reason);
517
- 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.`);
518
- await this.client["session.unregister"]({ sessionId: this.sessionId }).catch(() => void 0);
519
- }
520
- rmSync(this.spec.record, { force: true });
521
- rmSync(stopRequestPath(this.spec.record), { force: true });
522
- this.log(`stopped: ${describeStop(reason)}`);
523
- }
524
- };
525
- /**
526
- * End `pid` and its descendants. POSIX: the agent leads its own process group (it was started
527
- * detached), so the whole group gets SIGKILL. Windows has no process groups; `taskkill /T` ends the
528
- * tree by parent pid. Never throws: the process may be gone already.
529
- */
530
- function killProcessTree(pid, platform = process.platform) {
531
- if (platform === "win32") {
532
- spawnSync("taskkill", [
533
- "/PID",
534
- String(pid),
535
- "/T",
536
- "/F"
537
- ], {
538
- stdio: "ignore",
539
- windowsHide: true
540
- });
541
- return;
542
- }
543
- try {
544
- process.kill(-pid, "SIGKILL");
545
- } catch {
546
- try {
547
- process.kill(pid, "SIGKILL");
548
- } catch {}
549
- }
550
- }
551
- /**
552
- * Start a CLI's ACP server with piped stdio. On POSIX it gets its own process group, so stopping
553
- * it ends the tools it started too. Whatever happens to the host, the server's stdin closes when
554
- * the host exits, and an ACP server on stdio exits when its input closes (OpenCode, Copilot and
555
- * the SDK-based adapters document this), so a crashed host leaves no worker behind.
556
- */
557
- function startAgentProcess(opts) {
558
- const platform = opts.platform ?? process.platform;
559
- return new Promise((resolve, reject) => {
560
- const child = spawn(opts.file, [...opts.args], {
561
- cwd: opts.cwd,
562
- stdio: [
563
- "pipe",
564
- "pipe",
565
- "pipe"
566
- ],
567
- detached: platform !== "win32",
568
- windowsHide: true,
569
- env: opts.env ?? process.env,
570
- ...opts.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
571
- });
572
- const exited = new Promise((r) => {
573
- child.once("exit", (code, signal) => r({
574
- code,
575
- signal
576
- }));
577
- });
578
- child.stderr.pipe(opts.stderr ?? process.stderr, { end: false });
579
- child.stdin.on("error", () => void 0);
580
- child.once("error", (e) => reject(/* @__PURE__ */ new Error(`Could not start ${opts.file}: ${e.message}`)));
581
- child.once("spawn", () => {
582
- const pid = child.pid;
583
- if (pid === void 0) {
584
- reject(/* @__PURE__ */ new Error(`${opts.file} has no pid.`));
585
- return;
586
- }
587
- resolve({
588
- pid,
589
- stdin: child.stdin,
590
- stdout: child.stdout,
591
- exited,
592
- killTree: () => killProcessTree(pid, platform)
593
- });
594
- });
595
- });
596
- }
597
- /**
598
- * `conveno acp-host <launch file>`: read and delete the launch file, connect to the daemon and
599
- * drive the worker until it stops. Returns the exit code.
600
- */
601
- async function runAcpHostFromFile(path, opts = {}) {
602
- const spec = takeAcpLaunchFile(path);
603
- const client = await connect({
604
- kind: "adapter",
605
- autoStart: true,
606
- ...opts.daemonEntry ? { daemonEntry: opts.daemonEntry } : {},
607
- ...opts.dataDir ? { dataDir: opts.dataDir } : {},
608
- ...opts.socketPath ? { socketPath: opts.socketPath } : {}
609
- });
610
- try {
611
- return await runAcpHost(spec, {
612
- client,
613
- startAgent: (s) => startAgentProcess({
614
- file: s.file,
615
- args: s.args,
616
- cwd: s.cwd,
617
- ...s.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
618
- })
619
- });
620
- } finally {
621
- await client.close().catch(() => void 0);
622
- }
623
- }
624
- export { runAcpHostFromFile as n, stopRequestPath as r, killProcessTree as t };