@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/dist/github.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * GitHub: your open pull requests and their comments, so you can pick one up
3
+ * from the watch ("continue working on this PR").
4
+ *
5
+ * Uses the GitHub CLI (`gh`) and whatever account it's logged in to
6
+ * (`gh auth login` on the Mac). The bridge never sees or stores a GitHub token.
7
+ * `gh` runs with argument lists (no shell); repo names and PR numbers from the
8
+ * watch are validated before they get anywhere near it.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import { git } from "./worktrees.js";
12
+ const runGh = (args) => new Promise((resolve) => execFile("gh", args, { timeout: 20_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, GH_PROMPT_DISABLED: "1" } }, (err, stdout, stderr) => resolve({ ok: !err, out: err ? `${stderr || err.message}`.trim() : stdout })));
13
+ export const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
14
+ export const REPO_RE = /^[A-Za-z0-9_.-]{1,100}$/;
15
+ const MAX_BODY = 8000;
16
+ export class GitHubError extends Error {
17
+ }
18
+ export class GitHubAuthError extends GitHubError {
19
+ }
20
+ /** The request itself can't work (e.g. the directory isn't a GitHub checkout). */
21
+ export class GitHubInputError extends GitHubError {
22
+ }
23
+ /** Bot comments often carry hidden HTML markers; drop them and tidy whitespace. */
24
+ export function cleanBody(s, max = 4000) {
25
+ return (s ?? "")
26
+ .replace(/<!--[\s\S]*?-->/g, "")
27
+ .replace(/\n{3,}/g, "\n\n")
28
+ .trim()
29
+ .slice(0, max);
30
+ }
31
+ const PR_FIELDS = `number title body url isDraft updatedAt repository { nameWithOwner }
32
+ headRefName baseRefName additions deletions changedFiles reviewDecision mergeable
33
+ reviewThreads(first: 100) { nodes { isResolved } }
34
+ commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }`;
35
+ // The search string is a GraphQL variable ($q), never spliced into the query text.
36
+ const SEARCH_QUERY = `query($q: String!) { search(query: $q, type: ISSUE, first: 25) {
37
+ nodes { ... on PullRequest { ${PR_FIELDS} } } } }`;
38
+ const CHECKS_QUERY = `query($owner: String!, $repo: String!, $number: Int!) {
39
+ repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
40
+ commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes {
41
+ __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state } } } } } } } } } }`;
42
+ /** owner/repo from a git remote URL (https or ssh), if it's GitHub. */
43
+ export function parseGitHubRemote(url) {
44
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim());
45
+ return m && OWNER_RE.test(m[1]) && REPO_RE.test(m[2]) ? { owner: m[1], repo: m[2] } : undefined;
46
+ }
47
+ export class GitHubSource {
48
+ run;
49
+ directories;
50
+ authed;
51
+ /** PR lists by search ("" = all your PRs, else "owner/repo"). */
52
+ prCache = new Map();
53
+ commentCache = new Map();
54
+ remotes = new Map(); // directory path → "owner/repo" (lowercase)
55
+ constructor(directories, run = runGh) {
56
+ this.directories = directories;
57
+ this.run = run;
58
+ }
59
+ /** Whether `gh` is installed and logged in (checked in the background, refreshed every 5 minutes). */
60
+ get enabled() {
61
+ if (!this.authed || Date.now() - this.authed.at > 5 * 60_000)
62
+ void this.checkAuth();
63
+ return this.authed?.ok ?? false;
64
+ }
65
+ async checkAuth() {
66
+ const r = await this.run(["auth", "status", "--hostname", "github.com"]);
67
+ this.authed = { at: Date.now(), ok: r.ok };
68
+ return r.ok;
69
+ }
70
+ async json(args) {
71
+ const r = await this.run(args);
72
+ if (!r.ok) {
73
+ if (/auth login|not logged in|authentication/i.test(r.out)) {
74
+ this.authed = { at: Date.now(), ok: false };
75
+ throw new GitHubAuthError("GitHub CLI isn't logged in. Run `gh auth login` on the host.");
76
+ }
77
+ throw new GitHubError(`gh failed: ${r.out.split("\n")[0]?.slice(0, 200)}`);
78
+ }
79
+ try {
80
+ return JSON.parse(r.out);
81
+ }
82
+ catch {
83
+ throw new GitHubError("gh returned something unexpected");
84
+ }
85
+ }
86
+ /** "owner/repo" (lowercase) for each configured directory that's a GitHub checkout. */
87
+ async directoryRepos() {
88
+ const out = new Map();
89
+ for (const d of this.directories()) {
90
+ if (!this.remotes.has(d.path)) {
91
+ const r = await git(["remote", "get-url", "origin"], d.path);
92
+ const parsed = r.ok ? parseGitHubRemote(r.out) : undefined;
93
+ this.remotes.set(d.path, parsed ? `${parsed.owner}/${parsed.repo}`.toLowerCase() : null);
94
+ }
95
+ const repo = this.remotes.get(d.path);
96
+ if (repo && !out.has(repo))
97
+ out.set(repo, d.id);
98
+ }
99
+ return out;
100
+ }
101
+ /**
102
+ * Your open PRs, most recently updated first, with CI, review and merge status (cached for a
103
+ * minute). With a directory: only the PRs in that checkout's GitHub repo.
104
+ */
105
+ async pullRequests(directoryId) {
106
+ let scope = "";
107
+ if (directoryId !== undefined) {
108
+ const dir = this.directories().find((d) => d.id === directoryId);
109
+ if (!dir)
110
+ throw new GitHubInputError(`unknown directory "${directoryId}"`);
111
+ const repo = [...(await this.directoryRepos())].find(([, id]) => id === dir.id)?.[0];
112
+ if (!repo)
113
+ throw new GitHubInputError(`${dir.name} isn't a GitHub checkout (no github.com origin remote).`);
114
+ scope = repo;
115
+ }
116
+ const cached = this.prCache.get(scope);
117
+ if (cached && Date.now() - cached.at < 60_000)
118
+ return cached.prs;
119
+ const q = `is:pr is:open author:@me sort:updated-desc${scope ? ` repo:${scope}` : ""}`;
120
+ const args = ["api", "graphql", "-f", `query=${SEARCH_QUERY}`, "-f", `q=${q}`];
121
+ let data;
122
+ try {
123
+ // GitHub's search API sometimes times out on this query (a 502 with an empty body, which gh
124
+ // reports as "unexpected end of JSON input"); one retry almost always gets through.
125
+ data = await this.json(args).catch((e) => e instanceof GitHubAuthError ? Promise.reject(e) : this.json(args));
126
+ if (!data.data)
127
+ throw new GitHubError(`GitHub: ${data.errors?.[0]?.message ?? "no data"}`);
128
+ }
129
+ catch (e) {
130
+ if (cached && !(e instanceof GitHubAuthError))
131
+ return cached.prs; // stale beats an error
132
+ throw e;
133
+ }
134
+ const repos = await this.directoryRepos();
135
+ const prs = data.data.search.nodes
136
+ .filter((n) => n && typeof n.number === "number")
137
+ .map((n) => {
138
+ const [owner = "", repo = ""] = n.repository.nameWithOwner.split("/");
139
+ return {
140
+ id: `${owner}/${repo}#${n.number}`,
141
+ owner,
142
+ repo,
143
+ number: n.number,
144
+ title: n.title,
145
+ body: cleanBody(n.body, MAX_BODY),
146
+ url: n.url,
147
+ draft: n.isDraft,
148
+ updatedAt: n.updatedAt,
149
+ branch: n.headRefName,
150
+ baseBranch: n.baseRefName,
151
+ additions: n.additions,
152
+ deletions: n.deletions,
153
+ changedFiles: n.changedFiles,
154
+ ci: n.commits?.nodes[0]?.commit.statusCheckRollup?.state ?? undefined,
155
+ review: n.reviewDecision ?? undefined,
156
+ conflicts: n.mergeable === "CONFLICTING",
157
+ unresolvedThreads: (n.reviewThreads?.nodes ?? []).filter((t) => !t.isResolved).length,
158
+ directoryId: repos.get(`${owner}/${repo}`.toLowerCase()),
159
+ };
160
+ });
161
+ this.prCache.set(scope, { at: Date.now(), prs });
162
+ return prs;
163
+ }
164
+ /** Every PR fetched lately, without fetching (for decorating threads with status). */
165
+ cachedPullRequests() {
166
+ const byId = new Map();
167
+ for (const { prs } of this.prCache.values())
168
+ for (const pr of prs)
169
+ byId.set(pr.id, pr);
170
+ return [...byId.values()];
171
+ }
172
+ /** The latest commit's individual checks, failures first. */
173
+ async checks(owner, repo, number) {
174
+ if (!OWNER_RE.test(owner) || !REPO_RE.test(repo) || !Number.isInteger(number) || number < 1)
175
+ throw new GitHubError("bad pull request");
176
+ const data = await this.json(["api", "graphql", "-f", `query=${CHECKS_QUERY}`, "-f", `owner=${owner}`, "-f", `repo=${repo}`, "-F", `number=${number}`]);
177
+ const nodes = data.data?.repository?.pullRequest?.commits.nodes[0]?.commit.statusCheckRollup?.contexts.nodes ?? [];
178
+ const rank = (s) => ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED"].includes(s)
179
+ ? 0
180
+ : ["PENDING", "IN_PROGRESS", "QUEUED", "WAITING", "EXPECTED"].includes(s)
181
+ ? 1
182
+ : s === "CANCELLED"
183
+ ? 2
184
+ : 3;
185
+ // One row per check name (re-runs and matrix jobs repeat names), keeping its most important state.
186
+ const byName = new Map();
187
+ for (const c of nodes) {
188
+ const run = {
189
+ name: c.name ?? c.context ?? "check",
190
+ state: (c.conclusion ?? (c.status === "COMPLETED" ? "" : c.status) ?? c.state ?? "").toUpperCase() || "UNKNOWN",
191
+ };
192
+ const prev = byName.get(run.name);
193
+ if (!prev || rank(run.state) < rank(prev.state))
194
+ byName.set(run.name, run);
195
+ }
196
+ return [...byName.values()].sort((a, b) => rank(a.state) - rank(b.state) || a.name.localeCompare(b.name));
197
+ }
198
+ /** Conversation comments, review summaries and inline review comments, oldest first (cached 30 s). */
199
+ async comments(owner, repo, number) {
200
+ if (!OWNER_RE.test(owner) || !REPO_RE.test(repo) || !Number.isInteger(number) || number < 1)
201
+ throw new GitHubError("bad pull request");
202
+ const key = `${owner}/${repo}#${number}`;
203
+ const cached = this.commentCache.get(key);
204
+ if (cached && Date.now() - cached.at < 30_000)
205
+ return cached.comments;
206
+ const base = `repos/${owner}/${repo}`;
207
+ const [issue, reviews, inline] = await Promise.all([
208
+ this.json(["api", `${base}/issues/${number}/comments?per_page=100`]),
209
+ this.json(["api", `${base}/pulls/${number}/reviews?per_page=100`]),
210
+ this.json(["api", `${base}/pulls/${number}/comments?per_page=100`]),
211
+ ]);
212
+ const clip = (s) => cleanBody(s);
213
+ const comments = [
214
+ ...issue.map((c) => ({
215
+ id: `c${c.id}`,
216
+ kind: "comment",
217
+ author: c.user?.login ?? "?",
218
+ body: clip(c.body),
219
+ createdAt: c.created_at,
220
+ })),
221
+ ...reviews
222
+ .filter((r) => (r.body ?? "").trim() || r.state === "APPROVED" || r.state === "CHANGES_REQUESTED")
223
+ .map((r) => ({
224
+ id: `r${r.id}`,
225
+ kind: "review",
226
+ author: r.user?.login ?? "?",
227
+ body: clip(r.body),
228
+ createdAt: r.submitted_at ?? "",
229
+ state: r.state,
230
+ })),
231
+ ...inline.map((c) => ({
232
+ id: `i${c.id}`,
233
+ kind: "inline",
234
+ author: c.user?.login ?? "?",
235
+ body: clip(c.body),
236
+ createdAt: c.created_at,
237
+ path: c.path,
238
+ line: c.line ?? c.original_line ?? undefined,
239
+ })),
240
+ ].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
241
+ this.commentCache.set(key, { at: Date.now(), comments });
242
+ return comments;
243
+ }
244
+ }
package/dist/http.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Runs fetch-style handlers (Request → Response) on node:http / node:https.
3
+ */
4
+ import { createHash } from "node:crypto";
5
+ import { TLSSocket } from "node:tls";
6
+ /** Hard cap on request bodies, enforced while reading (handlers apply tighter limits). */
7
+ const MAX_BODY_BYTES = 1024 * 1024;
8
+ export function clientCertFingerprint(socket) {
9
+ if (!(socket instanceof TLSSocket) || !socket.authorized)
10
+ return undefined;
11
+ const raw = socket.getPeerCertificate()?.raw;
12
+ return raw ? createHash("sha256").update(raw).digest("hex") : undefined;
13
+ }
14
+ export function nodeListener(handler, log = () => { }) {
15
+ return (req, res) => {
16
+ const chunks = [];
17
+ let size = 0;
18
+ let aborted = false;
19
+ req.on("data", (c) => {
20
+ if (aborted)
21
+ return;
22
+ size += c.length;
23
+ if (size > MAX_BODY_BYTES) {
24
+ aborted = true;
25
+ res.writeHead(413, { "content-type": "application/json" }).end(JSON.stringify({ error: "request body too large" }));
26
+ req.destroy();
27
+ return;
28
+ }
29
+ chunks.push(c);
30
+ });
31
+ req.on("end", async () => {
32
+ if (aborted)
33
+ return;
34
+ try {
35
+ const headers = new Headers();
36
+ for (const [k, v] of Object.entries(req.headers)) {
37
+ if (Array.isArray(v))
38
+ v.forEach((x) => headers.append(k, x));
39
+ else if (v !== undefined)
40
+ headers.set(k, v);
41
+ }
42
+ const method = req.method ?? "GET";
43
+ const request = new Request(`http://localhost${req.url ?? "/"}`, {
44
+ method,
45
+ headers,
46
+ body: method === "GET" || method === "HEAD" || !chunks.length ? undefined : Buffer.concat(chunks),
47
+ });
48
+ const response = await handler(request, { clientCertFingerprint: clientCertFingerprint(req.socket) });
49
+ const body = Buffer.from(await response.arrayBuffer());
50
+ if (res.destroyed)
51
+ return;
52
+ res.writeHead(response.status, Object.fromEntries(response.headers));
53
+ res.end(body);
54
+ }
55
+ catch (e) {
56
+ log(`request handling failed: ${String(e?.stack ?? e)}`);
57
+ if (!res.headersSent)
58
+ res.writeHead(500, { "content-type": "application/json" });
59
+ res.end(JSON.stringify({ error: "internal error" }));
60
+ }
61
+ });
62
+ };
63
+ }
package/dist/linear.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Linear: the issues assigned to you that are still open, so you can start a
3
+ * thread on one from the watch.
4
+ *
5
+ * Log in on the Mac with `overwatch linear login`: it stores a Linear personal
6
+ * API key in the macOS Keychain (typed straight into macOS's `security` prompt;
7
+ * this code never sees it then). LINEAR_API_KEY in the environment works too.
8
+ * The key is never logged or returned by the bridge's API.
9
+ */
10
+ import { execFileSync } from "node:child_process";
11
+ export const KEYCHAIN_SERVICE = "agent-overwatch";
12
+ export const KEYCHAIN_ACCOUNT = "linear";
13
+ const ENDPOINT = "https://api.linear.app/graphql";
14
+ const MAX_DESCRIPTION = 8000;
15
+ /** The Linear API key from LINEAR_API_KEY, or the macOS Keychain. */
16
+ export function readLinearKey() {
17
+ if (process.env.LINEAR_API_KEY)
18
+ return process.env.LINEAR_API_KEY;
19
+ if (process.platform !== "darwin")
20
+ return undefined;
21
+ try {
22
+ const key = execFileSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", KEYCHAIN_ACCOUNT, "-w"], {
23
+ encoding: "utf8",
24
+ timeout: 5000,
25
+ stdio: ["ignore", "pipe", "ignore"],
26
+ }).trim();
27
+ return key || undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ const QUERY = `query AssignedIssues {
34
+ viewer {
35
+ assignedIssues(first: 40, orderBy: updatedAt, filter: { state: { type: { nin: ["completed", "canceled"] } } }) {
36
+ nodes { id identifier title description url priority updatedAt branchName state { name } team { key } }
37
+ }
38
+ }
39
+ }`;
40
+ export class LinearError extends Error {
41
+ }
42
+ export class LinearSource {
43
+ key;
44
+ keyCheckedAt = 0;
45
+ cache;
46
+ readKey;
47
+ fetchImpl;
48
+ constructor(readKey = readLinearKey, fetchImpl = fetch) {
49
+ this.readKey = readKey;
50
+ this.fetchImpl = fetchImpl;
51
+ }
52
+ /** Whether you're logged in (re-checks the Keychain at most once a minute, so `overwatch linear login` takes effect without a restart). */
53
+ get enabled() {
54
+ if (Date.now() - this.keyCheckedAt > 60_000) {
55
+ this.key = this.readKey();
56
+ this.keyCheckedAt = Date.now();
57
+ }
58
+ return !!this.key;
59
+ }
60
+ async query(query) {
61
+ if (!this.enabled)
62
+ throw new LinearError("Linear isn't set up. Run `overwatch linear login` on the host.");
63
+ let res;
64
+ try {
65
+ res = await this.fetchImpl(ENDPOINT, {
66
+ method: "POST",
67
+ headers: { "content-type": "application/json", authorization: this.key },
68
+ body: JSON.stringify({ query }),
69
+ signal: AbortSignal.timeout(15_000),
70
+ });
71
+ }
72
+ catch (e) {
73
+ throw new LinearError(`Couldn't reach Linear: ${e.message}`);
74
+ }
75
+ if (res.status === 401 || res.status === 403) {
76
+ this.keyCheckedAt = 0; // re-read the key next time (maybe it was replaced)
77
+ throw new LinearError("Linear rejected the API key. Run `overwatch linear login` again.");
78
+ }
79
+ const body = (await res.json().catch(() => ({})));
80
+ if (!res.ok || body.errors?.length || !body.data) {
81
+ throw new LinearError(`Linear error: ${body.errors?.[0]?.message ?? `HTTP ${res.status}`}`);
82
+ }
83
+ return body.data;
84
+ }
85
+ /** Your open assigned issues, most recently updated first (cached for a minute). */
86
+ async issues() {
87
+ if (this.cache && Date.now() - this.cache.at < 60_000)
88
+ return this.cache.issues;
89
+ const data = await this.query(QUERY);
90
+ const issues = data.viewer.assignedIssues.nodes.map((n) => ({
91
+ id: n.id,
92
+ identifier: n.identifier,
93
+ title: n.title,
94
+ description: (n.description ?? "").slice(0, MAX_DESCRIPTION),
95
+ url: n.url,
96
+ state: n.state?.name ?? "",
97
+ team: n.team?.key ?? "",
98
+ priority: n.priority ?? 0,
99
+ updatedAt: n.updatedAt,
100
+ branchName: n.branchName ?? "",
101
+ }));
102
+ this.cache = { at: Date.now(), issues };
103
+ return issues;
104
+ }
105
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * A tiny ACP v1 agent for tests. On each prompt it streams a message, asks for
3
+ * permission to run a command, reports the tool result, and ends the turn.
4
+ * If the prompt text is "no-permission" it skips the permission step; "ask" asks a
5
+ * multiple-choice question (form elicitation) instead.
6
+ * It also exposes model / effort / mode config options, like real agents do.
7
+ * With MOCK_LOAD_SESSION=1 it supports session/load, which (like some real agents)
8
+ * brings the session back with default settings.
9
+ */
10
+ const sessions = new Map();
11
+ /** The system-prompt text each session was given (session/new or session/load). */
12
+ const systemPrompts = new Map();
13
+ function configOptions(s) {
14
+ // The "smart" model offers a higher effort level, so switching models changes the effort choices.
15
+ const efforts = s.model === "smart" ? ["low", "medium", "high"] : ["low", "medium"];
16
+ return [
17
+ {
18
+ id: "model",
19
+ name: "Model",
20
+ category: "model",
21
+ type: "select",
22
+ currentValue: s.model,
23
+ options: [
24
+ { value: "fast", name: "Mock Fast" },
25
+ { value: "smart", name: "Mock Smart" },
26
+ ],
27
+ },
28
+ {
29
+ id: "effort",
30
+ name: "Effort",
31
+ category: "thought_level",
32
+ type: "select",
33
+ currentValue: s.effort,
34
+ options: efforts.map((e) => ({ value: e, name: e[0].toUpperCase() + e.slice(1) })),
35
+ },
36
+ {
37
+ id: "mode",
38
+ name: "Mode",
39
+ category: "mode",
40
+ type: "select",
41
+ currentValue: s.mode,
42
+ options: [
43
+ { value: "default", name: "Ask first" },
44
+ { value: "plan", name: "Plan" },
45
+ ],
46
+ },
47
+ { id: "verbose", name: "Verbose", category: "other", type: "boolean", currentValue: false },
48
+ ];
49
+ }
50
+ let nextId = 1000;
51
+ const waiting = new Map();
52
+ function send(msg) {
53
+ process.stdout.write(JSON.stringify(msg) + "\n");
54
+ }
55
+ function update(sessionId, u) {
56
+ send({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: u } });
57
+ }
58
+ function request(method, params) {
59
+ const id = nextId++;
60
+ send({ jsonrpc: "2.0", id, method, params });
61
+ return new Promise((resolve) => waiting.set(id, resolve));
62
+ }
63
+ async function handle(msg) {
64
+ if (msg.id !== undefined && !msg.method) {
65
+ waiting.get(msg.id)?.(msg.result ?? { error: msg.error });
66
+ waiting.delete(msg.id);
67
+ return;
68
+ }
69
+ const { id, method, params } = msg;
70
+ switch (method) {
71
+ case "initialize":
72
+ send({
73
+ jsonrpc: "2.0",
74
+ id,
75
+ result: {
76
+ protocolVersion: Number(process.env.MOCK_PROTOCOL_VERSION ?? 1),
77
+ agentCapabilities: {
78
+ loadSession: process.env.MOCK_LOAD_SESSION === "1",
79
+ sessionCapabilities: { systemPrompt: { mode: { override: {} } } },
80
+ },
81
+ agentInfo: { name: "mock" },
82
+ authMethods: [],
83
+ },
84
+ });
85
+ return;
86
+ case "session/new": {
87
+ const sid = `sess_${sessions.size + 1}`;
88
+ const s = { model: "fast", effort: "low", mode: "default" };
89
+ sessions.set(sid, s);
90
+ if (params.systemPrompt)
91
+ systemPrompts.set(sid, params.systemPrompt.content.map((b) => b.text).join("\n\n"));
92
+ send({ jsonrpc: "2.0", id, result: { sessionId: sid, configOptions: configOptions(s) } });
93
+ return;
94
+ }
95
+ case "session/load": {
96
+ const s = { model: "fast", effort: "low", mode: "default" };
97
+ sessions.set(params.sessionId, s);
98
+ send({ jsonrpc: "2.0", id, result: { configOptions: configOptions(s) } });
99
+ return;
100
+ }
101
+ case "session/set_config_option": {
102
+ const s = sessions.get(params.sessionId);
103
+ const opt = s && configOptions(s).find((o) => o.id === params.configId);
104
+ if (!s || !opt || !opt.options?.some((o) => o.value === params.value)) {
105
+ send({ jsonrpc: "2.0", id, error: { code: -32602, message: "invalid config option" } });
106
+ return;
107
+ }
108
+ s[params.configId] = params.value;
109
+ if (!configOptions(s)[1].options.some((o) => o.value === s.effort))
110
+ s.effort = "low";
111
+ send({ jsonrpc: "2.0", id, result: { configOptions: configOptions(s) } });
112
+ return;
113
+ }
114
+ case "session/cancel":
115
+ // The client answers outstanding permission requests with "cancelled" itself.
116
+ return;
117
+ case "session/prompt": {
118
+ const sid = params.sessionId;
119
+ const text = params.prompt?.[0]?.text ?? "";
120
+ if (text === "show-system-prompt") {
121
+ update(sid, {
122
+ sessionUpdate: "agent_message_chunk",
123
+ content: { type: "text", text: `system prompt: ${systemPrompts.get(sid) ?? "none"}` },
124
+ });
125
+ send({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } });
126
+ return;
127
+ }
128
+ if (text === "ask") {
129
+ // Like Claude's AskUserQuestion through claude-agent-acp: a form elicitation.
130
+ const res = await request("elicitation/create", {
131
+ mode: "form",
132
+ sessionId: sid,
133
+ toolCallId: "ask_1",
134
+ message: "Which cache should I use?",
135
+ requestedSchema: {
136
+ type: "object",
137
+ properties: {
138
+ question_0: {
139
+ type: "string",
140
+ title: "Cache",
141
+ oneOf: [
142
+ { const: "Redis", title: "Redis", description: "Fast, needs a server" },
143
+ { const: "SQLite", title: "SQLite" },
144
+ ],
145
+ },
146
+ question_0_custom: { type: "string", title: "Other" },
147
+ },
148
+ },
149
+ });
150
+ const answer = res?.action === "accept"
151
+ ? `${res.content.question_0 ?? ""}${res.content.question_0_custom ? ` (${res.content.question_0_custom})` : ""}`
152
+ : res?.action;
153
+ update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `answer: ${answer}` } });
154
+ send({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } });
155
+ return;
156
+ }
157
+ update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Sure, " } });
158
+ update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `working on: ${text}` } });
159
+ update(sid, {
160
+ sessionUpdate: "plan",
161
+ entries: [{ content: "Run tests", priority: "high", status: "in_progress" }],
162
+ });
163
+ if (text === "edit-file") {
164
+ // A read that asks permission (auto-approved by the default rules), then an edit.
165
+ update(sid, {
166
+ sessionUpdate: "tool_call",
167
+ toolCallId: "read_1",
168
+ title: "Read app.ts",
169
+ kind: "read",
170
+ status: "pending",
171
+ locations: [{ path: "/repo/app.ts" }],
172
+ });
173
+ const res = await request("session/request_permission", {
174
+ sessionId: sid,
175
+ toolCall: { toolCallId: "read_1" },
176
+ options: [
177
+ { optionId: "approve", name: "Allow", kind: "allow_once" },
178
+ { optionId: "reject", name: "Reject", kind: "reject_once" },
179
+ ],
180
+ });
181
+ update(sid, {
182
+ sessionUpdate: "tool_call_update",
183
+ toolCallId: "read_1",
184
+ status: res?.outcome?.optionId === "approve" ? "completed" : "failed",
185
+ });
186
+ update(sid, {
187
+ sessionUpdate: "tool_call",
188
+ toolCallId: "edit_1",
189
+ title: "Edit app.ts",
190
+ kind: "edit",
191
+ status: "completed",
192
+ content: [{ type: "diff", path: "/repo/app.ts", oldText: "a\nb\nc", newText: "a\nB\nc\nd" }],
193
+ });
194
+ }
195
+ else if (text !== "no-permission") {
196
+ update(sid, {
197
+ sessionUpdate: "tool_call",
198
+ toolCallId: "call_1",
199
+ title: "Run `pnpm test`",
200
+ kind: "execute",
201
+ status: "pending",
202
+ rawInput: { command: "pnpm test" },
203
+ });
204
+ const res = await request("session/request_permission", {
205
+ sessionId: sid,
206
+ toolCall: { toolCallId: "call_1" },
207
+ options: [
208
+ { optionId: "approve", name: "Allow", kind: "allow_once" },
209
+ { optionId: "reject", name: "Reject", kind: "reject_once" },
210
+ ],
211
+ });
212
+ if (res?.outcome?.outcome === "cancelled") {
213
+ send({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } });
214
+ return;
215
+ }
216
+ const ok = res?.outcome?.optionId === "approve";
217
+ update(sid, { sessionUpdate: "tool_call_update", toolCallId: "call_1", status: ok ? "completed" : "failed" });
218
+ }
219
+ update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "\n\nDone. Anything else?" } });
220
+ send({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } });
221
+ return;
222
+ }
223
+ default:
224
+ if (id !== undefined)
225
+ send({ jsonrpc: "2.0", id, error: { code: -32601, message: "nope" } });
226
+ }
227
+ }
228
+ let buf = "";
229
+ process.stdin.setEncoding("utf8");
230
+ for await (const chunk of process.stdin) {
231
+ buf += chunk;
232
+ let nl;
233
+ while ((nl = buf.indexOf("\n")) >= 0) {
234
+ const line = buf.slice(0, nl).trim();
235
+ buf = buf.slice(nl + 1);
236
+ if (!line)
237
+ continue;
238
+ const msg = JSON.parse(line);
239
+ void handle(msg);
240
+ }
241
+ }
242
+ export {};