@jacoblee93/agent-overwatch 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +45 -0
- package/README.md +33 -2
- package/config.example.json +44 -0
- package/dist/acp/connection.js +175 -0
- package/dist/acp/types.js +23 -0
- package/dist/acp-session.js +212 -0
- package/dist/agents.js +111 -0
- package/dist/approvals.js +70 -0
- package/dist/auth.js +71 -0
- package/dist/bridge.js +103 -0
- package/dist/cli.js +612 -0
- package/dist/config.js +171 -0
- package/dist/daemon.js +191 -0
- package/dist/devices.js +82 -0
- package/dist/dirs.js +107 -0
- package/dist/errors.js +8 -0
- package/dist/events.js +38 -0
- package/dist/github.js +244 -0
- package/dist/http.js +63 -0
- package/dist/linear.js +105 -0
- package/dist/mock-agent.js +242 -0
- package/dist/notify.js +32 -0
- package/dist/pairing.js +166 -0
- package/dist/pending.js +108 -0
- package/dist/pki.js +94 -0
- package/dist/push.js +287 -0
- package/dist/qr.js +304 -0
- package/dist/questions.js +117 -0
- package/dist/relay.js +80 -0
- package/dist/server.js +256 -0
- package/dist/servers.js +92 -0
- package/dist/sessions.js +691 -0
- package/dist/summaries.js +70 -0
- package/dist/tailscale.js +51 -0
- package/dist/thread-store.js +74 -0
- package/dist/transcript.js +167 -0
- package/dist/version.js +4 -0
- package/dist/worktrees.js +157 -0
- package/dist/x509.js +144 -0
- package/package.json +63 -3
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Threads: one agent session each, with its transcript, its settings, and what it's
|
|
3
|
+
* waiting on you for. The SessionManager ties together the agent sessions
|
|
4
|
+
* (acp-session.ts), the transcript (transcript.ts), pending approvals and questions
|
|
5
|
+
* (pending.ts) and saving to disk (thread-store.ts), and tells listeners when a
|
|
6
|
+
* thread needs you.
|
|
7
|
+
*/
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { RpcRequestError } from "./acp/connection.js";
|
|
12
|
+
import { AgentSession } from "./acp-session.js";
|
|
13
|
+
import { autoAllowReason, rememberableCommand, withRememberedCommand } from "./approvals.js";
|
|
14
|
+
import { agentKind, overwatchHome, updateConfigFile, WATCH_PROMPT } from "./config.js";
|
|
15
|
+
import { HttpError } from "./errors.js";
|
|
16
|
+
import { PendingInputs } from "./pending.js";
|
|
17
|
+
import { describeQuestions } from "./questions.js";
|
|
18
|
+
import { ThreadStore } from "./thread-store.js";
|
|
19
|
+
import * as transcript from "./transcript.js";
|
|
20
|
+
import { clip, MAX_TRANSCRIPT_ITEMS } from "./transcript.js";
|
|
21
|
+
import { createWorktree, removeWorktree } from "./worktrees.js";
|
|
22
|
+
export { toSettings } from "./acp-session.js";
|
|
23
|
+
export { findLinks } from "./transcript.js";
|
|
24
|
+
const DAY_MS = 86_400_000;
|
|
25
|
+
const isBusy = (s) => s === "working" || s === "starting" || s === "needs_input";
|
|
26
|
+
export class SessionManager {
|
|
27
|
+
threads = new Map();
|
|
28
|
+
live = new Map();
|
|
29
|
+
pending = new PendingInputs();
|
|
30
|
+
/** Recent tool calls' raw input (`threadId:toolCallId`), for agents that only send it on the tool call, not the approval request. */
|
|
31
|
+
toolInputs = new Map();
|
|
32
|
+
needsInputListeners = [];
|
|
33
|
+
/** Each agent's settings as a fresh session reports them (i.e. its defaults). */
|
|
34
|
+
agentDefaults = new Map();
|
|
35
|
+
probes = new Map();
|
|
36
|
+
config;
|
|
37
|
+
feed;
|
|
38
|
+
log;
|
|
39
|
+
store;
|
|
40
|
+
constructor(config, feed, log = console.log, persistPath = join(overwatchHome(), "threads.json")) {
|
|
41
|
+
this.config = config;
|
|
42
|
+
this.feed = feed;
|
|
43
|
+
this.log = log;
|
|
44
|
+
this.store = new ThreadStore(persistPath, log);
|
|
45
|
+
this.restore();
|
|
46
|
+
for (const [id, settings] of Object.entries(this.store.loadAgentDefaults()))
|
|
47
|
+
this.agentDefaults.set(id, settings);
|
|
48
|
+
this.prune();
|
|
49
|
+
setInterval(() => this.prune(), 3_600_000).unref();
|
|
50
|
+
}
|
|
51
|
+
onNeedsInput(fn) {
|
|
52
|
+
this.needsInputListeners.push(fn);
|
|
53
|
+
}
|
|
54
|
+
// ---- Queries ------------------------------------------------------------
|
|
55
|
+
listThreads() {
|
|
56
|
+
return [...this.threads.values()]
|
|
57
|
+
.filter((t) => t.status !== "closed")
|
|
58
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
59
|
+
.map((t) => this.summarize(t));
|
|
60
|
+
}
|
|
61
|
+
getThread(id, limit = 120) {
|
|
62
|
+
const t = this.mustGet(id);
|
|
63
|
+
return {
|
|
64
|
+
...this.summarize(t),
|
|
65
|
+
directoryId: t.directoryId,
|
|
66
|
+
cwd: t.cwd,
|
|
67
|
+
createdAt: t.createdAt,
|
|
68
|
+
stopReason: t.stopReason,
|
|
69
|
+
pendingInput: this.pending.forThread(id),
|
|
70
|
+
settings: t.settings ?? [],
|
|
71
|
+
canReply: this.canReply(t),
|
|
72
|
+
transcript: t.transcript.slice(-Math.max(1, Math.min(limit, MAX_TRANSCRIPT_ITEMS))),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** Everything agents are waiting on you for, oldest first. */
|
|
76
|
+
listPending() {
|
|
77
|
+
return this.pending.list();
|
|
78
|
+
}
|
|
79
|
+
/** Number of agent processes currently attached (for diagnostics/tests). */
|
|
80
|
+
get liveAgentCount() {
|
|
81
|
+
return this.live.size;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Threads linked to a PR or issue: it's in their links, or (for a PR) the thread's own
|
|
85
|
+
* worktree branch is the PR's branch.
|
|
86
|
+
*/
|
|
87
|
+
threadsLinkedTo(kind, id, pr) {
|
|
88
|
+
return [...this.threads.values()]
|
|
89
|
+
.filter((t) => t.status !== "closed")
|
|
90
|
+
.filter((t) => t.links?.some((l) => l.kind === kind && l.id === id) || (pr && t.worktree?.branch === pr.branch))
|
|
91
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
92
|
+
.map((t) => t.id);
|
|
93
|
+
}
|
|
94
|
+
// ---- Commands -----------------------------------------------------------
|
|
95
|
+
/**
|
|
96
|
+
* The settings a new thread with this agent can pick from (model, effort,
|
|
97
|
+
* mode), with the agent's defaults as `currentValue`. Learned from the last
|
|
98
|
+
* session the agent started; if there's none yet, starts the agent once,
|
|
99
|
+
* opens a session to read them, and stops it.
|
|
100
|
+
*/
|
|
101
|
+
async agentSettings(agentId) {
|
|
102
|
+
const agent = this.config.agents.find((a) => a.id === agentId);
|
|
103
|
+
if (!agent)
|
|
104
|
+
throw new HttpError(404, `unknown agent "${agentId}"`);
|
|
105
|
+
const known = this.agentDefaults.get(agentId);
|
|
106
|
+
if (known)
|
|
107
|
+
return known;
|
|
108
|
+
let probe = this.probes.get(agentId);
|
|
109
|
+
if (!probe) {
|
|
110
|
+
const cwd = this.config.directories[0]?.path ?? homedir();
|
|
111
|
+
probe = AgentSession.readDefaults(agent, cwd, this.log)
|
|
112
|
+
.then((settings) => {
|
|
113
|
+
this.rememberAgentDefaults(agent.id, settings);
|
|
114
|
+
return settings;
|
|
115
|
+
})
|
|
116
|
+
.finally(() => this.probes.delete(agentId));
|
|
117
|
+
this.probes.set(agentId, probe);
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
return await probe;
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
throw new HttpError(502, `couldn't start ${agent.name} to read its settings: ${e.message}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async startThread(agentId, directoryId, prompt, settings = {}, opts = {}) {
|
|
127
|
+
const agent = this.config.agents.find((a) => a.id === agentId);
|
|
128
|
+
if (!agent)
|
|
129
|
+
throw new HttpError(400, `unknown agent "${agentId}"`);
|
|
130
|
+
const ws = this.config.directories.find((w) => w.id === directoryId);
|
|
131
|
+
if (!ws)
|
|
132
|
+
throw new HttpError(400, `unknown directory "${directoryId}"`);
|
|
133
|
+
const text = prompt.trim();
|
|
134
|
+
if (!text)
|
|
135
|
+
throw new HttpError(400, "prompt is required");
|
|
136
|
+
// A short title (e.g. "PR #42 · add dark mode") when the prompt opens with boilerplate context.
|
|
137
|
+
const title = clip((opts.title?.trim() || text).replace(/\s+/g, " "), 60);
|
|
138
|
+
// "New branch": its own worktree, so parallel agents in one repo don't collide.
|
|
139
|
+
let worktree;
|
|
140
|
+
let cwd = ws.path;
|
|
141
|
+
if (opts.worktree) {
|
|
142
|
+
try {
|
|
143
|
+
({ worktree, cwd } = await createWorktree(ws.path, opts.title?.trim() || text, opts.branch?.trim() || undefined));
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
throw new HttpError(400, `couldn't create a branch: ${e.message}`);
|
|
147
|
+
}
|
|
148
|
+
this.log(`worktree ${worktree.path} on ${worktree.branch}`);
|
|
149
|
+
}
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
const t = {
|
|
152
|
+
id: randomUUID(),
|
|
153
|
+
agentId: agent.id,
|
|
154
|
+
agentName: agent.name,
|
|
155
|
+
directoryId: ws.id,
|
|
156
|
+
directoryName: ws.name,
|
|
157
|
+
cwd,
|
|
158
|
+
worktree,
|
|
159
|
+
title,
|
|
160
|
+
status: "starting",
|
|
161
|
+
createdAt: now,
|
|
162
|
+
updatedAt: now,
|
|
163
|
+
transcript: [],
|
|
164
|
+
};
|
|
165
|
+
this.threads.set(t.id, t);
|
|
166
|
+
transcript.push(t, { kind: "user", text });
|
|
167
|
+
this.collectLinks(t, text);
|
|
168
|
+
this.changed(t);
|
|
169
|
+
// Connect + prompt in the background; the watch shouldn't wait on model latency.
|
|
170
|
+
void (async () => {
|
|
171
|
+
try {
|
|
172
|
+
const session = await this.connect(t, agent);
|
|
173
|
+
await this.applyWanted(t, session, settings);
|
|
174
|
+
this.runPrompt(t, text);
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
this.fail(t, e);
|
|
178
|
+
}
|
|
179
|
+
})();
|
|
180
|
+
return this.summarize(t);
|
|
181
|
+
}
|
|
182
|
+
async sendPrompt(threadId, text) {
|
|
183
|
+
const t = this.mustGet(threadId);
|
|
184
|
+
const body = text.trim();
|
|
185
|
+
if (!body)
|
|
186
|
+
throw new HttpError(400, "text is required");
|
|
187
|
+
if (isBusy(t.status))
|
|
188
|
+
throw new HttpError(409, "agent is still working; cancel it first or wait for its turn to end");
|
|
189
|
+
if (t.status === "closed")
|
|
190
|
+
throw new HttpError(409, "thread is closed");
|
|
191
|
+
if (!this.live.has(t.id)) {
|
|
192
|
+
const agent = this.resumable(t);
|
|
193
|
+
t.status = "starting";
|
|
194
|
+
transcript.push(t, { kind: "user", text: body });
|
|
195
|
+
this.changed(t);
|
|
196
|
+
try {
|
|
197
|
+
await this.reconnect(t, agent);
|
|
198
|
+
}
|
|
199
|
+
catch (e) {
|
|
200
|
+
this.fail(t, e);
|
|
201
|
+
throw new HttpError(502, `could not resume session: ${e.message}`);
|
|
202
|
+
}
|
|
203
|
+
this.runPrompt(t, body);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
transcript.push(t, { kind: "user", text: body });
|
|
207
|
+
this.runPrompt(t, body);
|
|
208
|
+
}
|
|
209
|
+
async setSetting(threadId, settingId, value) {
|
|
210
|
+
const t = this.mustGet(threadId);
|
|
211
|
+
if (t.status === "closed")
|
|
212
|
+
throw new HttpError(409, "thread is closed");
|
|
213
|
+
const known = t.settings?.find((x) => x.id === settingId);
|
|
214
|
+
if (!known)
|
|
215
|
+
throw new HttpError(400, `unknown setting "${settingId}"`);
|
|
216
|
+
if (!known.options.some((o) => o.value === value))
|
|
217
|
+
throw new HttpError(400, `"${value}" isn't an option for ${known.name}`);
|
|
218
|
+
// A done or idle thread's agent may have been stopped (Mark done, a bridge restart):
|
|
219
|
+
// resume its session first, like a reply would.
|
|
220
|
+
if (!this.live.has(t.id)) {
|
|
221
|
+
const agent = this.resumable(t);
|
|
222
|
+
try {
|
|
223
|
+
await this.reconnect(t, agent);
|
|
224
|
+
}
|
|
225
|
+
catch (e) {
|
|
226
|
+
throw new HttpError(502, `could not resume session: ${e.message}`);
|
|
227
|
+
}
|
|
228
|
+
if (t.status === "disconnected" || t.status === "error") {
|
|
229
|
+
t.status = "awaiting_reply";
|
|
230
|
+
t.error = undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const session = this.live.get(t.id);
|
|
234
|
+
// Resuming can refresh the list (e.g. a new model's effort levels), so look it up again.
|
|
235
|
+
const setting = t.settings?.find((x) => x.id === settingId);
|
|
236
|
+
const option = setting?.options.find((o) => o.value === value);
|
|
237
|
+
if (!session || !setting || !option)
|
|
238
|
+
throw new HttpError(409, `${known.name} can't be changed right now`);
|
|
239
|
+
await this.applySetting(t, session, setting.id, option.value);
|
|
240
|
+
transcript.push(t, { kind: "system", text: `${setting.name}: ${option.name}` });
|
|
241
|
+
this.changed(t);
|
|
242
|
+
}
|
|
243
|
+
cancel(threadId) {
|
|
244
|
+
const t = this.mustGet(threadId);
|
|
245
|
+
// Per spec: everything the turn was waiting on is answered "cancelled".
|
|
246
|
+
this.pending.cancelThread(t.id);
|
|
247
|
+
this.live.get(t.id)?.cancel();
|
|
248
|
+
transcript.cancelRunningTools(t);
|
|
249
|
+
this.changed(t);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Resolve a thread: it leaves the inbox and the agent ring but stays in the
|
|
253
|
+
* list. A running turn is cancelled. Agents that can resume (session/load)
|
|
254
|
+
* are stopped to free resources; others stay attached so you can still reply.
|
|
255
|
+
*/
|
|
256
|
+
markDone(threadId) {
|
|
257
|
+
const t = this.mustGet(threadId);
|
|
258
|
+
if (t.status === "closed")
|
|
259
|
+
throw new HttpError(409, "thread is closed");
|
|
260
|
+
if (t.status === "starting")
|
|
261
|
+
throw new HttpError(409, "the agent is still starting; try again in a moment");
|
|
262
|
+
if (t.status === "done")
|
|
263
|
+
return;
|
|
264
|
+
if (t.status === "working" || t.status === "needs_input")
|
|
265
|
+
this.cancel(threadId);
|
|
266
|
+
t.status = "done";
|
|
267
|
+
if (t.supportsLoad && t.acpSessionId)
|
|
268
|
+
this.teardown(t.id);
|
|
269
|
+
transcript.push(t, { kind: "system", text: "Marked done" });
|
|
270
|
+
this.changed(t);
|
|
271
|
+
}
|
|
272
|
+
/** Delete: stop the agent and drop the thread. Its worktree goes too, unless that would lose work. */
|
|
273
|
+
async close(threadId) {
|
|
274
|
+
const t = this.mustGet(threadId);
|
|
275
|
+
this.cancel(threadId);
|
|
276
|
+
this.teardown(t.id);
|
|
277
|
+
t.status = "closed";
|
|
278
|
+
this.changed(t);
|
|
279
|
+
return { keptWorktree: await this.cleanUpWorktree(t) };
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Answer an approval with one of its options (null dismisses it). With `remember`, an
|
|
283
|
+
* allow also adds the call's exact command to the approval rules, so it's never asked again.
|
|
284
|
+
* For a question, null skips it (the agent hears you declined).
|
|
285
|
+
*/
|
|
286
|
+
approve(inputId, optionId, remember = false) {
|
|
287
|
+
const answered = this.pending.approve(inputId, optionId, remember);
|
|
288
|
+
if (answered.remember)
|
|
289
|
+
this.rememberCommand(answered.remember);
|
|
290
|
+
this.settle(answered.input, answered.said);
|
|
291
|
+
}
|
|
292
|
+
/** Answer a question from the agent: `{ [questionId or its textField]: value | value[] }`. */
|
|
293
|
+
answer(inputId, answers) {
|
|
294
|
+
const answered = this.pending.answer(inputId, answers);
|
|
295
|
+
this.settle(answered.input, answered.said);
|
|
296
|
+
}
|
|
297
|
+
shutdown() {
|
|
298
|
+
for (const id of this.live.keys())
|
|
299
|
+
this.teardown(id);
|
|
300
|
+
this.store.flush(() => this.threads.values());
|
|
301
|
+
}
|
|
302
|
+
/** Housekeeping: drop done and errored threads that have been idle past the retention window. */
|
|
303
|
+
prune(now = Date.now()) {
|
|
304
|
+
const days = this.config.housekeeping?.doneRetentionDays ?? 7;
|
|
305
|
+
if (!(days > 0))
|
|
306
|
+
return 0;
|
|
307
|
+
let removed = 0;
|
|
308
|
+
for (const t of this.threads.values()) {
|
|
309
|
+
const stale = (t.status === "done" || t.status === "error" || t.status === "closed") && now - t.updatedAt > days * DAY_MS;
|
|
310
|
+
if (!stale)
|
|
311
|
+
continue;
|
|
312
|
+
this.teardown(t.id);
|
|
313
|
+
this.threads.delete(t.id);
|
|
314
|
+
void this.cleanUpWorktree(t);
|
|
315
|
+
removed++;
|
|
316
|
+
}
|
|
317
|
+
if (removed) {
|
|
318
|
+
this.log(`housekeeping: removed ${removed} thread(s) idle for more than ${days} day(s)`);
|
|
319
|
+
this.feed.bump();
|
|
320
|
+
this.store.scheduleSave(() => this.threads.values());
|
|
321
|
+
}
|
|
322
|
+
return removed;
|
|
323
|
+
}
|
|
324
|
+
// ---- Agent sessions -----------------------------------------------------
|
|
325
|
+
/** Start the thread's agent with a new session. */
|
|
326
|
+
async connect(t, agent) {
|
|
327
|
+
const session = await AgentSession.open(this.openOptions(t, agent));
|
|
328
|
+
t.acpSessionId = session.sessionId;
|
|
329
|
+
t.supportsLoad = session.supportsLoad;
|
|
330
|
+
t.settings = session.settings;
|
|
331
|
+
this.rememberAgentDefaults(agent.id, session.settings);
|
|
332
|
+
this.live.set(t.id, session);
|
|
333
|
+
return session;
|
|
334
|
+
}
|
|
335
|
+
/** Start the thread's agent again and load its session, keeping the settings the thread was using. */
|
|
336
|
+
async reconnect(t, agent) {
|
|
337
|
+
// Agents may load a session with their defaults: note what the thread had.
|
|
338
|
+
const chosen = Object.fromEntries((t.settings ?? []).map((x) => [x.id, x.currentValue]));
|
|
339
|
+
const session = await AgentSession.open({ ...this.openOptions(t, agent), resume: t.acpSessionId });
|
|
340
|
+
t.supportsLoad = session.supportsLoad;
|
|
341
|
+
if (session.settings.length)
|
|
342
|
+
t.settings = session.settings;
|
|
343
|
+
this.live.set(t.id, session);
|
|
344
|
+
// In display order, looking each one up again: restoring the model can change the effort choices.
|
|
345
|
+
for (const id of (t.settings ?? []).map((x) => x.id)) {
|
|
346
|
+
const setting = t.settings?.find((x) => x.id === id);
|
|
347
|
+
const value = chosen[id];
|
|
348
|
+
if (!setting || !value || setting.currentValue === value || !setting.options.some((o) => o.value === value))
|
|
349
|
+
continue;
|
|
350
|
+
try {
|
|
351
|
+
await this.applySetting(t, session, id, value);
|
|
352
|
+
}
|
|
353
|
+
catch (e) {
|
|
354
|
+
transcript.push(t, { kind: "system", text: `Couldn't restore ${setting.name}: ${e.message}` });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return session;
|
|
358
|
+
}
|
|
359
|
+
/** Change a setting, keeping the thread's copy current (the agent may send back the whole new set). */
|
|
360
|
+
async applySetting(t, session, id, value) {
|
|
361
|
+
const all = await session.setSetting(id, value);
|
|
362
|
+
t.settings = all ?? (t.settings ?? []).map((s) => (s.id === id ? { ...s, currentValue: value } : s));
|
|
363
|
+
}
|
|
364
|
+
/** Settings picked for a new thread, in display order (the model first: it can change the effort choices). */
|
|
365
|
+
async applyWanted(t, session, wanted) {
|
|
366
|
+
for (const id of (t.settings ?? []).map((x) => x.id)) {
|
|
367
|
+
const value = wanted[id];
|
|
368
|
+
const setting = t.settings?.find((x) => x.id === id);
|
|
369
|
+
if (!value || !setting || setting.currentValue === value)
|
|
370
|
+
continue;
|
|
371
|
+
if (!setting.options.some((o) => o.value === value)) {
|
|
372
|
+
transcript.push(t, { kind: "system", text: `${setting.name} "${value}" isn't available; using the agent's default.` });
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
await this.applySetting(t, session, id, value);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
openOptions(t, agent) {
|
|
379
|
+
// Agents that accept extra system-prompt text are told their replies are read on a watch.
|
|
380
|
+
const watchPrompt = this.config.watchPrompt === undefined ? WATCH_PROMPT : this.config.watchPrompt;
|
|
381
|
+
return {
|
|
382
|
+
agent,
|
|
383
|
+
cwd: t.cwd,
|
|
384
|
+
tag: `[${agent.id}:${t.id.slice(0, 8)}]`,
|
|
385
|
+
log: this.log,
|
|
386
|
+
systemPrompt: watchPrompt || undefined,
|
|
387
|
+
handlers: {
|
|
388
|
+
update: (u) => this.applyUpdate(t, u),
|
|
389
|
+
approval: (req) => this.requestApproval(t, req),
|
|
390
|
+
question: (req) => this.askQuestion(t, req),
|
|
391
|
+
closed: (session, reason) => this.agentExited(t, session, reason),
|
|
392
|
+
},
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
/** The agent for a thread whose process is gone, if its session can be resumed. */
|
|
396
|
+
resumable(t) {
|
|
397
|
+
if (!t.supportsLoad || !t.acpSessionId)
|
|
398
|
+
throw new HttpError(409, "the agent process is gone and this agent can't resume sessions");
|
|
399
|
+
const agent = this.config.agents.find((a) => a.id === t.agentId);
|
|
400
|
+
const ws = this.config.directories.find((w) => w.id === t.directoryId);
|
|
401
|
+
if (!agent || !ws)
|
|
402
|
+
throw new HttpError(409, "agent or directory no longer configured");
|
|
403
|
+
return agent;
|
|
404
|
+
}
|
|
405
|
+
runPrompt(t, text) {
|
|
406
|
+
const session = this.live.get(t.id);
|
|
407
|
+
if (!session) {
|
|
408
|
+
this.fail(t, new Error("agent is not connected"));
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
t.status = "working";
|
|
412
|
+
t.stopReason = undefined;
|
|
413
|
+
t.error = undefined;
|
|
414
|
+
t.turnToolIds = [];
|
|
415
|
+
this.changed(t);
|
|
416
|
+
session
|
|
417
|
+
.prompt(text)
|
|
418
|
+
.then((stopReason) => {
|
|
419
|
+
t.stopReason = stopReason;
|
|
420
|
+
if (t.status === "closed" || t.status === "done")
|
|
421
|
+
return;
|
|
422
|
+
t.status = "awaiting_reply";
|
|
423
|
+
if (stopReason && stopReason !== "end_turn") {
|
|
424
|
+
transcript.push(t, { kind: "system", text: `Turn ended: ${stopReason.replace(/_/g, " ")}` });
|
|
425
|
+
}
|
|
426
|
+
this.collectLinks(t, transcript.plainText(t));
|
|
427
|
+
const summary = transcript.endTurn(t);
|
|
428
|
+
if (summary)
|
|
429
|
+
transcript.push(t, { kind: "summary", text: summary });
|
|
430
|
+
this.changed(t);
|
|
431
|
+
if (stopReason !== "cancelled") {
|
|
432
|
+
this.emit({
|
|
433
|
+
kind: "reply",
|
|
434
|
+
threadId: t.id,
|
|
435
|
+
threadTitle: t.title,
|
|
436
|
+
agentName: t.agentName,
|
|
437
|
+
message: clip(transcript.lastAgentText(t) || "Finished its turn", 180),
|
|
438
|
+
summary,
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
})
|
|
442
|
+
.catch((e) => {
|
|
443
|
+
if (t.status === "closed" || t.status === "done")
|
|
444
|
+
return;
|
|
445
|
+
this.fail(t, e);
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
applyUpdate(t, u) {
|
|
449
|
+
switch (u.kind) {
|
|
450
|
+
case "text":
|
|
451
|
+
transcript.appendChunk(t, u.role, u.text);
|
|
452
|
+
break;
|
|
453
|
+
case "tool":
|
|
454
|
+
this.noteTool(t, u.call);
|
|
455
|
+
break;
|
|
456
|
+
case "plan":
|
|
457
|
+
transcript.setPlan(t, u.entries);
|
|
458
|
+
break;
|
|
459
|
+
case "settings":
|
|
460
|
+
t.settings = u.settings;
|
|
461
|
+
break;
|
|
462
|
+
case "mode": {
|
|
463
|
+
const mode = t.settings?.find((x) => x.category === "mode");
|
|
464
|
+
if (mode)
|
|
465
|
+
mode.currentValue = u.modeId;
|
|
466
|
+
break;
|
|
467
|
+
}
|
|
468
|
+
case "title":
|
|
469
|
+
t.title = clip(u.title, 80);
|
|
470
|
+
break;
|
|
471
|
+
}
|
|
472
|
+
this.changed(t, false);
|
|
473
|
+
}
|
|
474
|
+
noteTool(t, tc) {
|
|
475
|
+
transcript.upsertTool(t, tc);
|
|
476
|
+
if (tc.rawInput == null)
|
|
477
|
+
return;
|
|
478
|
+
const key = `${t.id}:${tc.toolCallId}`;
|
|
479
|
+
this.toolInputs.delete(key);
|
|
480
|
+
this.toolInputs.set(key, tc.rawInput);
|
|
481
|
+
if (this.toolInputs.size > 500)
|
|
482
|
+
this.toolInputs.delete(this.toolInputs.keys().next().value);
|
|
483
|
+
}
|
|
484
|
+
/** A tool call that needs approving: auto-approved by the rules, or it waits for you. */
|
|
485
|
+
requestApproval(t, req) {
|
|
486
|
+
const tc = req.toolCall;
|
|
487
|
+
if (tc.toolCallId)
|
|
488
|
+
this.noteTool(t, tc);
|
|
489
|
+
const existing = tc.toolCallId ? transcript.toolItem(t, tc.toolCallId) : undefined;
|
|
490
|
+
const allowOnce = req.options.find((o) => o.kind === "allow_once");
|
|
491
|
+
const kind = tc.kind ?? existing?.toolKind;
|
|
492
|
+
const rawInput = tc.rawInput ?? this.toolInputs.get(`${t.id}:${tc.toolCallId}`) ?? undefined;
|
|
493
|
+
// Approval rules: answer routine requests (reads, allow-listed commands) without bothering you.
|
|
494
|
+
if (allowOnce && autoAllowReason(this.config, kind, rawInput)) {
|
|
495
|
+
transcript.push(t, { kind: "system", text: `Auto-approved: ${tc.title ?? existing?.title ?? "tool call"}` });
|
|
496
|
+
this.changed(t, false);
|
|
497
|
+
return Promise.resolve(allowOnce.optionId);
|
|
498
|
+
}
|
|
499
|
+
const always = allowOnce ? rememberableCommand(this.config, kind, rawInput) : undefined;
|
|
500
|
+
const { input, done } = this.pending.approval({
|
|
501
|
+
...this.inputBase(t),
|
|
502
|
+
title: tc.title ?? existing?.title ?? "Approval requested",
|
|
503
|
+
toolKind: kind,
|
|
504
|
+
detail: transcript.describeToolCall(tc) ?? existing?.text,
|
|
505
|
+
options: req.options,
|
|
506
|
+
...(always ? { alwaysAllowCommand: always } : {}),
|
|
507
|
+
});
|
|
508
|
+
this.waiting(t, input);
|
|
509
|
+
return done;
|
|
510
|
+
}
|
|
511
|
+
/** The agent asks you something: it waits like an approval does. */
|
|
512
|
+
askQuestion(t, req) {
|
|
513
|
+
const { questions } = req;
|
|
514
|
+
const { input, done } = this.pending.question({
|
|
515
|
+
...this.inputBase(t),
|
|
516
|
+
title: clip(questions.length === 1 ? questions[0].text : req.message || "The agent has questions", 300),
|
|
517
|
+
toolKind: "question",
|
|
518
|
+
detail: questions.length === 1 ? undefined : clip(describeQuestions(questions), 1_000),
|
|
519
|
+
questions,
|
|
520
|
+
}, req.required);
|
|
521
|
+
this.waiting(t, input);
|
|
522
|
+
return done;
|
|
523
|
+
}
|
|
524
|
+
inputBase(t) {
|
|
525
|
+
return { threadId: t.id, threadTitle: t.title, agentName: t.agentName, agentKind: this.kindOf(t.agentId) };
|
|
526
|
+
}
|
|
527
|
+
waiting(t, input) {
|
|
528
|
+
t.status = "needs_input";
|
|
529
|
+
this.changed(t);
|
|
530
|
+
this.emit({ kind: input.kind, threadId: t.id, threadTitle: t.title, agentName: t.agentName, message: input.title, input });
|
|
531
|
+
}
|
|
532
|
+
/** Something it was waiting on was answered: note it in the transcript and carry on. */
|
|
533
|
+
settle(input, said) {
|
|
534
|
+
const t = this.threads.get(input.threadId);
|
|
535
|
+
if (!t)
|
|
536
|
+
return;
|
|
537
|
+
transcript.push(t, { kind: "system", text: said });
|
|
538
|
+
if (t.status === "needs_input" && !this.pending.forThread(t.id))
|
|
539
|
+
t.status = "working";
|
|
540
|
+
this.changed(t);
|
|
541
|
+
}
|
|
542
|
+
agentExited(t, session, reason) {
|
|
543
|
+
// Only the thread's current session counts (not one it has since replaced).
|
|
544
|
+
if (this.live.get(t.id) !== session)
|
|
545
|
+
return;
|
|
546
|
+
this.live.delete(t.id);
|
|
547
|
+
this.pending.cancelThread(t.id);
|
|
548
|
+
// Waiting on you with a resumable session: nothing's lost, the next reply restarts the agent.
|
|
549
|
+
if (t.status === "awaiting_reply" && t.supportsLoad && t.acpSessionId)
|
|
550
|
+
return;
|
|
551
|
+
if (t.status === "closed" || t.status === "error" || t.status === "done")
|
|
552
|
+
return;
|
|
553
|
+
t.status = t.supportsLoad ? "disconnected" : "error";
|
|
554
|
+
if (!t.supportsLoad)
|
|
555
|
+
t.error = reason;
|
|
556
|
+
transcript.push(t, {
|
|
557
|
+
kind: "system",
|
|
558
|
+
text: `Agent process ended (${reason}).${t.supportsLoad ? " Reply to pick up where it left off." : ""}`,
|
|
559
|
+
});
|
|
560
|
+
this.changed(t);
|
|
561
|
+
}
|
|
562
|
+
teardown(id) {
|
|
563
|
+
const session = this.live.get(id);
|
|
564
|
+
if (!session)
|
|
565
|
+
return;
|
|
566
|
+
this.live.delete(id);
|
|
567
|
+
session.close();
|
|
568
|
+
}
|
|
569
|
+
fail(t, e) {
|
|
570
|
+
const msg = e instanceof RpcRequestError ? e.message : String(e?.message ?? e);
|
|
571
|
+
this.log(`[${t.agentId}:${t.id.slice(0, 8)}] error: ${msg}`);
|
|
572
|
+
t.status = "error";
|
|
573
|
+
t.error = clip(msg, 500);
|
|
574
|
+
transcript.push(t, { kind: "system", text: `Error: ${t.error}` });
|
|
575
|
+
this.changed(t);
|
|
576
|
+
this.emit({ kind: "error", threadId: t.id, threadTitle: t.title, agentName: t.agentName, message: t.error });
|
|
577
|
+
}
|
|
578
|
+
// ---- Helpers ------------------------------------------------------------
|
|
579
|
+
/** Add a command to the approval rules, here and in the config file (which the bridge reloads). */
|
|
580
|
+
rememberCommand(command) {
|
|
581
|
+
this.config.approvals = withRememberedCommand(this.config, command);
|
|
582
|
+
try {
|
|
583
|
+
updateConfigFile((c) => {
|
|
584
|
+
c.approvals = withRememberedCommand(c, command);
|
|
585
|
+
});
|
|
586
|
+
this.log(`approvals: always allowing \`${command}\``);
|
|
587
|
+
}
|
|
588
|
+
catch (e) {
|
|
589
|
+
this.log(`couldn't save the approval rule for \`${command}\`: ${e.message}`);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
rememberAgentDefaults(agentId, settings) {
|
|
593
|
+
this.agentDefaults.set(agentId, structuredClone(settings));
|
|
594
|
+
this.store.saveAgentDefaults(Object.fromEntries(this.agentDefaults));
|
|
595
|
+
}
|
|
596
|
+
async cleanUpWorktree(t) {
|
|
597
|
+
if (!t.worktree)
|
|
598
|
+
return undefined;
|
|
599
|
+
const wt = t.worktree;
|
|
600
|
+
t.worktree = undefined;
|
|
601
|
+
try {
|
|
602
|
+
const r = await removeWorktree(wt);
|
|
603
|
+
this.log(r.removed ? `removed worktree ${wt.path}` : `worktree ${r.kept}`);
|
|
604
|
+
return r.kept;
|
|
605
|
+
}
|
|
606
|
+
catch (e) {
|
|
607
|
+
this.log(`couldn't clean up worktree ${wt.path}: ${String(e)}`);
|
|
608
|
+
return `kept ${wt.path}`;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
mustGet(id) {
|
|
612
|
+
const t = this.threads.get(id);
|
|
613
|
+
if (!t)
|
|
614
|
+
throw new HttpError(404, "thread not found");
|
|
615
|
+
return t;
|
|
616
|
+
}
|
|
617
|
+
canReply(t) {
|
|
618
|
+
if (t.status === "awaiting_reply")
|
|
619
|
+
return true;
|
|
620
|
+
if (t.status === "done" && (this.live.has(t.id) || (t.supportsLoad && t.acpSessionId)))
|
|
621
|
+
return true;
|
|
622
|
+
if ((t.status === "disconnected" || t.status === "error") && t.supportsLoad && t.acpSessionId)
|
|
623
|
+
return true;
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
collectLinks(t, text) {
|
|
627
|
+
for (const link of transcript.findLinks(text)) {
|
|
628
|
+
t.links ??= [];
|
|
629
|
+
if (!t.links.some((l) => l.kind === link.kind && l.id === link.id))
|
|
630
|
+
t.links.push(link);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
kindOf(agentId) {
|
|
634
|
+
const agent = this.config.agents.find((a) => a.id === agentId);
|
|
635
|
+
return agent ? agentKind(agent) : "other";
|
|
636
|
+
}
|
|
637
|
+
summarize(t) {
|
|
638
|
+
const pending = this.pending.forThread(t.id);
|
|
639
|
+
return {
|
|
640
|
+
id: t.id,
|
|
641
|
+
title: t.title,
|
|
642
|
+
agentId: t.agentId,
|
|
643
|
+
agentName: t.agentName,
|
|
644
|
+
agentKind: this.kindOf(t.agentId),
|
|
645
|
+
directoryName: t.directoryName,
|
|
646
|
+
status: t.status,
|
|
647
|
+
updatedAt: t.updatedAt,
|
|
648
|
+
preview: transcript.preview(t),
|
|
649
|
+
...(pending ? { pendingInput: { id: pending.id, kind: pending.kind } } : {}),
|
|
650
|
+
error: t.error,
|
|
651
|
+
turnSummary: transcript.latestTurnSummary(t),
|
|
652
|
+
branch: t.worktree?.branch,
|
|
653
|
+
links: t.links ?? [],
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
emit(e) {
|
|
657
|
+
for (const l of this.needsInputListeners) {
|
|
658
|
+
try {
|
|
659
|
+
l(e);
|
|
660
|
+
}
|
|
661
|
+
catch (err) {
|
|
662
|
+
this.log(`needs-input listener failed: ${String(err)}`);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
changed(t, touch = true) {
|
|
667
|
+
if (touch)
|
|
668
|
+
t.updatedAt = Date.now();
|
|
669
|
+
else
|
|
670
|
+
t.updatedAt = Math.max(t.updatedAt, Date.now() - 1);
|
|
671
|
+
this.feed.bump();
|
|
672
|
+
this.store.scheduleSave(() => this.threads.values());
|
|
673
|
+
}
|
|
674
|
+
restore() {
|
|
675
|
+
for (const t of this.store.loadThreads()) {
|
|
676
|
+
// A thread waiting on you is still waiting on you: replying resumes its session.
|
|
677
|
+
// One that was mid-turn was cut off, and says so.
|
|
678
|
+
if (t.status === "awaiting_reply" && t.supportsLoad && t.acpSessionId) {
|
|
679
|
+
// unchanged
|
|
680
|
+
}
|
|
681
|
+
else if (t.status !== "closed" && t.status !== "error" && t.status !== "done") {
|
|
682
|
+
if (isBusy(t.status))
|
|
683
|
+
transcript.push(t, { kind: "system", text: "The bridge restarted mid-turn. Reply to pick up where it left off." });
|
|
684
|
+
t.status = t.supportsLoad && t.acpSessionId ? "disconnected" : "error";
|
|
685
|
+
if (t.status === "error")
|
|
686
|
+
t.error ??= "The bridge restarted, and this agent can't resume sessions.";
|
|
687
|
+
}
|
|
688
|
+
this.threads.set(t.id, t);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|