@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 ADDED
@@ -0,0 +1,45 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jacoblee93
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ src/qr.ts (dist/qr.js) (the QR code encoder for `overwatch pair`) follows the structure of the
26
+ QR Code generator library by Project Nayuki:
27
+
28
+ Copyright (c) Project Nayuki. (MIT License)
29
+ https://www.nayuki.io/page/qr-code-generator-library
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
32
+ this software and associated documentation files (the "Software"), to deal in
33
+ the Software without restriction, including without limitation the rights to
34
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
35
+ the Software, and to permit persons to whom the Software is furnished to do so,
36
+ subject to the following conditions:
37
+ - The above copyright notice and this permission notice shall be included in
38
+ all copies or substantial portions of the Software.
39
+ - The Software is provided "as is", without warranty of any kind, express or
40
+ implied, including but not limited to the warranties of merchantability,
41
+ fitness for a particular purpose and noninfringement. In no event shall the
42
+ authors or copyright holders be liable for any claim, damages or other
43
+ liability, whether in an action of contract, tort or otherwise, arising from,
44
+ out of or in connection with the Software or the use or other dealings in the
45
+ Software.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # agent-overwatch
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The bridge and `overwatch` CLI for [Agent Overwatch](https://github.com/jacoblee93/agent-overwatch): start, watch and steer coding agents (Claude Code, Codex, Gemini CLI, any [ACP](https://agentclientprotocol.com) agent) from your Apple Watch. Approve tool calls, answer their questions and reply from your wrist.
4
+
5
+ It runs on your Mac, next to your code. The watch talks only to it, over mutual TLS with a certificate it gets when you pair.
6
+
7
+ ## Install
8
+
9
+ Needs Node.js 22.18 or later.
10
+
11
+ ```bash
12
+ npm install -g @jacoblee93/agent-overwatch
13
+ overwatch init # pick directories and agents
14
+ overwatch daemon start # run it in the background (macOS)
15
+ overwatch pair # shows a QR code: scan it with your iPhone's camera
16
+ ```
17
+
18
+ Then install the AgentOverwatch app on your iPhone and Apple Watch. Your watch has to reach the bridge from wherever you are: see [Make it reachable](https://github.com/jacoblee93/agent-overwatch#4-make-it-reachable).
19
+
20
+ `overwatch doctor` checks the whole setup. `overwatch help` lists every command.
21
+
22
+ ## Update
23
+
24
+ ```bash
25
+ npm install -g @jacoblee93/agent-overwatch@latest && overwatch daemon restart
26
+ ```
27
+
28
+ ## Docs
29
+
30
+ Setup, how it works, the security model and the bridge API are in the [main README](https://github.com/jacoblee93/agent-overwatch#readme).
31
+
32
+ ## License
33
+
34
+ MIT
@@ -0,0 +1,44 @@
1
+ {
2
+ "hostName": "My Mac",
3
+ "listen": { "hostname": "127.0.0.1", "port": 7878 },
4
+ "secure": {
5
+ "hostname": "127.0.0.1",
6
+ "port": 7879,
7
+ "pairPort": 7880,
8
+ "publicURL": "https://my-mac.tail1234.ts.net"
9
+ },
10
+ "token": "generated-on-first-run-do-not-copy-this",
11
+ "agents": [
12
+ {
13
+ "id": "mock",
14
+ "name": "Mock agent (no API key)",
15
+ "command": "/usr/local/bin/node",
16
+ "args": ["/Users/you/personal-projects/agent-overwatch/bridge/src/mock-agent.ts"]
17
+ },
18
+ { "id": "claude-code", "name": "Claude Code", "command": "npx", "args": ["-y", "@agentclientprotocol/claude-agent-acp"] },
19
+ { "id": "codex", "name": "Codex", "command": "npx", "args": ["-y", "@zed-industries/codex-acp"] },
20
+ { "id": "gemini", "name": "Gemini CLI", "command": "gemini", "args": ["--experimental-acp"] },
21
+ {
22
+ "id": "sandbox-claude",
23
+ "name": "Claude Code (sandbox)",
24
+ "command": "ssh",
25
+ "args": ["my-sandbox", "npx", "-y", "@agentclientprotocol/claude-agent-acp"]
26
+ }
27
+ ],
28
+ "directories": [
29
+ { "id": "overwatch", "name": "agent-overwatch", "path": "/Users/you/personal-projects/agent-overwatch" },
30
+ { "id": "home", "name": "Home", "path": "/Users/you" }
31
+ ],
32
+ "approvals": {
33
+ "autoAllow": { "kinds": ["read", "search", "think"], "commands": ["git status", "git diff*", "npm test"] }
34
+ },
35
+ "housekeeping": { "doneRetentionDays": 7 },
36
+ "push": {
37
+ "keyPath": "~/.agent-overwatch/AuthKey_ABC123DEFG.p8",
38
+ "keyId": "ABC123DEFG",
39
+ "teamId": "XYZ987TEAM"
40
+ },
41
+ "notify": {
42
+ "ntfyUrl": "https://ntfy.example.com/overwatch-8f3c1e0a9b7d"
43
+ }
44
+ }
@@ -0,0 +1,175 @@
1
+ export class RpcRequestError extends Error {
2
+ code;
3
+ data;
4
+ constructor(code, message, data) {
5
+ super(message);
6
+ this.code = code;
7
+ this.data = data;
8
+ }
9
+ }
10
+ /** Max size of a single JSON-RPC line we will buffer from an agent (16 MiB). */
11
+ const MAX_LINE_BYTES = 16 * 1024 * 1024;
12
+ export class JsonRpcPeer {
13
+ nextId = 1;
14
+ pending = new Map();
15
+ requestHandlers = new Map();
16
+ notificationHandlers = new Map();
17
+ closed = false;
18
+ closeListeners = [];
19
+ write;
20
+ log;
21
+ constructor(write, log = () => { }) {
22
+ this.write = write;
23
+ this.log = log;
24
+ }
25
+ onRequest(method, handler) {
26
+ this.requestHandlers.set(method, handler);
27
+ }
28
+ onNotification(method, handler) {
29
+ this.notificationHandlers.set(method, handler);
30
+ }
31
+ onClose(listener) {
32
+ this.closeListeners.push(listener);
33
+ }
34
+ request(method, params) {
35
+ if (this.closed)
36
+ return Promise.reject(new Error("connection closed"));
37
+ const id = this.nextId++;
38
+ return new Promise((resolve, reject) => {
39
+ this.pending.set(id, { resolve, reject, method });
40
+ this.send({ jsonrpc: "2.0", id, method, params });
41
+ });
42
+ }
43
+ notify(method, params) {
44
+ if (this.closed)
45
+ return;
46
+ this.send({ jsonrpc: "2.0", method, params });
47
+ }
48
+ /** Feed one complete line received from the peer. */
49
+ handleLine(line) {
50
+ const trimmed = line.trim();
51
+ if (!trimmed)
52
+ return;
53
+ let msg;
54
+ try {
55
+ msg = JSON.parse(trimmed);
56
+ }
57
+ catch {
58
+ // Agents sometimes print non-protocol noise to stdout; ignore it.
59
+ this.log(`ignoring non-JSON line from agent: ${trimmed.slice(0, 200)}`);
60
+ return;
61
+ }
62
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0")
63
+ return;
64
+ if ("method" in msg && typeof msg.method === "string") {
65
+ if ("id" in msg && msg.id !== undefined && msg.id !== null) {
66
+ void this.dispatchRequest(msg.id, msg.method, msg.params);
67
+ }
68
+ else {
69
+ const handler = this.notificationHandlers.get(msg.method);
70
+ if (handler) {
71
+ try {
72
+ handler(msg.params);
73
+ }
74
+ catch (e) {
75
+ this.log(`notification handler ${msg.method} threw: ${String(e)}`);
76
+ }
77
+ }
78
+ }
79
+ return;
80
+ }
81
+ if ("id" in msg) {
82
+ const p = this.pending.get(msg.id);
83
+ if (!p)
84
+ return;
85
+ this.pending.delete(msg.id);
86
+ if (msg.error) {
87
+ const err = msg.error;
88
+ p.reject(new RpcRequestError(err.code, `${p.method}: ${err.message}`, err.data));
89
+ }
90
+ else {
91
+ p.resolve(msg.result);
92
+ }
93
+ }
94
+ }
95
+ close(reason) {
96
+ if (this.closed)
97
+ return;
98
+ this.closed = true;
99
+ for (const [, p] of this.pending)
100
+ p.reject(new Error(`connection closed: ${reason}`));
101
+ this.pending.clear();
102
+ for (const l of this.closeListeners)
103
+ l(reason);
104
+ }
105
+ get isClosed() {
106
+ return this.closed;
107
+ }
108
+ async dispatchRequest(id, method, params) {
109
+ const handler = this.requestHandlers.get(method);
110
+ if (!handler) {
111
+ this.send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
112
+ return;
113
+ }
114
+ try {
115
+ const result = await handler(params);
116
+ this.send({ jsonrpc: "2.0", id, result: result ?? null });
117
+ }
118
+ catch (e) {
119
+ if (e instanceof RpcRequestError) {
120
+ this.send({ jsonrpc: "2.0", id, error: { code: e.code, message: e.message, data: e.data } });
121
+ }
122
+ else {
123
+ this.send({ jsonrpc: "2.0", id, error: { code: -32603, message: String(e?.message ?? e) } });
124
+ }
125
+ }
126
+ }
127
+ send(msg) {
128
+ if (this.closed)
129
+ return;
130
+ this.write(JSON.stringify(msg) + "\n");
131
+ }
132
+ }
133
+ /** Wire a JsonRpcPeer to a spawned subprocess's stdio. */
134
+ export function attachToProcess(proc, log) {
135
+ const peer = new JsonRpcPeer((line) => {
136
+ if (proc.stdin.writable)
137
+ proc.stdin.write(line);
138
+ }, log);
139
+ // Writing to an agent that already exited raises EPIPE on stdin; the exit handler reports it.
140
+ proc.stdin.on("error", () => { });
141
+ let stderrTail = "";
142
+ proc.stderr.setEncoding("utf8");
143
+ proc.stderr.on("data", (text) => {
144
+ const t = text.trimEnd();
145
+ if (!t)
146
+ return;
147
+ stderrTail = (stderrTail + "\n" + t).slice(-4000);
148
+ log(`[agent stderr] ${t.slice(0, 2000)}`);
149
+ });
150
+ let buf = "";
151
+ proc.stdout.setEncoding("utf8");
152
+ proc.stdout.on("data", (chunk) => {
153
+ buf += chunk;
154
+ let nl;
155
+ while ((nl = buf.indexOf("\n")) >= 0) {
156
+ const line = buf.slice(0, nl);
157
+ buf = buf.slice(nl + 1);
158
+ peer.handleLine(line);
159
+ }
160
+ if (buf.length > MAX_LINE_BYTES) {
161
+ log("agent emitted an oversized line; dropping buffer");
162
+ buf = "";
163
+ }
164
+ });
165
+ const tail = () => stderrTail.trim().split("\n").slice(-3).join(" ").slice(-400);
166
+ // e.g. ENOENT when the configured command doesn't exist.
167
+ proc.on("error", (e) => peer.close(`agent failed to start: ${e.message}`));
168
+ proc.on("close", (code, signal) => {
169
+ if (buf.trim())
170
+ peer.handleLine(buf);
171
+ const how = signal ? `signal ${signal}` : `code ${code}`;
172
+ peer.close(`agent exited with ${how}${tail() ? `: ${tail()}` : ""}`);
173
+ });
174
+ return peer;
175
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The subset of ACP v1 (protocolVersion = 1) types this client uses.
3
+ * See https://agentclientprotocol.com/protocol/overview
4
+ */
5
+ export const ACP_PROTOCOL_VERSION = 1;
6
+ export function contentToText(block) {
7
+ if (!block)
8
+ return "";
9
+ switch (block.type) {
10
+ case "text":
11
+ return block.text;
12
+ case "resource_link":
13
+ return `[${block.title ?? block.name}](${block.uri})`;
14
+ case "resource":
15
+ return block.resource.text ?? `[resource ${block.resource.uri}]`;
16
+ case "image":
17
+ return "[image]";
18
+ case "audio":
19
+ return "[audio]";
20
+ default:
21
+ return "";
22
+ }
23
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * One agent process and its ACP session. This is the only place that speaks ACP:
3
+ * it starts the agent, does the handshake, opens or loads the session, and turns
4
+ * what the agent sends into protocol-neutral events (`AgentUpdate`, approvals,
5
+ * questions) for the SessionManager. A future protocol version would be another
6
+ * implementation of this same surface.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { attachToProcess } from "./acp/connection.js";
10
+ import { ACP_PROTOCOL_VERSION, contentToText, } from "./acp/types.js";
11
+ import { questionsFrom } from "./questions.js";
12
+ import { VERSION } from "./version.js";
13
+ const SHOWN_CATEGORIES = ["model", "thought_level", "mode"];
14
+ export function toSettings(opts) {
15
+ const out = [];
16
+ for (const o of opts ?? []) {
17
+ const category = SHOWN_CATEGORIES.find((c) => c === o.category);
18
+ if (!category || o.type !== "select" || typeof o.currentValue !== "string")
19
+ continue;
20
+ const options = (o.options ?? []).flatMap((x) => "group" in x ? x.options.map((y) => ({ value: y.value, name: y.name })) : [{ value: x.value, name: x.name }]);
21
+ if (options.length)
22
+ out.push({ id: o.id, name: o.name, category, currentValue: o.currentValue, options });
23
+ }
24
+ return out.sort((a, b) => SHOWN_CATEGORIES.indexOf(a.category) - SHOWN_CATEGORIES.indexOf(b.category));
25
+ }
26
+ const CLIENT = {
27
+ protocolVersion: ACP_PROTOCOL_VERSION,
28
+ // No fs or terminal: agents use their own tools. Form elicitation: agents can ask
29
+ // multiple-choice questions (e.g. Claude's AskUserQuestion).
30
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false, elicitation: { form: {} } },
31
+ clientInfo: { name: "agent-overwatch", title: "Agent Overwatch", version: VERSION },
32
+ };
33
+ function startProcess(agent, cwd) {
34
+ // argv array, no shell: the command and args come only from the bridge config.
35
+ return spawn(agent.command, agent.args ?? [], {
36
+ cwd,
37
+ env: { ...process.env, ...agent.env },
38
+ stdio: ["pipe", "pipe", "pipe"],
39
+ });
40
+ }
41
+ async function initialize(peer) {
42
+ const init = await peer.request("initialize", CLIENT);
43
+ if (init.protocolVersion !== ACP_PROTOCOL_VERSION) {
44
+ throw new Error(`agent speaks ACP protocol v${init.protocolVersion}; Agent Overwatch supports v${ACP_PROTOCOL_VERSION}`);
45
+ }
46
+ return init;
47
+ }
48
+ export class AgentSession {
49
+ sessionId;
50
+ supportsLoad;
51
+ /** As the agent reported them when the session opened (later changes arrive as updates). */
52
+ settings;
53
+ peer;
54
+ proc;
55
+ closing = false;
56
+ constructor(peer, proc, sessionId, supportsLoad, settings) {
57
+ this.peer = peer;
58
+ this.proc = proc;
59
+ this.sessionId = sessionId;
60
+ this.supportsLoad = supportsLoad;
61
+ this.settings = settings;
62
+ }
63
+ /** Start the agent and open (or load) a session. Fails, with the process stopped, if the handshake does. */
64
+ static async open(o) {
65
+ const proc = startProcess(o.agent, o.cwd);
66
+ const peer = attachToProcess(proc, (m) => o.log(`${o.tag} ${m}`));
67
+ let session;
68
+ let sessionId = o.resume;
69
+ // A session/load replays history we already have: ignore it.
70
+ let replaying = false;
71
+ peer.onNotification("session/update", (params) => {
72
+ if (replaying || (sessionId && params?.sessionId && params.sessionId !== sessionId))
73
+ return;
74
+ const u = toUpdate(params);
75
+ if (u)
76
+ o.handlers.update(u);
77
+ });
78
+ peer.onRequest("session/request_permission", async (params) => {
79
+ const optionId = await o.handlers.approval({
80
+ toolCall: params.toolCall ?? { toolCallId: "" },
81
+ options: (params.options ?? []).map((x) => ({ optionId: x.optionId, name: x.name, kind: x.kind })),
82
+ });
83
+ return { outcome: optionId === null ? { outcome: "cancelled" } : { outcome: "selected", optionId } };
84
+ });
85
+ peer.onRequest("elicitation/create", (params) => {
86
+ const questions = params && sessionId && params.sessionId === sessionId ? questionsFrom(params) : [];
87
+ // URL mode, request-scoped (setup) forms and forms we can't show: declined, so the agent carries on.
88
+ if (!questions.length)
89
+ return Promise.resolve({ action: "decline" });
90
+ const required = (params.requestedSchema?.required ?? []).filter((r) => typeof r === "string");
91
+ return o.handlers.question({ message: params.message ?? "", questions, required });
92
+ });
93
+ // Other agent→client methods (fs, terminal) fall through to "method not found".
94
+ peer.onClose((reason) => {
95
+ if (session && !session.closing)
96
+ o.handlers.closed(session, reason);
97
+ });
98
+ try {
99
+ const init = await initialize(peer);
100
+ const supportsLoad = Boolean(init.agentCapabilities?.loadSession);
101
+ const systemPrompt = o.systemPrompt && init.agentCapabilities?.sessionCapabilities?.systemPrompt
102
+ ? { systemPrompt: { mode: "append", content: [{ type: "text", text: o.systemPrompt }] } }
103
+ : {};
104
+ if (init.authMethods?.length) {
105
+ o.log(`${o.tag} agent advertises auth methods (${init.authMethods.map((m) => m.id).join(", ")}); ` +
106
+ "authenticate it once from a terminal/editor if session/new fails.");
107
+ }
108
+ let settings;
109
+ if (o.resume) {
110
+ replaying = true;
111
+ try {
112
+ const res = await peer.request("session/load", {
113
+ sessionId: o.resume,
114
+ cwd: o.cwd,
115
+ mcpServers: [],
116
+ ...systemPrompt,
117
+ });
118
+ settings = toSettings(res?.configOptions);
119
+ }
120
+ finally {
121
+ replaying = false;
122
+ }
123
+ }
124
+ else {
125
+ const res = await peer.request("session/new", { cwd: o.cwd, mcpServers: [], ...systemPrompt });
126
+ sessionId = res.sessionId;
127
+ settings = toSettings(res.configOptions);
128
+ }
129
+ session = new AgentSession(peer, proc, sessionId, supportsLoad, settings);
130
+ return session;
131
+ }
132
+ catch (e) {
133
+ peer.close("handshake failed");
134
+ proc.kill();
135
+ throw e;
136
+ }
137
+ }
138
+ /** Start the agent, open a session to read its settings (its defaults), and stop it. */
139
+ static async readDefaults(agent, cwd, log) {
140
+ const proc = startProcess(agent, cwd);
141
+ const peer = attachToProcess(proc, (m) => log(`[${agent.id}:probe] ${m}`));
142
+ const timer = setTimeout(() => proc.kill(), 60_000);
143
+ try {
144
+ await initialize(peer);
145
+ const res = await peer.request("session/new", { cwd, mcpServers: [] });
146
+ return toSettings(res.configOptions);
147
+ }
148
+ finally {
149
+ clearTimeout(timer);
150
+ peer.close("done");
151
+ proc.kill();
152
+ }
153
+ }
154
+ /** Run a turn. Resolves when it ends, with why. */
155
+ async prompt(text) {
156
+ const res = await this.peer.request("session/prompt", {
157
+ sessionId: this.sessionId,
158
+ prompt: [{ type: "text", text }],
159
+ });
160
+ return res?.stopReason;
161
+ }
162
+ /** Stop the current turn. Pending approvals and questions are cancelled by the caller. */
163
+ cancel() {
164
+ this.peer.notify("session/cancel", { sessionId: this.sessionId });
165
+ }
166
+ /**
167
+ * Change a setting. Returns the complete, possibly changed, set (e.g. a new model's effort levels)
168
+ * when the agent sends it, or null when it doesn't (the change applied as asked).
169
+ */
170
+ async setSetting(id, value) {
171
+ const res = await this.peer.request("session/set_config_option", {
172
+ sessionId: this.sessionId,
173
+ configId: id,
174
+ value,
175
+ });
176
+ return res?.configOptions ? toSettings(res.configOptions) : null;
177
+ }
178
+ /** Stop the agent process. `closed` isn't called for this. */
179
+ close(reason = "closed by user") {
180
+ this.closing = true;
181
+ this.peer.close(reason);
182
+ this.proc.kill(); // a no-op if it already exited
183
+ }
184
+ }
185
+ /** An ACP session/update as an AgentUpdate (or nothing, for ones the watch doesn't show). */
186
+ function toUpdate(n) {
187
+ const u = n?.update;
188
+ if (!u || typeof u.sessionUpdate !== "string")
189
+ return undefined;
190
+ switch (u.sessionUpdate) {
191
+ case "agent_message_chunk":
192
+ return { kind: "text", role: "agent", text: contentToText(u.content) };
193
+ case "agent_thought_chunk":
194
+ return { kind: "text", role: "thought", text: contentToText(u.content) };
195
+ case "user_message_chunk":
196
+ return { kind: "text", role: "user", text: contentToText(u.content) };
197
+ case "tool_call":
198
+ case "tool_call_update":
199
+ return { kind: "tool", call: u };
200
+ case "plan":
201
+ return { kind: "plan", entries: Array.isArray(u.entries) ? u.entries : [] };
202
+ case "config_option_update":
203
+ return { kind: "settings", settings: toSettings(u.configOptions) };
204
+ case "current_mode_update":
205
+ return typeof u.currentModeId === "string" ? { kind: "mode", modeId: u.currentModeId } : undefined;
206
+ case "session_info_update":
207
+ return typeof u.title === "string" && u.title.trim() ? { kind: "title", title: u.title.trim() } : undefined;
208
+ default:
209
+ // available_commands_update, usage_update, etc. are not surfaced on the watch.
210
+ return undefined;
211
+ }
212
+ }
package/dist/agents.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `overwatch agents …` — the ACP agents the watch can start threads with.
3
+ * Any program that speaks ACP over stdio works; the command is run directly
4
+ * (no shell), in the thread's directory. A running bridge picks up changes
5
+ * within a second.
6
+ *
7
+ * overwatch agents add codex --name "Codex" -- npx -y @zed-industries/codex-acp
8
+ * overwatch agents add box --name "Claude (sandbox)" --env FOO=bar -- ssh my-box npx -y @agentclientprotocol/claude-agent-acp
9
+ */
10
+ import { agentKind, configPath, loadConfig, updateConfigFile } from "./config.js";
11
+ const USAGE = `usage: overwatch agents [list]
12
+ overwatch agents add <id> [--name "Display name"] [--env KEY=VALUE ...] -- <command> [args...]
13
+ overwatch agents remove <id>
14
+
15
+ Any program that speaks ACP (Agent Client Protocol) over stdio works. The command runs directly,
16
+ not through a shell, in the thread's directory. Examples:
17
+ overwatch agents add claude-code --name "Claude Code" -- npx -y @agentclientprotocol/claude-agent-acp
18
+ overwatch agents add codex --name Codex -- npx -y @zed-industries/codex-acp
19
+ overwatch agents add deepagents --name "Deep Agents" -- dcode --acp
20
+ overwatch agents add gemini --name "Gemini CLI" -- gemini --experimental-acp`;
21
+ const ID_RE = /^[A-Za-z0-9_.-]{1,64}$/;
22
+ const ENV_RE = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
23
+ function list() {
24
+ const { agents } = loadConfig().config;
25
+ if (!agents.length) {
26
+ console.log("No agents. Add one with: overwatch agents add <id> -- <command> [args...]");
27
+ return;
28
+ }
29
+ const w = Math.max(...agents.map((a) => a.id.length));
30
+ for (const a of agents) {
31
+ const env = Object.keys(a.env ?? {});
32
+ console.log(`${a.id.padEnd(w)} ${a.name} (${agentKind(a)})\n${" ".repeat(w)} ${[a.command, ...(a.args ?? [])].join(" ")}${env.length ? ` [env: ${env.join(", ")}]` : ""}`);
33
+ }
34
+ }
35
+ export function agents(argv) {
36
+ const [sub = "list", ...rest] = argv;
37
+ switch (sub) {
38
+ case "list":
39
+ case "ls":
40
+ list();
41
+ return 0;
42
+ case "add": {
43
+ const sep = rest.indexOf("--");
44
+ const opts = sep >= 0 ? rest.slice(0, sep) : rest;
45
+ const command = sep >= 0 ? rest.slice(sep + 1) : [];
46
+ const [id, ...flags] = opts;
47
+ if (!id || !ID_RE.test(id) || !command.length) {
48
+ console.log(USAGE);
49
+ return 1;
50
+ }
51
+ let name = id;
52
+ const env = {};
53
+ for (let i = 0; i < flags.length; i++) {
54
+ if (flags[i] === "--name" && flags[i + 1] !== undefined)
55
+ name = flags[++i];
56
+ else if (flags[i] === "--env" && flags[i + 1] !== undefined) {
57
+ const m = ENV_RE.exec(flags[++i]);
58
+ if (!m) {
59
+ console.log(`--env takes KEY=VALUE, got "${flags[i]}"`);
60
+ return 1;
61
+ }
62
+ env[m[1]] = m[2];
63
+ }
64
+ else {
65
+ console.log(USAGE);
66
+ return 1;
67
+ }
68
+ }
69
+ const agent = { id, name, command: command[0], args: command.slice(1) };
70
+ if (Object.keys(env).length)
71
+ agent.env = env;
72
+ let replaced = false;
73
+ try {
74
+ updateConfigFile((c) => {
75
+ replaced = c.agents.some((a) => a.id === id);
76
+ c.agents = [...c.agents.filter((a) => a.id !== id), agent];
77
+ });
78
+ }
79
+ catch (e) {
80
+ console.log(`Couldn't save: ${e.message}`);
81
+ return 1;
82
+ }
83
+ console.log(`${replaced ? "Updated" : "Added"} "${name}" (${id}). It shows up in the watch's agent picker.`);
84
+ if (Object.keys(env).length)
85
+ console.log(`Its env is stored in ${configPath()} (0600). For secrets, prefer exporting them in your shell profile.`);
86
+ return 0;
87
+ }
88
+ case "remove":
89
+ case "rm": {
90
+ const id = rest[0];
91
+ if (!id) {
92
+ console.log(USAGE);
93
+ return 1;
94
+ }
95
+ let removed;
96
+ updateConfigFile((c) => {
97
+ removed = c.agents.find((a) => a.id === id)?.name;
98
+ c.agents = c.agents.filter((a) => a.id !== id);
99
+ });
100
+ if (!removed) {
101
+ console.log(`No agent "${id}". See: overwatch agents`);
102
+ return 1;
103
+ }
104
+ console.log(`Removed "${removed}". Running threads keep going.`);
105
+ return 0;
106
+ }
107
+ default:
108
+ console.log(USAGE);
109
+ return sub === "help" || sub === "--help" ? 0 : 1;
110
+ }
111
+ }