@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.
- package/README.md +3 -5
- package/dist/{acp-BVk6rmXR.js → acp-BUddItzP.js} +39 -7
- package/dist/{agy-relay-D8eZcLuc.js → agy-relay-BZ3d_-FS.js} +4 -2
- package/dist/{args-B3Cj2Ie4.js → args-CtyKPZuN.js} +29 -8
- package/dist/bin.js +16 -2
- package/dist/daemon.js +4 -3139
- package/dist/{daemonError-C05GqdhQ.js → daemonError-CDgEtvy7.js} +1 -1
- package/dist/dist-BNhTPp5p.js +4509 -0
- package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
- package/dist/{dist-DaIpdMke.js → dist-CFsDqevs.js} +51 -9
- package/dist/dist-CNdqmI3E.js +1065 -0
- package/dist/{dist-STNJjbNH.js → dist-CSSvrcKr.js} +1516 -599
- package/dist/{dist-BjdBeCHy.js → dist-D6Xoip5W.js} +63 -17
- package/dist/{dist-D_O_JLLq.js → dist-DAVtixeC.js} +19 -5
- package/dist/{dist-MK-cK1JY.js → dist-DTMnNySx.js} +39 -19
- package/dist/{hook-CDF1A8AY.js → hook-BA-tI6Oc.js} +101 -7
- package/dist/hook-entry-BwzBtAnd.js +1346 -0
- package/dist/hook-entry-Cgt5ZH1s.js +1 -0
- package/dist/{main-Kv31Qxro.js → main-kKnLA7Hj.js} +58 -21
- package/dist/{pick-DLp6w_-z.js → pick-BsMvXuDo.js} +1 -1
- package/dist/run-PQBzaHv1.js +8193 -0
- package/dist/{runtime-xjPzIGmp.js → runtime-0FMqklYn.js} +171 -119
- package/dist/{uninstall-8AHErPRN.js → uninstall-DcxkIDpk.js} +356 -56
- package/dist/{watch-D0KIPowJ.js → watch-BIepRTXJ.js} +29 -7
- package/package.json +14 -15
- package/dist/dist-CVdpCNJo.js +0 -793
- package/dist/dist-DzpERiRx.js +0 -624
- package/dist/hook-entry-BTJK7aO0.js +0 -2500
- package/dist/hook-entry-D6zup0QV.js +0 -1
- package/dist/run-BPtFUGtu.js +0 -5609
|
@@ -0,0 +1,1065 @@
|
|
|
1
|
+
import { n as connect } from "./dist-DAVtixeC.js";
|
|
2
|
+
import { Bn as CliKind, Cn as takeAcpLaunchFile, In as writeModelMenu, Ot as menuFromConfigOptions, Wt as planProgram, Zn as RpcErrorCode, a as ConvenoError, at as formatContinuation, it as findOnPath, kn as updateSpawnRecord, kt as modelLabel, l as NPX_SETUP_TIMEOUT_MS, ln as resolveAcpProgram, p as SPAWN_TABLE, rt as findModelOption, tr as SessionId, v as accessAllows } from "./dist-CSSvrcKr.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
|
+
var version = "0.2.0";
|
|
10
|
+
/**
|
|
11
|
+
* Pick the option to answer with. Allowing uses `allow_once` only: `allow_always` would change the
|
|
12
|
+
* CLI's own saved permissions, which is the user's call. Denying uses `reject_once`, and when the
|
|
13
|
+
* agent offers none, `cancelled`, so no `reject_always` rule is saved either.
|
|
14
|
+
*/
|
|
15
|
+
function answer(ask, allow) {
|
|
16
|
+
const want = allow ? "allow_once" : "reject_once";
|
|
17
|
+
const candidates = ask.options.filter((o) => o.kind === want);
|
|
18
|
+
const option = allow ? candidates[0] : candidates.find((o) => {
|
|
19
|
+
const text = `${o.optionId} ${o.name}`;
|
|
20
|
+
return /decline|continue/i.test(text) && !/cancel|abort|differently/i.test(text);
|
|
21
|
+
}) ?? candidates[0];
|
|
22
|
+
return option ? {
|
|
23
|
+
outcome: "selected",
|
|
24
|
+
optionId: option.optionId
|
|
25
|
+
} : { outcome: "cancelled" };
|
|
26
|
+
}
|
|
27
|
+
const CONVENO_TOOL_TITLE = new RegExp(`^(?:(?:running|run|calling|call|using|use|execute|invoke)\\s+)?(?:tool\\s*[:\\-]\\s*)?(?:mcp[_\\-.:/ ]{1,3})?conveno[_\\-.:/ ]{1,3}(${[
|
|
28
|
+
"whoami",
|
|
29
|
+
"list_sessions",
|
|
30
|
+
"send",
|
|
31
|
+
"inbox",
|
|
32
|
+
"ack",
|
|
33
|
+
"rename",
|
|
34
|
+
"set_status",
|
|
35
|
+
"become_lead",
|
|
36
|
+
"orchestrate",
|
|
37
|
+
"handoff",
|
|
38
|
+
"spawn_session",
|
|
39
|
+
"answer_permission"
|
|
40
|
+
].join("|")})$`, "i");
|
|
41
|
+
/** The hidden subcommand that starts Antigravity's idle-wake relay (`RELAY_SUBCOMMAND` of its adapter). */
|
|
42
|
+
const RELAY_SUBCOMMAND = "agy-relay";
|
|
43
|
+
/** One word of a command line: quoted (no quote, `$` or backtick inside), or bare without shell metacharacters. */
|
|
44
|
+
const WORD = String.raw`"[^"'\r\n$\`]+"|'[^"'\r\n$\`]+'|[^\s"'\r\n$\`&|;<>()^%!*?{}]+`;
|
|
45
|
+
const unquote = (w) => /^["']/.test(w) ? w.slice(1, -1) : w;
|
|
46
|
+
const baseName = (w) => unquote(w).split(/[\\/]/).pop() ?? "";
|
|
47
|
+
const RELAY_TITLE = new RegExp(`^(?:(?:running|run|calling|call|using|use|execute|invoke)\\s+)?(\`?)(?:&\\s+)?(${WORD})(?:\\s+(${WORD}))?\\s+${RELAY_SUBCOMMAND}\\1$`, "i");
|
|
48
|
+
/**
|
|
49
|
+
* Is this execute call exactly Conveno's relay command: `conveno agy-relay`, with a path, a
|
|
50
|
+
* `.cmd`, `.exe` or `.ps1` ending, or `node <path>/bin.js agy-relay`, and nothing chained after it.
|
|
51
|
+
*/
|
|
52
|
+
function isRelayCommand(call) {
|
|
53
|
+
if (call.kind !== "execute") return false;
|
|
54
|
+
const m = RELAY_TITLE.exec((call.title ?? "").trim());
|
|
55
|
+
if (!m) return false;
|
|
56
|
+
const first = m[2] ?? "";
|
|
57
|
+
const second = m[3];
|
|
58
|
+
if (second === void 0) return /^conveno(?:\.(?:cmd|exe|ps1))?$/i.test(baseName(first));
|
|
59
|
+
return /^node(?:\.exe)?$/i.test(baseName(first)) && /^bin\.js$/i.test(baseName(second));
|
|
60
|
+
}
|
|
61
|
+
/** Kinds whose title is a command line or a path, so a title that looks like a tool name is not one. */
|
|
62
|
+
const COMMAND_OR_FILE_KINDS = /* @__PURE__ */ new Set([
|
|
63
|
+
"execute",
|
|
64
|
+
"edit",
|
|
65
|
+
"delete",
|
|
66
|
+
"move"
|
|
67
|
+
]);
|
|
68
|
+
/**
|
|
69
|
+
* The Conveno tool a tool call is, or undefined. Only a call that names the whole tool counts, and
|
|
70
|
+
* never one the agent reports as a command it runs or a file it changes: the title of such a call
|
|
71
|
+
* is the command line or the path.
|
|
72
|
+
*/
|
|
73
|
+
function convenoToolOf(call) {
|
|
74
|
+
if (call.kind && COMMAND_OR_FILE_KINDS.has(call.kind)) return void 0;
|
|
75
|
+
const m = CONVENO_TOOL_TITLE.exec((call.title ?? "").trim());
|
|
76
|
+
return m ? m[1]?.toLowerCase() : void 0;
|
|
77
|
+
}
|
|
78
|
+
var AllowListPolicy = class {
|
|
79
|
+
allows;
|
|
80
|
+
constructor(allows) {
|
|
81
|
+
this.allows = allows;
|
|
82
|
+
}
|
|
83
|
+
async decide(ask, _signal) {
|
|
84
|
+
const what = `${ask.title ?? "a tool call"} (${ask.kind ?? "other"})`;
|
|
85
|
+
const own = convenoToolOf(ask) !== void 0 || isRelayCommand(ask);
|
|
86
|
+
if (own || this.allows({
|
|
87
|
+
kind: ask.kind,
|
|
88
|
+
title: ask.title
|
|
89
|
+
})) {
|
|
90
|
+
const outcome = answer(ask, true);
|
|
91
|
+
if (outcome.outcome === "selected") return {
|
|
92
|
+
allowed: true,
|
|
93
|
+
outcome,
|
|
94
|
+
reason: `allowed ${what} ${own ? "(a Conveno tool)" : "by the allow list"}`
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
allowed: false,
|
|
98
|
+
outcome: answer(ask, false),
|
|
99
|
+
reason: `denied ${what}: allowed by the allow list, but the agent offered no allow-once option`
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
allowed: false,
|
|
104
|
+
outcome: answer(ask, false),
|
|
105
|
+
reason: `denied ${what}: the allow list does not cover it`
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
/** "45 s", "2 min". */
|
|
110
|
+
const waitText = (ms) => ms >= 6e4 && ms % 6e4 === 0 ? `${ms / 6e4} min` : `${Math.round(ms / 1e3)} s`;
|
|
111
|
+
/**
|
|
112
|
+
* What the inner policy denies is put to the spawner. Its answer decides; with no answer, or no
|
|
113
|
+
* spawner, `unanswered` does. "Always" is remembered for this policy's lifetime, per kind and exact
|
|
114
|
+
* title. The agent only ever gets allow-once or reject-once (see `answer`).
|
|
115
|
+
*/
|
|
116
|
+
var AskSpawnerPolicy = class {
|
|
117
|
+
inner;
|
|
118
|
+
deps;
|
|
119
|
+
always = /* @__PURE__ */ new Set();
|
|
120
|
+
constructor(inner, deps) {
|
|
121
|
+
this.inner = inner;
|
|
122
|
+
this.deps = deps;
|
|
123
|
+
}
|
|
124
|
+
async decide(ask, signal) {
|
|
125
|
+
const first = await this.inner.decide(ask, signal);
|
|
126
|
+
if (first.allowed) return first;
|
|
127
|
+
const what = `${ask.title ?? "a tool call"} (${ask.kind ?? "other"})`;
|
|
128
|
+
const key = ask.title === void 0 ? void 0 : `${ask.kind ?? ""}\0${ask.title}`;
|
|
129
|
+
if (key !== void 0 && this.always.has(key)) return this.allow(ask, what, `allowed ${what}: always allowed earlier`);
|
|
130
|
+
const { deps } = this;
|
|
131
|
+
const timeoutMs = deps.timeoutMs ?? 12e4;
|
|
132
|
+
await deps.waiting?.(ask.title ?? what);
|
|
133
|
+
let reply;
|
|
134
|
+
try {
|
|
135
|
+
reply = await Promise.race([deps.ask({
|
|
136
|
+
...ask.title !== void 0 ? { title: ask.title.slice(0, 500) } : {},
|
|
137
|
+
...ask.kind !== void 0 ? { kind: ask.kind.slice(0, 100) } : {},
|
|
138
|
+
timeoutMs,
|
|
139
|
+
unanswered: deps.unanswered
|
|
140
|
+
}).catch((e) => {
|
|
141
|
+
deps.log?.(`could not ask the spawner: ${e instanceof Error ? e.message : String(e)}`);
|
|
142
|
+
return { answer: "no_spawner" };
|
|
143
|
+
}), new Promise((r) => {
|
|
144
|
+
if (signal.aborted) r(null);
|
|
145
|
+
else signal.addEventListener("abort", () => r(null), { once: true });
|
|
146
|
+
})]);
|
|
147
|
+
} finally {
|
|
148
|
+
await deps.waiting?.(null);
|
|
149
|
+
}
|
|
150
|
+
if (reply === null) return {
|
|
151
|
+
allowed: false,
|
|
152
|
+
outcome: { outcome: "cancelled" },
|
|
153
|
+
reason: `cancelled ${what}`
|
|
154
|
+
};
|
|
155
|
+
switch (reply.answer) {
|
|
156
|
+
case "allow_once": return this.allow(ask, what, `allowed ${what}: ${deps.spawnerName} said yes`);
|
|
157
|
+
case "allow_always":
|
|
158
|
+
if (key !== void 0) this.always.add(key);
|
|
159
|
+
return this.allow(ask, what, `allowed ${what}: ${deps.spawnerName} said always`);
|
|
160
|
+
case "deny": return this.deny(ask, what, `denied by ${deps.spawnerName}`);
|
|
161
|
+
case "unanswered":
|
|
162
|
+
case "worker_offline":
|
|
163
|
+
case "no_spawner": {
|
|
164
|
+
const why = reply.answer === "unanswered" ? `no answer in ${waitText(timeoutMs)}` : reply.answer === "worker_offline" ? "the worker went offline while waiting" : "no spawner to ask";
|
|
165
|
+
return deps.unanswered === "allow" ? this.allow(ask, what, `allowed ${what}: ${why}`) : this.deny(ask, what, why);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
allow(ask, what, reason) {
|
|
170
|
+
const outcome = answer(ask, true);
|
|
171
|
+
if (outcome.outcome === "selected") return {
|
|
172
|
+
allowed: true,
|
|
173
|
+
outcome,
|
|
174
|
+
reason
|
|
175
|
+
};
|
|
176
|
+
return this.deny(ask, what, "the agent offered no allow-once option");
|
|
177
|
+
}
|
|
178
|
+
deny(ask, what, why) {
|
|
179
|
+
return {
|
|
180
|
+
allowed: false,
|
|
181
|
+
outcome: answer(ask, false),
|
|
182
|
+
reason: `denied ${what}: ${why}`,
|
|
183
|
+
why
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
/** Calls remembered at most; the oldest are dropped. */
|
|
188
|
+
const TOOLS_MAX = 1e3;
|
|
189
|
+
var ToolTracker = class {
|
|
190
|
+
/** Tool calls seen in this session: their latest title and kind. */
|
|
191
|
+
tools = /* @__PURE__ */ new Map();
|
|
192
|
+
/** Feed one `session/update`. Returns a status line when the agent starts a tool call. */
|
|
193
|
+
update(u) {
|
|
194
|
+
if (u.sessionUpdate !== "tool_call" && u.sessionUpdate !== "tool_call_update") return;
|
|
195
|
+
const t = u;
|
|
196
|
+
const next = {
|
|
197
|
+
...this.tools.get(t.toolCallId) ?? {},
|
|
198
|
+
...t.title ? { title: t.title } : {},
|
|
199
|
+
...t.kind ? { kind: t.kind } : {}
|
|
200
|
+
};
|
|
201
|
+
this.tools.set(t.toolCallId, next);
|
|
202
|
+
if (this.tools.size > TOOLS_MAX) {
|
|
203
|
+
const first = this.tools.keys().next().value;
|
|
204
|
+
if (first !== void 0) this.tools.delete(first);
|
|
205
|
+
}
|
|
206
|
+
return u.sessionUpdate === "tool_call" ? next.title ?? next.kind ?? "tool" : void 0;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const HOST_VERSION = version;
|
|
210
|
+
/** How long the agent gets to answer `initialize` and `session/new`. */
|
|
211
|
+
const SETUP_TIMEOUT_MS = 12e4;
|
|
212
|
+
/** How often the host looks for a stop request from `conveno stop`. */
|
|
213
|
+
const STOP_POLL_MS = 500;
|
|
214
|
+
/** A stop request file: `conveno stop` writes it next to the spawn record. */
|
|
215
|
+
const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
|
|
216
|
+
function withTimeout$1(p, ms, what) {
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
const t = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} did not answer within ${Math.round(ms / 1e3)} s.`)), ms);
|
|
219
|
+
p.then((v) => {
|
|
220
|
+
clearTimeout(t);
|
|
221
|
+
resolve(v);
|
|
222
|
+
}, (e) => {
|
|
223
|
+
clearTimeout(t);
|
|
224
|
+
reject(e);
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
const errText$1 = (e) => e instanceof Error ? e.message : String(e);
|
|
229
|
+
/** A JSON-RPC error's own words: an agent that throws gets "Internal error" with the text in `data.details`. */
|
|
230
|
+
const requestReason = (e) => {
|
|
231
|
+
const details = e?.data?.details;
|
|
232
|
+
return typeof details === "string" && details.trim() !== "" ? details.trim() : errText$1(e);
|
|
233
|
+
};
|
|
234
|
+
const describeStop = (r) => {
|
|
235
|
+
switch (r.kind) {
|
|
236
|
+
case "requested": return `stopped by ${r.by}`;
|
|
237
|
+
case "agent-exit": return `its ACP server exited (${r.signal ? `signal ${r.signal}` : `code ${r.code ?? "none"}`})`;
|
|
238
|
+
case "session-gone": return `its Conveno session ended (${r.detail})`;
|
|
239
|
+
case "failed": return `it failed: ${r.detail}`;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
/**
|
|
243
|
+
* Drive one worker until it stops. Returns the process exit code: 0 for a requested stop, 1 for
|
|
244
|
+
* anything else.
|
|
245
|
+
*/
|
|
246
|
+
async function runAcpHost(spec, deps) {
|
|
247
|
+
return new AcpHost(spec, deps).run();
|
|
248
|
+
}
|
|
249
|
+
var AcpHost = class {
|
|
250
|
+
spec;
|
|
251
|
+
deps;
|
|
252
|
+
client;
|
|
253
|
+
log;
|
|
254
|
+
policy;
|
|
255
|
+
tools = new ToolTracker();
|
|
256
|
+
sessionId;
|
|
257
|
+
/** The model label, sent again with each heartbeat so a restarted daemon still shows it. */
|
|
258
|
+
modelLabel;
|
|
259
|
+
acpSessionId;
|
|
260
|
+
conn;
|
|
261
|
+
agent;
|
|
262
|
+
stopReason;
|
|
263
|
+
stopCtl = new AbortController();
|
|
264
|
+
/** Aborted to cancel the current prompt turn; pending permission policies see it too. */
|
|
265
|
+
turnCtl = new AbortController();
|
|
266
|
+
lastPromptFailure;
|
|
267
|
+
/** The status line after a failed prompt, kept until the next prompt starts. */
|
|
268
|
+
failedText;
|
|
269
|
+
denials = [];
|
|
270
|
+
/** The last denied call, shown on the row until the next turn starts. */
|
|
271
|
+
deniedText;
|
|
272
|
+
/** The worker called Conveno's `send` (or `handoff`) in the turn that is running. */
|
|
273
|
+
sentThisTurn = false;
|
|
274
|
+
/** The daemon's `lastSentAt` of this session when the turn began. */
|
|
275
|
+
sentAtTurnStart;
|
|
276
|
+
/** The messages the next turn's prompt hands over; undefined for the first task. */
|
|
277
|
+
answering;
|
|
278
|
+
/** When the newest message from a session that the running turn hands over was sent. */
|
|
279
|
+
askedAt;
|
|
280
|
+
/** Status updates go out one after another, so a late one cannot overwrite a newer one. */
|
|
281
|
+
statusChain = Promise.resolve();
|
|
282
|
+
lastStatus;
|
|
283
|
+
timers = [];
|
|
284
|
+
constructor(spec, deps) {
|
|
285
|
+
this.spec = spec;
|
|
286
|
+
this.deps = deps;
|
|
287
|
+
this.client = deps.client;
|
|
288
|
+
this.log = deps.log ?? ((line) => process.stderr.write(`[conveno acp-host] ${line}\n`));
|
|
289
|
+
this.policy = deps.policy ?? new AskSpawnerPolicy(new AllowListPolicy((call) => accessAllows(spec.access, call)), {
|
|
290
|
+
spawnerName: spec.from,
|
|
291
|
+
unanswered: spec.unanswered ?? "deny",
|
|
292
|
+
timeoutMs: deps.askTimeoutMs ?? spec.askTimeoutMs ?? 12e4,
|
|
293
|
+
ask: (p) => this.client["permission.ask"]({
|
|
294
|
+
sessionId: this.me,
|
|
295
|
+
...p
|
|
296
|
+
}),
|
|
297
|
+
waiting: (title) => this.waitingFor(title),
|
|
298
|
+
log: this.log
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
/** Ask the host to stop. The first reason wins. */
|
|
302
|
+
stop(reason) {
|
|
303
|
+
if (this.stopReason) return;
|
|
304
|
+
this.stopReason = reason;
|
|
305
|
+
this.log(`stopping: ${describeStop(reason)}`);
|
|
306
|
+
this.stopCtl.abort();
|
|
307
|
+
this.turnCtl.abort();
|
|
308
|
+
}
|
|
309
|
+
get stopping() {
|
|
310
|
+
return this.stopReason !== void 0;
|
|
311
|
+
}
|
|
312
|
+
async run() {
|
|
313
|
+
const onSignal = () => this.stop({
|
|
314
|
+
kind: "requested",
|
|
315
|
+
by: "a signal"
|
|
316
|
+
});
|
|
317
|
+
process.once("SIGTERM", onSignal);
|
|
318
|
+
process.once("SIGINT", onSignal);
|
|
319
|
+
try {
|
|
320
|
+
await this.setup();
|
|
321
|
+
await this.loop();
|
|
322
|
+
} catch (e) {
|
|
323
|
+
if (!this.stopping) this.stop({
|
|
324
|
+
kind: "failed",
|
|
325
|
+
detail: errText$1(e)
|
|
326
|
+
});
|
|
327
|
+
} finally {
|
|
328
|
+
process.off("SIGTERM", onSignal);
|
|
329
|
+
process.off("SIGINT", onSignal);
|
|
330
|
+
await this.teardown();
|
|
331
|
+
}
|
|
332
|
+
return this.stopReason?.kind === "requested" ? 0 : 1;
|
|
333
|
+
}
|
|
334
|
+
async setup() {
|
|
335
|
+
const { spec } = this;
|
|
336
|
+
const timeout = spec.setupTimeoutMs ?? this.deps.setupTimeoutMs ?? SETUP_TIMEOUT_MS;
|
|
337
|
+
this.agent = await this.deps.startAgent(spec);
|
|
338
|
+
const agent = this.agent;
|
|
339
|
+
this.log(`started ${spec.file} (pid ${agent.pid}) for ${spec.name}`);
|
|
340
|
+
agent.exited.then(({ code, signal }) => {
|
|
341
|
+
this.stop({
|
|
342
|
+
kind: "agent-exit",
|
|
343
|
+
code,
|
|
344
|
+
signal
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
updateSpawnRecord(spec.record, {
|
|
348
|
+
pid: process.pid,
|
|
349
|
+
agentPid: agent.pid
|
|
350
|
+
});
|
|
351
|
+
this.every(this.deps.stopPollMs ?? STOP_POLL_MS, () => {
|
|
352
|
+
const path = stopRequestPath(spec.record);
|
|
353
|
+
if (existsSync(path)) {
|
|
354
|
+
rmSync(path, { force: true });
|
|
355
|
+
this.stop({
|
|
356
|
+
kind: "requested",
|
|
357
|
+
by: "conveno stop"
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
const app = client({ name: "conveno" }).onNotification(methods.client.session.update, ({ params }) => this.onUpdate(params)).onRequest(methods.client.session.requestPermission, ({ params }) => this.onPermission(params));
|
|
362
|
+
this.conn = app.connect(ndJsonStream(Writable.toWeb(agent.stdin), Readable.toWeb(agent.stdout)));
|
|
363
|
+
const conn = this.conn;
|
|
364
|
+
const init = await this.untilStopped(withTimeout$1(conn.agent.request(methods.agent.initialize, {
|
|
365
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
366
|
+
clientCapabilities: {
|
|
367
|
+
fs: {
|
|
368
|
+
readTextFile: false,
|
|
369
|
+
writeTextFile: false
|
|
370
|
+
},
|
|
371
|
+
terminal: false
|
|
372
|
+
},
|
|
373
|
+
clientInfo: {
|
|
374
|
+
name: "conveno",
|
|
375
|
+
version: HOST_VERSION
|
|
376
|
+
}
|
|
377
|
+
}), timeout, "initialize"));
|
|
378
|
+
const agentVersion = init.agentInfo?.version?.trim().slice(0, 64);
|
|
379
|
+
this.log(`initialize: protocol ${init.protocolVersion}, agent ${init.agentInfo?.name ?? "unknown"} ${agentVersion ?? ""}`);
|
|
380
|
+
const created = await this.untilStopped(withTimeout$1(conn.agent.request(methods.agent.session.new, {
|
|
381
|
+
cwd: spec.cwd,
|
|
382
|
+
mcpServers: spec.mcp ? [{
|
|
383
|
+
name: "conveno",
|
|
384
|
+
command: spec.mcp.command,
|
|
385
|
+
args: spec.mcp.args,
|
|
386
|
+
env: []
|
|
387
|
+
}] : []
|
|
388
|
+
}), timeout, "session/new"));
|
|
389
|
+
this.acpSessionId = created.sessionId;
|
|
390
|
+
this.log(`session/new: ${created.sessionId}`);
|
|
391
|
+
const mode = spec.mode;
|
|
392
|
+
if (mode && created.modes?.availableModes.some((m) => m.id === mode)) await this.untilStopped(withTimeout$1(conn.agent.request(methods.agent.session.setMode, {
|
|
393
|
+
sessionId: created.sessionId,
|
|
394
|
+
modeId: mode
|
|
395
|
+
}), timeout, "session/set_mode")).then(() => this.log(`mode: ${mode}`), (e) => this.log(`could not set mode ${mode}: ${errText$1(e)}`));
|
|
396
|
+
else if (mode) {
|
|
397
|
+
const configId = modeConfigId(created.configOptions, mode);
|
|
398
|
+
if (configId) await this.untilStopped(withTimeout$1(conn.agent.request(methods.agent.session.setConfigOption, {
|
|
399
|
+
sessionId: created.sessionId,
|
|
400
|
+
configId,
|
|
401
|
+
value: mode
|
|
402
|
+
}), timeout, "session/set_config_option")).then(() => this.log(`mode: ${mode} (config option ${configId})`), (e) => this.log(`could not set mode ${mode}: ${errText$1(e)}`));
|
|
403
|
+
}
|
|
404
|
+
const modelState = await this.applyModel(conn, created.sessionId, created.configOptions, timeout);
|
|
405
|
+
const spawnedBy = SessionId.safeParse(spec.spawnedBy);
|
|
406
|
+
const { session } = await this.client["session.register"]({
|
|
407
|
+
name: spec.name,
|
|
408
|
+
cli: CliKind.parse(spec.cli),
|
|
409
|
+
cwd: spec.cwd,
|
|
410
|
+
pid: process.pid,
|
|
411
|
+
hostPid: process.pid,
|
|
412
|
+
spawned: true,
|
|
413
|
+
acp: true,
|
|
414
|
+
...spawnedBy.success ? { spawnedBy: spawnedBy.data } : {},
|
|
415
|
+
...agentVersion ? { cliVersion: agentVersion } : {},
|
|
416
|
+
...modelState.label ? { model: modelState.label.slice(0, 200) } : {}
|
|
417
|
+
});
|
|
418
|
+
this.sessionId = session.id;
|
|
419
|
+
this.modelLabel = modelState.label?.slice(0, 200);
|
|
420
|
+
await this.client["session.setNative"]({
|
|
421
|
+
sessionId: session.id,
|
|
422
|
+
nativeId: created.sessionId.slice(0, 256)
|
|
423
|
+
}).catch((e) => this.log(`could not record the ACP session id: ${errText$1(e)}`));
|
|
424
|
+
updateSpawnRecord(spec.record, {
|
|
425
|
+
pid: process.pid,
|
|
426
|
+
sessionId: session.id,
|
|
427
|
+
agentPid: agent.pid
|
|
428
|
+
});
|
|
429
|
+
this.log(`registered as ${session.name} (${session.id})`);
|
|
430
|
+
for (const note of modelState.notes) await this.tell(`[conveno] Worker ${spec.name}: ${note}`);
|
|
431
|
+
this.every(this.deps.heartbeatMs ?? 15e3, () => this.heartbeat());
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Set the worker's model, then its effort (the effort list can change with the model), through
|
|
435
|
+
* the CLI's session config options. Never fails the worker: a name the CLI does not offer or an
|
|
436
|
+
* error keeps the CLI's default and leaves a note for the spawner.
|
|
437
|
+
*/
|
|
438
|
+
async applyModel(conn, sessionId, initial, timeout) {
|
|
439
|
+
const { spec } = this;
|
|
440
|
+
let options = initial;
|
|
441
|
+
const notes = [];
|
|
442
|
+
const set = async (kind, want) => {
|
|
443
|
+
if (!want) return;
|
|
444
|
+
const opt = findModelOption(options, kind);
|
|
445
|
+
if (!opt) {
|
|
446
|
+
this.log(`${kind}: '${want}' not offered; ${spec.cli} has no ${kind} choice here`);
|
|
447
|
+
notes.push(`${kind} '${want}' is not offered by ${spec.cli}: it has no ${kind} choice here.`);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (!opt.values.some((v) => v.value === want)) {
|
|
451
|
+
const names = opt.values.map((v) => v.value);
|
|
452
|
+
const offered = names.slice(0, 20).join(", ") + (names.length > 20 ? ` and ${names.length - 20} more` : "");
|
|
453
|
+
this.log(`${kind}: '${want}' not offered${opt.current ? `; using ${opt.current}` : ""}. Offered: ${offered}`);
|
|
454
|
+
notes.push(`${kind} '${want}' is not offered by ${spec.cli}${opt.current ? `; it uses ${opt.current}` : ""}. Offered: ${offered}.`);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
try {
|
|
458
|
+
const r = await this.untilStopped(withTimeout$1(conn.agent.request(methods.agent.session.setConfigOption, {
|
|
459
|
+
sessionId,
|
|
460
|
+
configId: opt.id,
|
|
461
|
+
value: want
|
|
462
|
+
}), timeout, "session/set_config_option"));
|
|
463
|
+
if (Array.isArray(r?.configOptions) && r.configOptions.length > 0) options = r.configOptions;
|
|
464
|
+
} catch (e) {
|
|
465
|
+
this.log(`could not set ${kind} ${want}: ${errText$1(e)}`);
|
|
466
|
+
notes.push(`${kind} '${want}' could not be set on ${spec.cli}; it keeps its default.`);
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
await set("model", spec.model);
|
|
470
|
+
await set("effort", spec.effort);
|
|
471
|
+
const m = findModelOption(options, "model");
|
|
472
|
+
const e = findModelOption(options, "effort");
|
|
473
|
+
const label = modelLabel({
|
|
474
|
+
...m?.current ? { model: m.current } : {},
|
|
475
|
+
...e?.current ? { effort: e.current } : {}
|
|
476
|
+
});
|
|
477
|
+
if (label) this.log(`model: ${label}`);
|
|
478
|
+
if (spec.modelMenuPath && m) writeModelMenu(spec.modelMenuPath, CliKind.parse(spec.cli), menuFromConfigOptions(options, (/* @__PURE__ */ new Date()).toISOString()));
|
|
479
|
+
return {
|
|
480
|
+
label,
|
|
481
|
+
notes
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
async loop() {
|
|
485
|
+
let next = this.spec.task ?? null;
|
|
486
|
+
if (next === null) await this.status("idle", null);
|
|
487
|
+
while (!this.stopping) if (next !== null) {
|
|
488
|
+
const finished = await this.prompt(next);
|
|
489
|
+
if (this.stopping) break;
|
|
490
|
+
await this.reportTurnEnd(finished);
|
|
491
|
+
next = await this.endTurn();
|
|
492
|
+
} else next = await this.waitForWork();
|
|
493
|
+
}
|
|
494
|
+
/** Report the end of a turn. Returns the prompt to continue with, or null to wait for work. */
|
|
495
|
+
async endTurn() {
|
|
496
|
+
try {
|
|
497
|
+
const r = await this.client["turn.end"]({
|
|
498
|
+
sessionId: this.me,
|
|
499
|
+
allowContinue: true
|
|
500
|
+
});
|
|
501
|
+
this.answering = r.messages;
|
|
502
|
+
const next = formatContinuation(r.messages, r.orchestrator, r.remaining) || null;
|
|
503
|
+
if (next === null) await this.status(void 0, this.failedText ?? this.deniedText ?? null);
|
|
504
|
+
return next;
|
|
505
|
+
} catch (e) {
|
|
506
|
+
if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
|
|
507
|
+
this.stop({
|
|
508
|
+
kind: "session-gone",
|
|
509
|
+
detail: errText$1(e)
|
|
510
|
+
});
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
this.log(`turn.end failed: ${errText$1(e)}`);
|
|
514
|
+
await this.status("idle", this.failedText ?? this.deniedText ?? null);
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* One prompt turn. Resolves when the agent answers `session/prompt` or the host stops. True when
|
|
520
|
+
* the turn ran to its end; false when the prompt failed (the spawner was told) or the host stopped.
|
|
521
|
+
*/
|
|
522
|
+
async prompt(text) {
|
|
523
|
+
const conn = this.conn;
|
|
524
|
+
const sid = this.acpSessionId;
|
|
525
|
+
if (!conn || !sid) return false;
|
|
526
|
+
this.turnCtl = new AbortController();
|
|
527
|
+
this.failedText = void 0;
|
|
528
|
+
this.denials = [];
|
|
529
|
+
this.deniedText = void 0;
|
|
530
|
+
this.sentThisTurn = false;
|
|
531
|
+
this.askedAt = (this.answering ?? []).filter((m) => m.kind !== "system").map((m) => m.createdAt).sort().at(-1);
|
|
532
|
+
this.answering = void 0;
|
|
533
|
+
this.sentAtTurnStart = await this.lastSentAt();
|
|
534
|
+
await this.status("busy", null);
|
|
535
|
+
const turn = conn.agent.request(methods.agent.session.prompt, {
|
|
536
|
+
sessionId: sid,
|
|
537
|
+
prompt: [{
|
|
538
|
+
type: "text",
|
|
539
|
+
text
|
|
540
|
+
}]
|
|
541
|
+
});
|
|
542
|
+
try {
|
|
543
|
+
await this.untilStopped(turn);
|
|
544
|
+
} catch (e) {
|
|
545
|
+
if (!this.stopping) {
|
|
546
|
+
const reason = requestReason(e);
|
|
547
|
+
this.log(`session/prompt failed: ${reason}`);
|
|
548
|
+
await this.promptFailed(reason);
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
await conn.agent.notify(methods.agent.session.cancel, { sessionId: sid }).catch(() => void 0);
|
|
552
|
+
const grace = this.deps.stopGraceMs ?? 5e3;
|
|
553
|
+
await Promise.race([turn.then(() => void 0, () => void 0), new Promise((r) => setTimeout(r, grace).unref())]);
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
return true;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Idle: wait until the daemon hands this session messages through `turn.wake`, then return the
|
|
560
|
+
* prompt for them. It asks on every `message.received` or `session.updated` event for this
|
|
561
|
+
* session and every `wakePollMs`. Returns null when the host is stopping.
|
|
562
|
+
*/
|
|
563
|
+
async waitForWork() {
|
|
564
|
+
const id = this.me;
|
|
565
|
+
const listenerId = randomBytes(12).toString("base64url");
|
|
566
|
+
let dirty = false;
|
|
567
|
+
let poke;
|
|
568
|
+
const off = this.client.onEvent((e) => {
|
|
569
|
+
if (e.event === "message.received" || e.event === "session.updated" && e.data.session.id === id) {
|
|
570
|
+
dirty = true;
|
|
571
|
+
poke?.();
|
|
572
|
+
}
|
|
573
|
+
});
|
|
574
|
+
const pollMs = this.deps.wakePollMs ?? 3e4;
|
|
575
|
+
try {
|
|
576
|
+
await this.client["events.subscribe"]({
|
|
577
|
+
sessionId: id,
|
|
578
|
+
topics: ["message.received", "session.updated"]
|
|
579
|
+
});
|
|
580
|
+
while (!this.stopping) {
|
|
581
|
+
dirty = false;
|
|
582
|
+
const r = await this.client["turn.wake"]({
|
|
583
|
+
sessionId: id,
|
|
584
|
+
listenerId
|
|
585
|
+
});
|
|
586
|
+
if (r.messages.length > 0) {
|
|
587
|
+
this.answering = r.messages;
|
|
588
|
+
return formatContinuation(r.messages, r.orchestrator, r.remaining);
|
|
589
|
+
}
|
|
590
|
+
if (r.superseded) {
|
|
591
|
+
this.log("turn.wake: superseded; listening again");
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
if (dirty) continue;
|
|
595
|
+
await new Promise((resolve) => {
|
|
596
|
+
const done = () => {
|
|
597
|
+
clearTimeout(t);
|
|
598
|
+
this.stopCtl.signal.removeEventListener("abort", done);
|
|
599
|
+
poke = void 0;
|
|
600
|
+
resolve();
|
|
601
|
+
};
|
|
602
|
+
const t = setTimeout(done, pollMs);
|
|
603
|
+
poke = done;
|
|
604
|
+
this.stopCtl.signal.addEventListener("abort", done);
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
return null;
|
|
608
|
+
} catch (e) {
|
|
609
|
+
if (this.stopping) return null;
|
|
610
|
+
if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) {
|
|
611
|
+
this.stop({
|
|
612
|
+
kind: "session-gone",
|
|
613
|
+
detail: errText$1(e)
|
|
614
|
+
});
|
|
615
|
+
return null;
|
|
616
|
+
}
|
|
617
|
+
this.log(`waiting for work failed: ${errText$1(e)}`);
|
|
618
|
+
await new Promise((r) => setTimeout(r, Math.min(pollMs, 5e3)).unref());
|
|
619
|
+
return null;
|
|
620
|
+
} finally {
|
|
621
|
+
off();
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
onUpdate(n) {
|
|
625
|
+
if (n.sessionId !== this.acpSessionId) return;
|
|
626
|
+
const doing = this.tools.update(n.update);
|
|
627
|
+
const id = n.update.toolCallId;
|
|
628
|
+
if (id !== void 0) this.noteConvenoCall(this.tools.tools.get(id));
|
|
629
|
+
if (doing !== void 0 && doing !== this.lastStatus) {
|
|
630
|
+
this.lastStatus = doing;
|
|
631
|
+
this.status(void 0, this.deniedText ?? doing);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
async onPermission(p) {
|
|
635
|
+
if (this.turnCtl.signal.aborted) return { outcome: { outcome: "cancelled" } };
|
|
636
|
+
const known = this.tools.tools.get(p.toolCall.toolCallId) ?? {};
|
|
637
|
+
const title = p.toolCall.title ?? known.title;
|
|
638
|
+
const kind = p.toolCall.kind ?? known.kind;
|
|
639
|
+
this.noteConvenoCall({
|
|
640
|
+
title,
|
|
641
|
+
kind
|
|
642
|
+
});
|
|
643
|
+
const ask = {
|
|
644
|
+
toolCallId: p.toolCall.toolCallId,
|
|
645
|
+
...title ? { title } : {},
|
|
646
|
+
...kind ? { kind } : {},
|
|
647
|
+
options: p.options
|
|
648
|
+
};
|
|
649
|
+
const signal = this.turnCtl.signal;
|
|
650
|
+
const decision = await Promise.race([this.policy.decide(ask, signal), new Promise((r) => signal.addEventListener("abort", () => r(null), { once: true }))]);
|
|
651
|
+
if (decision === null || signal.aborted) return { outcome: { outcome: "cancelled" } };
|
|
652
|
+
this.log(`permission: ${decision.reason}`);
|
|
653
|
+
if (!decision.allowed) {
|
|
654
|
+
const what = `${title ?? "a tool call"} (${kind ?? "other"})`;
|
|
655
|
+
this.denials.push(`${what}: ${decision.why ?? "it was not allowed"}`);
|
|
656
|
+
this.deniedText = `denied: ${title ?? what}`;
|
|
657
|
+
this.status(void 0, this.deniedText);
|
|
658
|
+
}
|
|
659
|
+
return { outcome: decision.outcome };
|
|
660
|
+
}
|
|
661
|
+
get me() {
|
|
662
|
+
if (!this.sessionId) throw new Error("The session is not registered yet.");
|
|
663
|
+
return this.sessionId;
|
|
664
|
+
}
|
|
665
|
+
async status(status, statusText) {
|
|
666
|
+
if (!this.sessionId) return;
|
|
667
|
+
const text = typeof statusText === "string" ? statusText.slice(0, 200) : statusText;
|
|
668
|
+
if (status === void 0 && text === void 0) return;
|
|
669
|
+
const sessionId = this.sessionId;
|
|
670
|
+
const send = () => this.client["session.setStatus"]({
|
|
671
|
+
sessionId,
|
|
672
|
+
...status ? { status } : {},
|
|
673
|
+
...text !== void 0 ? { statusText: text } : {}
|
|
674
|
+
}).catch(() => void 0);
|
|
675
|
+
const done = this.statusChain.then(send, send);
|
|
676
|
+
this.statusChain = done;
|
|
677
|
+
await done;
|
|
678
|
+
}
|
|
679
|
+
/** This session as the daemon has it now; undefined when unknown. */
|
|
680
|
+
async self() {
|
|
681
|
+
if (!this.sessionId) return void 0;
|
|
682
|
+
try {
|
|
683
|
+
const { sessions } = await this.client["session.list"]({ includeOffline: true });
|
|
684
|
+
return sessions.find((x) => x.id === this.sessionId);
|
|
685
|
+
} catch {
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
/** When the daemon last saw this session send a message; undefined if never, or unknown. */
|
|
690
|
+
async lastSentAt() {
|
|
691
|
+
return (await this.self())?.lastSentAt;
|
|
692
|
+
}
|
|
693
|
+
/** How a notice names this worker: by its name now, which a rename may have changed. */
|
|
694
|
+
async who() {
|
|
695
|
+
return `[conveno] Worker ${(await this.self())?.name ?? this.spec.name} (${this.spec.cli}, over ACP)`;
|
|
696
|
+
}
|
|
697
|
+
/** Show that the worker waits for its spawner's answer; null puts the usual status back. */
|
|
698
|
+
async waitingFor(title) {
|
|
699
|
+
await this.status(void 0, title === null ? this.deniedText ?? this.lastStatus ?? null : `waiting for permission: ${title}`);
|
|
700
|
+
}
|
|
701
|
+
async heartbeat() {
|
|
702
|
+
if (!this.sessionId) return;
|
|
703
|
+
try {
|
|
704
|
+
await this.client["session.heartbeat"]({
|
|
705
|
+
sessionId: this.sessionId,
|
|
706
|
+
...this.modelLabel ? { model: this.modelLabel } : {}
|
|
707
|
+
});
|
|
708
|
+
} catch (e) {
|
|
709
|
+
if (e instanceof ConvenoError && e.code === RpcErrorCode.NotFound) this.stop({
|
|
710
|
+
kind: "session-gone",
|
|
711
|
+
detail: errText$1(e)
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* The agent refused a prompt. Not signed in is final: the worker could never run, so it stops,
|
|
717
|
+
* and its spawner is told why (the stop notice carries the reason). Any other failure keeps the
|
|
718
|
+
* worker running, shows in its status line, and goes to the spawner once per reason.
|
|
719
|
+
*/
|
|
720
|
+
async promptFailed(reason) {
|
|
721
|
+
if (/authentication required|not (logged|signed) in|unauthenticated/i.test(reason)) {
|
|
722
|
+
const detail = `${reason}. Sign in to ${this.spec.cli} on its own, then spawn it again`;
|
|
723
|
+
await this.status("idle", `Failed: ${detail}`);
|
|
724
|
+
this.stop({
|
|
725
|
+
kind: "failed",
|
|
726
|
+
detail
|
|
727
|
+
});
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
this.failedText = `Last prompt failed: ${reason}`;
|
|
731
|
+
await this.status("idle", this.failedText);
|
|
732
|
+
if (reason === this.lastPromptFailure) return;
|
|
733
|
+
this.lastPromptFailure = reason;
|
|
734
|
+
await this.tell(`${await this.who()} could not run a prompt: ${reason}. It keeps running and takes the next message.`);
|
|
735
|
+
}
|
|
736
|
+
/** Remember that the worker sent something this turn. Only Conveno's own send tools count. */
|
|
737
|
+
noteConvenoCall(call) {
|
|
738
|
+
if (!call) return;
|
|
739
|
+
const tool = convenoToolOf(call);
|
|
740
|
+
if (tool === "send" || tool === "handoff") this.sentThisTurn = true;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* One note to the spawner about the turn that just ended: the worker finished without sending
|
|
744
|
+
* anything, and/or which tool calls were denied. Nothing when there is no spawner (a spawn from
|
|
745
|
+
* a terminal), when the worker did reply and nothing was denied, or when the prompt failed.
|
|
746
|
+
*/
|
|
747
|
+
async reportTurnEnd(finished) {
|
|
748
|
+
const denials = this.denials;
|
|
749
|
+
this.denials = [];
|
|
750
|
+
if (!this.spec.spawnedBy) return;
|
|
751
|
+
let silent = finished && !this.sentThisTurn;
|
|
752
|
+
if (silent) {
|
|
753
|
+
const sent = await this.lastSentAt();
|
|
754
|
+
const askedAt = this.askedAt;
|
|
755
|
+
if (sent !== this.sentAtTurnStart) silent = false;
|
|
756
|
+
else if (sent !== void 0 && askedAt !== void 0 && sent >= askedAt) silent = false;
|
|
757
|
+
}
|
|
758
|
+
if (denials.length === 0 && !silent) return;
|
|
759
|
+
const who = await this.who();
|
|
760
|
+
const lines = [];
|
|
761
|
+
if (silent) lines.push(`${who} finished its turn without replying.`);
|
|
762
|
+
if (denials.length > 0) {
|
|
763
|
+
const list = denials.slice(0, 5).map((d) => `- ${d}`);
|
|
764
|
+
if (denials.length > 5) list.push(`- and ${denials.length - 5} more`);
|
|
765
|
+
lines.push(silent ? "These tool calls were not allowed in its last turn:" : `${who} had tool calls that were not allowed in its last turn:`, ...list);
|
|
766
|
+
}
|
|
767
|
+
await this.tell(lines.join("\n"));
|
|
768
|
+
}
|
|
769
|
+
/** Send a text message from this session to its spawner. Never throws. */
|
|
770
|
+
async tell(text) {
|
|
771
|
+
const to = this.spec.spawnedBy;
|
|
772
|
+
if (!to || !this.sessionId) return;
|
|
773
|
+
await this.client["message.send"]({
|
|
774
|
+
sessionId: this.sessionId,
|
|
775
|
+
to,
|
|
776
|
+
kind: "text",
|
|
777
|
+
body: { text }
|
|
778
|
+
}).catch((e) => {
|
|
779
|
+
this.log(`could not message the spawner: ${errText$1(e)}`);
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
every(ms, fn) {
|
|
783
|
+
const t = setInterval(() => void fn(), ms);
|
|
784
|
+
t.unref();
|
|
785
|
+
this.timers.push(t);
|
|
786
|
+
}
|
|
787
|
+
/** `p`, or a rejection as soon as the host is asked to stop. */
|
|
788
|
+
untilStopped(p) {
|
|
789
|
+
const signal = this.stopCtl.signal;
|
|
790
|
+
if (signal.aborted) return Promise.reject(/* @__PURE__ */ new Error("stopping"));
|
|
791
|
+
return new Promise((resolve, reject) => {
|
|
792
|
+
const onAbort = () => reject(/* @__PURE__ */ new Error("stopping"));
|
|
793
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
794
|
+
p.then((v) => {
|
|
795
|
+
signal.removeEventListener("abort", onAbort);
|
|
796
|
+
resolve(v);
|
|
797
|
+
}, (e) => {
|
|
798
|
+
signal.removeEventListener("abort", onAbort);
|
|
799
|
+
reject(e);
|
|
800
|
+
});
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
async teardown() {
|
|
804
|
+
for (const t of this.timers) clearInterval(t);
|
|
805
|
+
const reason = this.stopReason ?? {
|
|
806
|
+
kind: "failed",
|
|
807
|
+
detail: "unknown"
|
|
808
|
+
};
|
|
809
|
+
const agent = this.agent;
|
|
810
|
+
if (agent) {
|
|
811
|
+
this.conn?.close();
|
|
812
|
+
agent.stdin.end();
|
|
813
|
+
const grace = this.deps.stopGraceMs ?? 5e3;
|
|
814
|
+
const exited = await Promise.race([agent.exited.then(() => true), new Promise((r) => setTimeout(() => r(false), grace).unref())]);
|
|
815
|
+
agent.killTree();
|
|
816
|
+
if (!exited) this.log(`killed ${this.spec.file} (pid ${agent.pid}) after ${grace} ms`);
|
|
817
|
+
}
|
|
818
|
+
if (this.sessionId) {
|
|
819
|
+
const why = describeStop(reason);
|
|
820
|
+
if (reason.kind !== "session-gone") await this.tell(`${await this.who()} stopped: ${why}. Its session is now offline.`);
|
|
821
|
+
await this.client["session.unregister"]({ sessionId: this.sessionId }).catch(() => void 0);
|
|
822
|
+
}
|
|
823
|
+
rmSync(this.spec.record, { force: true });
|
|
824
|
+
rmSync(stopRequestPath(this.spec.record), { force: true });
|
|
825
|
+
this.log(`stopped: ${describeStop(reason)}`);
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
/**
|
|
829
|
+
* The id of a session config option in the `mode` category (or with id `mode`) that offers `value`,
|
|
830
|
+
* from `session/new`'s `configOptions`. Undefined when there is none.
|
|
831
|
+
*/
|
|
832
|
+
function modeConfigId(options, value) {
|
|
833
|
+
if (!Array.isArray(options)) return void 0;
|
|
834
|
+
for (const o of options) {
|
|
835
|
+
if (o?.category !== "mode" && o?.id !== "mode") continue;
|
|
836
|
+
const values = (Array.isArray(o.options) ? o.options : []).flatMap((x) => {
|
|
837
|
+
const item = x;
|
|
838
|
+
return Array.isArray(item?.options) ? item.options : [item];
|
|
839
|
+
});
|
|
840
|
+
if (typeof o.id === "string" && values.some((v) => v?.value === value)) return o.id;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/** Set on every agent the ACP host starts. `conveno hook` exits at once when it is set. */
|
|
844
|
+
const ACP_WORKER_ENV = "CONVENO_ACP_WORKER";
|
|
845
|
+
/**
|
|
846
|
+
* End `pid` and its descendants. POSIX: the agent leads its own process group (it was started
|
|
847
|
+
* detached), so the whole group gets SIGKILL. Windows has no process groups; `taskkill /T` ends the
|
|
848
|
+
* tree by parent pid. Never throws: the process may be gone already.
|
|
849
|
+
*/
|
|
850
|
+
function killProcessTree(pid, platform = process.platform) {
|
|
851
|
+
if (platform === "win32") {
|
|
852
|
+
spawnSync("taskkill", [
|
|
853
|
+
"/PID",
|
|
854
|
+
String(pid),
|
|
855
|
+
"/T",
|
|
856
|
+
"/F"
|
|
857
|
+
], {
|
|
858
|
+
stdio: "ignore",
|
|
859
|
+
windowsHide: true
|
|
860
|
+
});
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
try {
|
|
864
|
+
process.kill(-pid, "SIGKILL");
|
|
865
|
+
} catch {
|
|
866
|
+
try {
|
|
867
|
+
process.kill(pid, "SIGKILL");
|
|
868
|
+
} catch {}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Start a CLI's ACP server with piped stdio. On POSIX it gets its own process group, so stopping
|
|
873
|
+
* it ends the tools it started too. Whatever happens to the host, the server's stdin closes when
|
|
874
|
+
* the host exits, and an ACP server on stdio exits when its input closes (OpenCode and the
|
|
875
|
+
* SDK-based adapters document this), so a crashed host leaves no worker behind.
|
|
876
|
+
*/
|
|
877
|
+
function startAgentProcess(opts) {
|
|
878
|
+
const platform = opts.platform ?? process.platform;
|
|
879
|
+
return new Promise((resolve, reject) => {
|
|
880
|
+
const child = spawn(opts.file, [...opts.args], {
|
|
881
|
+
cwd: opts.cwd,
|
|
882
|
+
stdio: [
|
|
883
|
+
"pipe",
|
|
884
|
+
"pipe",
|
|
885
|
+
"pipe"
|
|
886
|
+
],
|
|
887
|
+
detached: platform !== "win32",
|
|
888
|
+
windowsHide: true,
|
|
889
|
+
env: {
|
|
890
|
+
...opts.env ?? process.env,
|
|
891
|
+
[ACP_WORKER_ENV]: "1"
|
|
892
|
+
},
|
|
893
|
+
...opts.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
894
|
+
});
|
|
895
|
+
const exited = new Promise((r) => {
|
|
896
|
+
child.once("exit", (code, signal) => r({
|
|
897
|
+
code,
|
|
898
|
+
signal
|
|
899
|
+
}));
|
|
900
|
+
});
|
|
901
|
+
child.stderr.pipe(opts.stderr ?? process.stderr, { end: false });
|
|
902
|
+
child.stdin.on("error", () => void 0);
|
|
903
|
+
child.once("error", (e) => reject(/* @__PURE__ */ new Error(`Could not start ${opts.file}: ${e.message}`)));
|
|
904
|
+
child.once("spawn", () => {
|
|
905
|
+
const pid = child.pid;
|
|
906
|
+
if (pid === void 0) {
|
|
907
|
+
reject(/* @__PURE__ */ new Error(`${opts.file} has no pid.`));
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
resolve({
|
|
911
|
+
pid,
|
|
912
|
+
stdin: child.stdin,
|
|
913
|
+
stdout: child.stdout,
|
|
914
|
+
exited,
|
|
915
|
+
killTree: () => killProcessTree(pid, platform)
|
|
916
|
+
});
|
|
917
|
+
});
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
/** An agent that throws gets "Internal error" from the SDK, with its own words in `data.details`. */
|
|
921
|
+
const errText = (e) => {
|
|
922
|
+
const details = e?.data?.details;
|
|
923
|
+
if (typeof details === "string" && details.trim() !== "") return details.trim();
|
|
924
|
+
return e instanceof Error ? e.message : String(e);
|
|
925
|
+
};
|
|
926
|
+
function withTimeout(p, ms, what) {
|
|
927
|
+
let timer;
|
|
928
|
+
const late = new Promise((_, reject) => {
|
|
929
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} timed out after ${ms / 1e3}s.`)), ms);
|
|
930
|
+
});
|
|
931
|
+
return Promise.race([p, late]).finally(() => clearTimeout(timer));
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Start `cli`'s ACP server, read the models and efforts it offers, and stop it (with everything it
|
|
935
|
+
* started). Never throws: a failure comes back as a message fit to show.
|
|
936
|
+
*/
|
|
937
|
+
async function probeModelMenu(opts) {
|
|
938
|
+
const platform = opts.platform;
|
|
939
|
+
const spec = SPAWN_TABLE[opts.cli]?.acp;
|
|
940
|
+
let launch;
|
|
941
|
+
let timeout = opts.timeoutMs ?? 6e4;
|
|
942
|
+
if (opts.command) launch = {
|
|
943
|
+
file: opts.command.file,
|
|
944
|
+
args: opts.command.args
|
|
945
|
+
};
|
|
946
|
+
else {
|
|
947
|
+
if (!spec) return {
|
|
948
|
+
ok: false,
|
|
949
|
+
message: `${opts.cli} cannot run in the background.`
|
|
950
|
+
};
|
|
951
|
+
const res = resolveAcpProgram(opts.cli, spec, {
|
|
952
|
+
env: opts.env,
|
|
953
|
+
which: opts.which ?? ((name) => findOnPath(name, opts.env, platform)),
|
|
954
|
+
npxConsent: opts.npxConsent
|
|
955
|
+
});
|
|
956
|
+
if (!res.ok) return {
|
|
957
|
+
ok: false,
|
|
958
|
+
message: res.reason === "no-npx" ? `${opts.cli} needs npx to start, and npx was not found. Install Node.js.` : `${opts.cli} is not installed for background workers. Run conveno init to set it up.`
|
|
959
|
+
};
|
|
960
|
+
if (res.run.source.startsWith("npx:") && opts.timeoutMs === void 0) timeout = NPX_SETUP_TIMEOUT_MS;
|
|
961
|
+
launch = planProgram(res.run.program, [...res.run.args, ...spec.args], {
|
|
962
|
+
platform,
|
|
963
|
+
env: opts.env
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
const CANCELLED = "Cancelled.";
|
|
967
|
+
if (opts.signal?.aborted) return {
|
|
968
|
+
ok: false,
|
|
969
|
+
message: CANCELLED
|
|
970
|
+
};
|
|
971
|
+
let agent;
|
|
972
|
+
let onAbort;
|
|
973
|
+
const cancelled = new Promise((_, reject) => {
|
|
974
|
+
onAbort = () => {
|
|
975
|
+
agent?.killTree();
|
|
976
|
+
reject(/* @__PURE__ */ new Error(CANCELLED));
|
|
977
|
+
};
|
|
978
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
979
|
+
});
|
|
980
|
+
cancelled.catch(() => void 0);
|
|
981
|
+
try {
|
|
982
|
+
agent = await startAgentProcess({
|
|
983
|
+
file: launch.file,
|
|
984
|
+
args: launch.args,
|
|
985
|
+
cwd: opts.home,
|
|
986
|
+
env: opts.env,
|
|
987
|
+
platform,
|
|
988
|
+
stderr: new Writable({ write: (_c, _e, done) => done() }),
|
|
989
|
+
...launch.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
990
|
+
});
|
|
991
|
+
if (opts.signal?.aborted) return {
|
|
992
|
+
ok: false,
|
|
993
|
+
message: CANCELLED
|
|
994
|
+
};
|
|
995
|
+
const gone = agent.exited.then(({ code, signal }) => {
|
|
996
|
+
throw new Error(`${opts.cli} stopped before it answered (${signal ?? `exit ${code}`}).`);
|
|
997
|
+
});
|
|
998
|
+
gone.catch(() => void 0);
|
|
999
|
+
const conn = client({ name: "conveno" }).connect(ndJsonStream(Writable.toWeb(agent.stdin), Readable.toWeb(agent.stdout)));
|
|
1000
|
+
const step = (p, what) => Promise.race([
|
|
1001
|
+
withTimeout(p, timeout, what),
|
|
1002
|
+
gone,
|
|
1003
|
+
cancelled
|
|
1004
|
+
]);
|
|
1005
|
+
await step(conn.agent.request(methods.agent.initialize, {
|
|
1006
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
1007
|
+
clientCapabilities: {
|
|
1008
|
+
fs: {
|
|
1009
|
+
readTextFile: false,
|
|
1010
|
+
writeTextFile: false
|
|
1011
|
+
},
|
|
1012
|
+
terminal: false
|
|
1013
|
+
},
|
|
1014
|
+
clientInfo: {
|
|
1015
|
+
name: "conveno",
|
|
1016
|
+
version: "probe"
|
|
1017
|
+
}
|
|
1018
|
+
}), "initialize");
|
|
1019
|
+
const created = await step(conn.agent.request(methods.agent.session.new, {
|
|
1020
|
+
cwd: opts.home,
|
|
1021
|
+
mcpServers: []
|
|
1022
|
+
}), "session/new");
|
|
1023
|
+
const at = (opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1024
|
+
return {
|
|
1025
|
+
ok: true,
|
|
1026
|
+
menu: menuFromConfigOptions(created.configOptions, at)
|
|
1027
|
+
};
|
|
1028
|
+
} catch (e) {
|
|
1029
|
+
return {
|
|
1030
|
+
ok: false,
|
|
1031
|
+
message: opts.signal?.aborted ? CANCELLED : errText(e)
|
|
1032
|
+
};
|
|
1033
|
+
} finally {
|
|
1034
|
+
if (onAbort) opts.signal?.removeEventListener("abort", onAbort);
|
|
1035
|
+
agent?.killTree();
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* `conveno acp-host <launch file>`: read and delete the launch file, connect to the daemon and
|
|
1040
|
+
* drive the worker until it stops. Returns the exit code.
|
|
1041
|
+
*/
|
|
1042
|
+
async function runAcpHostFromFile(path, opts = {}) {
|
|
1043
|
+
const spec = takeAcpLaunchFile(path);
|
|
1044
|
+
const client = await connect({
|
|
1045
|
+
kind: "adapter",
|
|
1046
|
+
autoStart: true,
|
|
1047
|
+
...opts.daemonEntry ? { daemonEntry: opts.daemonEntry } : {},
|
|
1048
|
+
...opts.dataDir ? { dataDir: opts.dataDir } : {},
|
|
1049
|
+
...opts.socketPath ? { socketPath: opts.socketPath } : {}
|
|
1050
|
+
});
|
|
1051
|
+
try {
|
|
1052
|
+
return await runAcpHost(spec, {
|
|
1053
|
+
client,
|
|
1054
|
+
startAgent: (s) => startAgentProcess({
|
|
1055
|
+
file: s.file,
|
|
1056
|
+
args: s.args,
|
|
1057
|
+
cwd: s.cwd,
|
|
1058
|
+
...s.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
1059
|
+
})
|
|
1060
|
+
});
|
|
1061
|
+
} finally {
|
|
1062
|
+
await client.close().catch(() => void 0);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
export { stopRequestPath as i, probeModelMenu as n, runAcpHostFromFile as r, killProcessTree as t };
|