@harness-sdk/harnessd 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +15 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/channel.d.ts +56 -0
  8. package/dist/channel.d.ts.map +1 -0
  9. package/dist/channel.js +356 -0
  10. package/dist/channel.js.map +1 -0
  11. package/dist/claude.d.ts +42 -0
  12. package/dist/claude.d.ts.map +1 -0
  13. package/dist/claude.js +166 -0
  14. package/dist/claude.js.map +1 -0
  15. package/dist/cli.d.ts +8 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +258 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config.d.ts +43 -0
  20. package/dist/config.d.ts.map +1 -0
  21. package/dist/config.js +121 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/daemon.d.ts +24 -0
  24. package/dist/daemon.d.ts.map +1 -0
  25. package/dist/daemon.js +239 -0
  26. package/dist/daemon.js.map +1 -0
  27. package/dist/launchd.d.ts +22 -0
  28. package/dist/launchd.d.ts.map +1 -0
  29. package/dist/launchd.js +88 -0
  30. package/dist/launchd.js.map +1 -0
  31. package/dist/log.d.ts +3 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +17 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/terminal.d.ts +11 -0
  36. package/dist/terminal.d.ts.map +1 -0
  37. package/dist/terminal.js +36 -0
  38. package/dist/terminal.js.map +1 -0
  39. package/dist/watchdog.d.ts +73 -0
  40. package/dist/watchdog.d.ts.map +1 -0
  41. package/dist/watchdog.js +230 -0
  42. package/dist/watchdog.js.map +1 -0
  43. package/package.json +54 -4
  44. package/src/bin.ts +18 -0
  45. package/src/channel.ts +461 -0
  46. package/src/claude.ts +274 -0
  47. package/src/cli.ts +372 -0
  48. package/src/config.ts +203 -0
  49. package/src/daemon.ts +312 -0
  50. package/src/launchd.ts +126 -0
  51. package/src/log.ts +17 -0
  52. package/src/terminal.ts +33 -0
  53. package/src/watchdog.ts +310 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentbaseAI Inc.
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.
package/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # harnessd
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
+ harnessd keeps Claude Code running on your Mac, day and night, connected to the events of your agentic apps. Put it on a Mac mini and you have an agent that's always on.
4
+
5
+ - It starts at login and after any crash, and picks up the same conversation.
6
+ - Each agentic app you connect is a channel. Its events reach the agent as they happen, and its tools let the agent answer.
7
+ - Its terminal is there whenever you want it, on the Mac or over SSH.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install -g @harness-sdk/harnessd
13
+ harnessd install
14
+ harnessd attach
15
+ ```
16
+
17
+ `harnessd attach` opens Claude Code's terminal. If Claude Code isn't signed in on this Mac yet, sign in there, then detach with Ctrl-\\. Claude Code keeps running.
18
+
19
+ The agent works in `~/agent`, which harnessd marks as trusted in Claude Code. Its standing instructions go in `~/agent/CLAUDE.md`, the file Claude Code already reads. Permission prompts are skipped, since nobody is there to answer them, so give the agent a Mac of its own.
20
+
21
+ Turn on automatic login (System Settings, Users & Groups), so the agent comes back after a power cut.
22
+
23
+ ## Connect a channel
24
+
25
+ A channel is an MCP server that serves events, such as a [Statewire](https://www.npmjs.com/package/statewire) host. Name it in `~/.harnessd/config.json`:
26
+
27
+ ```json
28
+ {
29
+ "folder": "~/agent",
30
+ "channels": {
31
+ "board": {
32
+ "url": "https://board.example.com/api/board/mcp",
33
+ "headers": { "Authorization": "Bearer ${BOARD_TOKEN}" }
34
+ }
35
+ }
36
+ }
37
+ ```
38
+
39
+ Each event reaches the conversation as `<channel source="plugin:harnessd:board" event="…">…</channel>`, and the server's tools sit beside it. If the agent restarts, the events it missed come when it's back.
40
+
41
+ Claude Code lets a channel in only when the Mac's managed settings list it. `harnessd install` offers to add harnessd there, and `harnessd status` shows whether each channel's events arrive.
42
+
43
+ ## The config file
44
+
45
+ | Key | What it does |
46
+ | --- | --- |
47
+ | `folder` | Where Claude Code runs. |
48
+ | `args` | More arguments for `claude`, such as `["--model", "opus"]` or `["--remote-control"]`. |
49
+ | `env` | More environment for `claude`. |
50
+ | `prestart` | A shell command run before each start. It prints `{ "env": {…}, "args": […] }` for that start, so a token is fetched fresh and never kept on disk. |
51
+ | `channels` | MCP servers by name: a `url` (https, or http on this Mac), `headers` that read `${VAR}` from the environment, and `arguments` for event types that ask for them. |
52
+
53
+ A change takes effect at the next start: `harnessd stop`, then `harnessd start`.
54
+
55
+ ## Commands
56
+
57
+ | Command | What it does |
58
+ | --- | --- |
59
+ | `harnessd status` | What runs, which conversation, and whether events arrive. `--json` for scripts. |
60
+ | `harnessd attach` | Claude Code's terminal. |
61
+ | `harnessd new "<message>"` | A new conversation that opens with your message, such as a handoff from a long one. |
62
+ | `harnessd stop`, `harnessd start` | Stop Claude Code until you start it again. |
63
+ | `harnessd logs` | Follow harnessd's log. |
64
+ | `harnessd uninstall` | Stop harnessd and remove it from login. Your settings and conversation stay. |
package/dist/bin.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=bin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":""}
package/dist/bin.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { runHarnessd } from "./cli.js";
3
+ import { realpathSync } from "node:fs";
4
+ // src/bin.ts
5
+ console.log = console.error.bind(console);
6
+ console.info = console.error.bind(console);
7
+ console.debug = console.error.bind(console);
8
+ try {
9
+ process.exitCode = await runHarnessd(process.argv.slice(2), realpathSync(process.argv[1]));
10
+ } catch (error) {
11
+ console.error(error instanceof Error ? error.message : String(error));
12
+ process.exitCode = 1;
13
+ }
14
+
15
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { runHarnessd } from \"./cli\";\n\n// stdout belongs to the command (for `harnessd channel`, to Claude Code)\nconsole.log = console.error.bind(console);\nconsole.info = console.error.bind(console);\nconsole.debug = console.error.bind(console);\n\ntry {\n process.exitCode = await runHarnessd(\n process.argv.slice(2),\n realpathSync(process.argv[1]!),\n );\n} catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n}\n"],"mappings":";;;;AAKA,QAAQ,MAAM,QAAQ,MAAM,KAAK,OAAO;AACxC,QAAQ,OAAO,QAAQ,MAAM,KAAK,OAAO;AACzC,QAAQ,QAAQ,QAAQ,MAAM,KAAK,OAAO;AAE1C,IAAI;CACF,QAAQ,WAAW,MAAM,YACvB,QAAQ,KAAK,MAAM,CAAC,GACpB,aAAa,QAAQ,KAAK,EAAG,CAC/B;AACF,SAAS,OAAO;CACd,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,WAAW;AACrB"}
@@ -0,0 +1,56 @@
1
+ import { type Harnessd } from "./config.js";
2
+ export declare namespace Channel {
3
+ /** What a channel keeps in harnessd's home: where its events resume, and whether Claude Code hears them. */
4
+ type Status = {
5
+ readonly cursor?: string;
6
+ /** When this Claude Code process got its first event. */
7
+ readonly pushedAt?: string;
8
+ /** When one of its events first showed up in the conversation's transcript. */
9
+ readonly heardAt?: string;
10
+ };
11
+ type Options = {
12
+ readonly name: string;
13
+ readonly channel: Harnessd.Channel;
14
+ readonly paths: Harnessd.Paths;
15
+ readonly send: (message: Record<string, unknown>) => void;
16
+ readonly log: (line: string) => void;
17
+ readonly env?: NodeJS.ProcessEnv;
18
+ readonly fetch?: typeof fetch;
19
+ readonly startMs?: number;
20
+ readonly checkMs?: number;
21
+ };
22
+ type Server = {
23
+ readonly handle: (request: Request) => Promise<Record<string, unknown> | undefined>;
24
+ readonly stop: () => Promise<void>;
25
+ };
26
+ type Request = {
27
+ jsonrpc: "2.0";
28
+ id?: string | number;
29
+ method: string;
30
+ params?: Record<string, unknown>;
31
+ };
32
+ }
33
+ /** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */
34
+ export declare const streamFlags: (args: Readonly<Record<string, string | number | boolean>>) => string[];
35
+ export declare const statusFile: (paths: Harnessd.Paths, name: string) => string;
36
+ export declare const readStatus: (file: string) => Channel.Status;
37
+ /** One event as Claude Code shows it: its `text`, else its data as JSON, with its scalar fields as tag attributes and its delivery id. */
38
+ export declare const channelMessage: (line: {
39
+ name: string;
40
+ data: unknown;
41
+ gap?: boolean;
42
+ delivery: string;
43
+ }) => {
44
+ content: string;
45
+ meta: Record<string, string>;
46
+ };
47
+ /**
48
+ * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push
49
+ * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so
50
+ * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it
51
+ * dropped (a channel it didn't let in) comes again at the next start.
52
+ */
53
+ export declare const channelServer: (options: Channel.Options) => Channel.Server;
54
+ /** Serves one channel on stdin and stdout until Claude Code closes stdin. */
55
+ export declare const serveChannel: (options: Omit<Channel.Options, "send">) => Promise<void>;
56
+ //# sourceMappingURL=channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAa,KAAK,QAAQ,EAAE,oBAAiB;AAEpD,yBAAiB,OAAO,CAAC;IACvB,4GAA4G;IAC5G,KAAY,MAAM,GAAG;QACnB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QACzB,yDAAyD;QACzD,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAC3B,+EAA+E;QAC/E,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;KAC3B,CAAC;IAEF,KAAY,OAAO,GAAG;QACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QACtB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC;QACnC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC;QAC/B,QAAQ,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;QAC1D,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;QACrC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O,CAAC,OAAO,KAAG,OAAO,CAAC,MA8PhE,CAAC;AAEF,6EAA6E;AAC7E,eAAO,MAAM,YAAY,GAAU,SAAS,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,kBAuBxE,CAAC"}
@@ -0,0 +1,356 @@
1
+ import { findTranscript } from "./claude.js";
2
+ import { headersOf } from "./config.js";
3
+ import { closeSync, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
4
+ import { createInterface } from "node:readline";
5
+ import { dirname, join } from "node:path";
6
+ import { randomBytes } from "node:crypto";
7
+ import { runCli } from "toolport/cli";
8
+ import { handleMcpMessage } from "toolport/mcp";
9
+ import { fromMcpServer } from "toolport/mcp-client";
10
+ // src/channel.ts
11
+ const CHANNEL = "notifications/claude/channel";
12
+ const PROTOCOL = "2025-06-18";
13
+ const protocolFor = (asked) => typeof asked === "string" && /^\d{4}-\d{2}-\d{2}$/.test(asked) && asked < "2026-07-28" ? asked : PROTOCOL;
14
+ const START_MS = 1500;
15
+ const CHECK_MS = 5e3;
16
+ const CONNECT_WAIT_MS = 5e3;
17
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
18
+ const unref = (timer) => timer.unref?.();
19
+ /** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */
20
+ const streamFlags = (args) => Object.entries(args).flatMap(([key, value]) => {
21
+ const flag = key.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
22
+ return typeof value === "boolean" ? [value ? `--${flag}` : `--no-${flag}`] : [`--${flag}`, String(value)];
23
+ });
24
+ const statusFile = (paths, name) => join(paths.channels, `${name}.json`);
25
+ const readStatus = (file) => {
26
+ try {
27
+ return JSON.parse(readFileSync(file, "utf8"));
28
+ } catch {
29
+ return {};
30
+ }
31
+ };
32
+ const writeStatus = (file, status) => {
33
+ mkdirSync(dirname(file), { recursive: true });
34
+ const temp = `${file}.${process.pid}`;
35
+ writeFileSync(temp, `${JSON.stringify(status)}\n`);
36
+ renameSync(temp, file);
37
+ };
38
+ /** One event as Claude Code shows it: its `text`, else its data as JSON, with its scalar fields as tag attributes and its delivery id. */
39
+ const channelMessage = (line) => {
40
+ if (line.gap) return {
41
+ content: `Some ${line.name} events were missed (the server no longer had them): read its state again.`,
42
+ meta: {
43
+ event: line.name,
44
+ gap: "true",
45
+ delivery: line.delivery
46
+ }
47
+ };
48
+ const data = line.data;
49
+ const meta = {};
50
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) for (const [key, value] of Object.entries(data)) {
51
+ if (key === "text" || key === "source" || !IDENTIFIER.test(key)) continue;
52
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") meta[key] = String(value).replace(/[<>"]/g, "").slice(0, 200);
53
+ }
54
+ meta.event = line.name;
55
+ meta.delivery = line.delivery;
56
+ const text = data?.text;
57
+ return {
58
+ content: typeof text === "string" ? text : JSON.stringify(data),
59
+ meta
60
+ };
61
+ };
62
+ /** The deliveries of this channel's messages in a transcript's whole lines from byte `from` on, and where those lines end. */
63
+ const deliveriesIn = (file, from, source) => {
64
+ try {
65
+ const buffer = Buffer.alloc(Math.max(0, statSync(file).size - from));
66
+ const fd = openSync(file, "r");
67
+ try {
68
+ readSync(fd, buffer, 0, buffer.length, from);
69
+ } finally {
70
+ closeSync(fd);
71
+ }
72
+ const whole = buffer.lastIndexOf(10) + 1;
73
+ const text = buffer.subarray(0, whole).toString("utf8");
74
+ const tag = new RegExp(`<channel source=\\\\?"${source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\\\?"([^>]*)>`, "g");
75
+ const found = [];
76
+ for (const [, attributes] of text.matchAll(tag)) {
77
+ const delivery = /delivery=\\?"([a-f0-9]+\.\d+)\\?"/.exec(attributes);
78
+ if (delivery) found.push(delivery[1]);
79
+ }
80
+ return {
81
+ found,
82
+ next: from + whole
83
+ };
84
+ } catch {
85
+ return {
86
+ found: [],
87
+ next: from
88
+ };
89
+ }
90
+ };
91
+ const sizeOf = (file) => {
92
+ try {
93
+ return file ? statSync(file).size : 0;
94
+ } catch {
95
+ return 0;
96
+ }
97
+ };
98
+ /**
99
+ * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push
100
+ * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so
101
+ * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it
102
+ * dropped (a channel it didn't let in) comes again at the next start.
103
+ */
104
+ const channelServer = (options) => {
105
+ const env = options.env ?? process.env;
106
+ const source = `plugin:harnessd:${options.name}`;
107
+ const file = statusFile(options.paths, options.name);
108
+ const saved = readStatus(file);
109
+ let status = saved.cursor ? { cursor: saved.cursor } : {};
110
+ writeStatus(file, status);
111
+ const controller = new AbortController();
112
+ let following;
113
+ const transcript = () => env.CLAUDE_CODE_SESSION_ID ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env) : void 0;
114
+ let from = sizeOf(transcript());
115
+ const nonce = randomBytes(4).toString("hex");
116
+ let delivery = 0;
117
+ let lastCursor = status.cursor;
118
+ const unconfirmed = [];
119
+ const heard = /* @__PURE__ */ new Set();
120
+ let check;
121
+ const save = (patch) => {
122
+ status = {
123
+ ...status,
124
+ ...patch
125
+ };
126
+ writeStatus(file, status);
127
+ };
128
+ const confirm = () => {
129
+ const at = transcript();
130
+ if (at === void 0) return;
131
+ const read = deliveriesIn(at, from, source);
132
+ from = read.next;
133
+ for (const n of read.found) heard.add(n);
134
+ let cursor;
135
+ while (unconfirmed.length > 0 && heard.has(unconfirmed[0].delivery)) {
136
+ const event = unconfirmed.shift();
137
+ heard.delete(event.delivery);
138
+ cursor = event.cursor ?? cursor;
139
+ if (!status.heardAt) {
140
+ save({ heardAt: (/* @__PURE__ */ new Date()).toISOString() });
141
+ options.log(`Claude Code hears ${options.name}'s events`);
142
+ }
143
+ }
144
+ if (cursor !== void 0) save({ cursor });
145
+ };
146
+ const onLine = (raw) => {
147
+ let line;
148
+ try {
149
+ line = JSON.parse(raw);
150
+ } catch {
151
+ return;
152
+ }
153
+ if (typeof line.name !== "string") return;
154
+ if (!status.pushedAt) save({ pushedAt: (/* @__PURE__ */ new Date()).toISOString() });
155
+ if (!check) {
156
+ check = setInterval(confirm, options.checkMs ?? CHECK_MS);
157
+ unref(check);
158
+ }
159
+ const cursor = typeof line.cursor === "string" && line.cursor ? line.cursor : void 0;
160
+ if (cursor) lastCursor = cursor;
161
+ const id = `${nonce}.${++delivery}`;
162
+ unconfirmed.push({
163
+ delivery: id,
164
+ cursor
165
+ });
166
+ options.send({
167
+ jsonrpc: "2.0",
168
+ method: CHANNEL,
169
+ params: channelMessage({
170
+ name: line.name,
171
+ data: line.data ?? null,
172
+ ...line.gap && { gap: true },
173
+ delivery: id
174
+ })
175
+ });
176
+ };
177
+ const follow = async () => {
178
+ let backoff = 5e3;
179
+ while (!controller.signal.aborted) {
180
+ const startedAt = Date.now();
181
+ let code;
182
+ try {
183
+ const cursor = lastCursor;
184
+ code = await runCli({
185
+ name: "harnessd",
186
+ configDir: join(options.paths.home, "auth"),
187
+ servers: { [options.name]: {
188
+ url: options.channel.url,
189
+ headers: headersOf(options.channel, env),
190
+ ...options.fetch && { fetch: options.fetch }
191
+ } }
192
+ }, {
193
+ argv: [
194
+ "stream",
195
+ ...cursor ? ["--from", cursor] : [],
196
+ ...streamFlags(options.channel.arguments)
197
+ ],
198
+ stdout: onLine,
199
+ stderr: (line) => options.log(`${options.name}: ${line}`),
200
+ signal: controller.signal
201
+ });
202
+ } catch (error) {
203
+ code = 1;
204
+ options.log(`${options.name}: ${error instanceof Error ? error.message : String(error)}`);
205
+ }
206
+ if (controller.signal.aborted) return;
207
+ if (Date.now() - startedAt > 6e5) backoff = 5e3;
208
+ options.log(`${options.name}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1e3)}s`);
209
+ await new Promise((resolve) => {
210
+ const timer = setTimeout(resolve, backoff);
211
+ controller.signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
212
+ });
213
+ backoff = Math.min(backoff * 2, 3e5);
214
+ }
215
+ };
216
+ let toolkit;
217
+ let announced = false;
218
+ const connect = () => toolkit ??= fromMcpServer({
219
+ url: options.channel.url,
220
+ headers: () => headersOf(options.channel, env),
221
+ ...options.fetch && { fetch: options.fetch },
222
+ name: options.name
223
+ }).catch((error) => {
224
+ toolkit = void 0;
225
+ throw error;
226
+ });
227
+ const withTimeout = (promise, ms) => Promise.race([promise, new Promise((resolve) => unref(setTimeout(resolve, ms)))]).catch(() => void 0);
228
+ const retryTools = async () => {
229
+ let wait = 5e3;
230
+ while (!controller.signal.aborted) {
231
+ await new Promise((resolve) => unref(setTimeout(resolve, wait)));
232
+ try {
233
+ await connect();
234
+ if (!announced) {
235
+ announced = true;
236
+ options.send({
237
+ jsonrpc: "2.0",
238
+ method: "notifications/tools/list_changed"
239
+ });
240
+ }
241
+ return;
242
+ } catch {
243
+ wait = Math.min(wait * 2, 3e5);
244
+ }
245
+ }
246
+ };
247
+ const instructions = (upstream) => [
248
+ `Events from ${options.name} arrive here for the whole session, one per message: <channel source="${source}" event="…" …>the event</channel>. Act on each.`,
249
+ `To answer or act on ${options.name}, use this server's tools: they are ${options.name}'s own.`,
250
+ ...upstream ? [`${options.name} says: ${upstream}`] : []
251
+ ].join(" ");
252
+ const handle = async (request) => {
253
+ const result = (value) => ({
254
+ jsonrpc: "2.0",
255
+ id: request.id,
256
+ result: value
257
+ });
258
+ switch (request.method) {
259
+ case "initialize": {
260
+ const kit = await withTimeout(connect(), CONNECT_WAIT_MS);
261
+ return result({
262
+ protocolVersion: protocolFor(request.params?.protocolVersion),
263
+ capabilities: {
264
+ experimental: { "claude/channel": {} },
265
+ tools: { listChanged: true }
266
+ },
267
+ serverInfo: {
268
+ name: `harnessd-${options.name}`,
269
+ version: "1.0.0"
270
+ },
271
+ instructions: instructions(kit?.description)
272
+ });
273
+ }
274
+ case "notifications/initialized":
275
+ unref(setTimeout(() => {
276
+ if (!controller.signal.aborted) following ??= follow();
277
+ }, options.startMs ?? START_MS));
278
+ return;
279
+ case "tools/list":
280
+ case "tools/call": {
281
+ let kit;
282
+ try {
283
+ kit = await connect();
284
+ } catch (error) {
285
+ options.log(`${options.name}: couldn't reach its tools: ${error instanceof Error ? error.message : String(error)}`);
286
+ if (request.method === "tools/list") {
287
+ retryTools();
288
+ return result({ tools: [] });
289
+ }
290
+ return result({
291
+ content: [{
292
+ type: "text",
293
+ text: `${options.name} can't be reached right now.`
294
+ }],
295
+ isError: true
296
+ });
297
+ }
298
+ announced = true;
299
+ return await handleMcpMessage(kit, request) ?? void 0;
300
+ }
301
+ case "ping": return result({});
302
+ default:
303
+ if (request.id === void 0) return void 0;
304
+ return {
305
+ jsonrpc: "2.0",
306
+ id: request.id,
307
+ error: {
308
+ code: -32601,
309
+ message: `Method not found: ${request.method}`
310
+ }
311
+ };
312
+ }
313
+ };
314
+ return {
315
+ handle,
316
+ stop: async () => {
317
+ controller.abort();
318
+ clearInterval(check);
319
+ await following;
320
+ await (await toolkit?.catch(() => void 0))?.close();
321
+ }
322
+ };
323
+ };
324
+ /** Serves one channel on stdin and stdout until Claude Code closes stdin. */
325
+ const serveChannel = async (options) => {
326
+ const write = (message) => void process.stdout.write(`${JSON.stringify(message)}\n`);
327
+ const server = channelServer({
328
+ ...options,
329
+ send: write
330
+ });
331
+ const end = () => void server.stop().finally(() => process.exit(0));
332
+ process.once("SIGTERM", end);
333
+ process.once("SIGINT", end);
334
+ for await (const line of createInterface({ input: process.stdin })) {
335
+ if (!line.trim()) continue;
336
+ let request;
337
+ try {
338
+ request = JSON.parse(line);
339
+ } catch {
340
+ write({
341
+ jsonrpc: "2.0",
342
+ id: null,
343
+ error: {
344
+ code: -32700,
345
+ message: "Parse error"
346
+ }
347
+ });
348
+ continue;
349
+ }
350
+ server.handle(request).then((response) => response && write(response));
351
+ }
352
+ await server.stop();
353
+ };
354
+ export { channelMessage, channelServer, readStatus, serveChannel, statusFile, streamFlags };
355
+
356
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["import {\n closeSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n renameSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { runCli } from \"toolport/cli\";\nimport { handleMcpMessage } from \"toolport/mcp\";\nimport { fromMcpServer, type McpToolkit } from \"toolport/mcp-client\";\nimport { findTranscript } from \"./claude\";\nimport { headersOf, type Harnessd } from \"./config\";\n\nexport namespace Channel {\n /** What a channel keeps in harnessd's home: where its events resume, and whether Claude Code hears them. */\n export type Status = {\n readonly cursor?: string;\n /** When this Claude Code process got its first event. */\n readonly pushedAt?: string;\n /** When one of its events first showed up in the conversation's transcript. */\n readonly heardAt?: string;\n };\n\n export type Options = {\n readonly name: string;\n readonly channel: Harnessd.Channel;\n readonly paths: Harnessd.Paths;\n readonly send: (message: Record<string, unknown>) => void;\n readonly log: (line: string) => void;\n readonly env?: NodeJS.ProcessEnv;\n readonly fetch?: typeof fetch;\n readonly startMs?: number;\n readonly checkMs?: number;\n };\n\n export type Server = {\n readonly handle: (\n request: Request,\n ) => Promise<Record<string, unknown> | undefined>;\n readonly stop: () => Promise<void>;\n };\n\n export type Request = {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst CHANNEL = \"notifications/claude/channel\";\n// Claude Code registers no channel on 2026-07-28 or later\nconst PROTOCOL = \"2025-06-18\";\nconst protocolFor = (asked: unknown) =>\n typeof asked === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(asked) &&\n asked < \"2026-07-28\"\n ? asked\n : PROTOCOL;\n// Claude Code drops what a channel sends before it registers, just after `initialized`\nconst START_MS = 1500;\nconst CHECK_MS = 5000;\nconst CONNECT_WAIT_MS = 5000;\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst unref = (timer: unknown) => (timer as { unref?: () => void }).unref?.();\n\n/** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */\nexport const streamFlags = (\n args: Readonly<Record<string, string | number | boolean>>,\n) =>\n Object.entries(args).flatMap(([key, value]) => {\n const flag = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n return typeof value === \"boolean\"\n ? [value ? `--${flag}` : `--no-${flag}`]\n : [`--${flag}`, String(value)];\n });\n\nexport const statusFile = (paths: Harnessd.Paths, name: string) =>\n join(paths.channels, `${name}.json`);\n\nexport const readStatus = (file: string): Channel.Status => {\n try {\n return JSON.parse(readFileSync(file, \"utf8\")) as Channel.Status;\n } catch {\n return {};\n }\n};\n\nconst writeStatus = (file: string, status: Channel.Status) => {\n mkdirSync(dirname(file), { recursive: true });\n // replaced whole, so a crash mid-write never loses the cursor\n const temp = `${file}.${process.pid}`;\n writeFileSync(temp, `${JSON.stringify(status)}\\n`);\n renameSync(temp, file);\n};\n\n/** One event as Claude Code shows it: its `text`, else its data as JSON, with its scalar fields as tag attributes and its delivery id. */\nexport const channelMessage = (line: {\n name: string;\n data: unknown;\n gap?: boolean;\n delivery: string;\n}) => {\n if (line.gap)\n return {\n content: `Some ${line.name} events were missed (the server no longer had them): read its state again.`,\n meta: { event: line.name, gap: \"true\", delivery: line.delivery },\n };\n const data = line.data;\n const meta: Record<string, string> = {};\n if (typeof data === \"object\" && data !== null && !Array.isArray(data))\n for (const [key, value] of Object.entries(data)) {\n if (key === \"text\" || key === \"source\" || !IDENTIFIER.test(key)) continue;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n )\n meta[key] = String(value).replace(/[<>\"]/g, \"\").slice(0, 200);\n }\n meta.event = line.name;\n meta.delivery = line.delivery;\n const text = (data as { text?: unknown } | null)?.text;\n return {\n content: typeof text === \"string\" ? text : JSON.stringify(data),\n meta,\n };\n};\n\n/** The deliveries of this channel's messages in a transcript's whole lines from byte `from` on, and where those lines end. */\nconst deliveriesIn = (file: string, from: number, source: string) => {\n try {\n const buffer = Buffer.alloc(Math.max(0, statSync(file).size - from));\n const fd = openSync(file, \"r\");\n try {\n readSync(fd, buffer, 0, buffer.length, from);\n } finally {\n closeSync(fd);\n }\n const whole = buffer.lastIndexOf(10) + 1;\n const text = buffer.subarray(0, whole).toString(\"utf8\");\n // in the JSONL the tag's quotes are escaped\n const tag = new RegExp(\n `<channel source=\\\\\\\\?\"${source.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\\\\\?\"([^>]*)>`,\n \"g\",\n );\n const found: string[] = [];\n for (const [, attributes] of text.matchAll(tag)) {\n const delivery = /delivery=\\\\?\"([a-f0-9]+\\.\\d+)\\\\?\"/.exec(attributes!);\n if (delivery) found.push(delivery[1]!);\n }\n return { found, next: from + whole };\n } catch {\n return { found: [], next: from };\n }\n};\n\nconst sizeOf = (file: string | undefined) => {\n try {\n return file ? statSync(file).size : 0;\n } catch {\n return 0;\n }\n};\n\n/**\n * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push\n * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so\n * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it\n * dropped (a channel it didn't let in) comes again at the next start.\n */\nexport const channelServer = (options: Channel.Options): Channel.Server => {\n const env = options.env ?? process.env;\n const source = `plugin:harnessd:${options.name}`;\n const file = statusFile(options.paths, options.name);\n const saved = readStatus(file);\n let status: Channel.Status = saved.cursor ? { cursor: saved.cursor } : {};\n writeStatus(file, status);\n const controller = new AbortController();\n let following: Promise<void> | undefined;\n const transcript = () =>\n env.CLAUDE_CODE_SESSION_ID\n ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env)\n : undefined;\n // a resumed conversation's earlier lines belong to earlier runs\n let from = sizeOf(transcript());\n // a payload can't name a later event's delivery: each run's numbers carry a random prefix\n const nonce = randomBytes(4).toString(\"hex\");\n let delivery = 0;\n let lastCursor = status.cursor;\n const unconfirmed: { delivery: string; cursor: string | undefined }[] = [];\n const heard = new Set<string>();\n let check: ReturnType<typeof setInterval> | undefined;\n\n const save = (patch: Channel.Status) => {\n status = { ...status, ...patch };\n writeStatus(file, status);\n };\n\n // The cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.\n const confirm = () => {\n const at = transcript();\n if (at === undefined) return;\n const read = deliveriesIn(at, from, source);\n from = read.next;\n for (const n of read.found) heard.add(n);\n let cursor: string | undefined;\n while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {\n const event = unconfirmed.shift()!;\n heard.delete(event.delivery);\n cursor = event.cursor ?? cursor;\n if (!status.heardAt) {\n save({ heardAt: new Date().toISOString() });\n options.log(`Claude Code hears ${options.name}'s events`);\n }\n }\n if (cursor !== undefined) save({ cursor });\n };\n\n const onLine = (raw: string) => {\n let line: { name?: string; data?: unknown; cursor?: string; gap?: boolean };\n try {\n line = JSON.parse(raw);\n } catch {\n return;\n }\n if (typeof line.name !== \"string\") return;\n if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });\n if (!check) {\n check = setInterval(confirm, options.checkMs ?? CHECK_MS);\n unref(check);\n }\n const cursor =\n typeof line.cursor === \"string\" && line.cursor ? line.cursor : undefined;\n if (cursor) lastCursor = cursor;\n const id = `${nonce}.${++delivery}`;\n unconfirmed.push({ delivery: id, cursor });\n options.send({\n jsonrpc: \"2.0\",\n method: CHANNEL,\n params: channelMessage({\n name: line.name,\n data: line.data ?? null,\n ...(line.gap && { gap: true }),\n delivery: id,\n }),\n });\n };\n\n const follow = async () => {\n let backoff = 5000;\n while (!controller.signal.aborted) {\n const startedAt = Date.now();\n let code: number;\n try {\n const cursor = lastCursor;\n code = await runCli(\n {\n name: \"harnessd\",\n configDir: join(options.paths.home, \"auth\"),\n servers: {\n [options.name]: {\n url: options.channel.url,\n headers: headersOf(options.channel, env),\n ...(options.fetch && { fetch: options.fetch }),\n },\n },\n },\n {\n argv: [\n \"stream\",\n ...(cursor ? [\"--from\", cursor] : []),\n ...streamFlags(options.channel.arguments),\n ],\n stdout: onLine,\n stderr: (line) => options.log(`${options.name}: ${line}`),\n signal: controller.signal,\n },\n );\n } catch (error) {\n code = 1;\n options.log(\n `${options.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (controller.signal.aborted) return;\n if (Date.now() - startedAt > 10 * 60_000) backoff = 5000;\n options.log(\n `${options.name}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,\n );\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, backoff);\n controller.signal.addEventListener(\n \"abort\",\n () => (clearTimeout(timer), resolve()),\n { once: true },\n );\n });\n backoff = Math.min(backoff * 2, 5 * 60_000);\n }\n };\n\n let toolkit: Promise<McpToolkit> | undefined;\n let announced = false;\n const connect = () =>\n (toolkit ??= fromMcpServer({\n url: options.channel.url,\n headers: () => headersOf(options.channel, env),\n ...(options.fetch && { fetch: options.fetch }),\n name: options.name,\n }).catch((error: unknown) => {\n toolkit = undefined;\n throw error;\n }));\n const withTimeout = <T>(promise: Promise<T>, ms: number) =>\n Promise.race([\n promise,\n new Promise<undefined>((resolve) => unref(setTimeout(resolve, ms))),\n ]).catch(() => undefined);\n // The server was down when Claude Code asked for the tools: list them once it's back.\n const retryTools = async () => {\n let wait = 5000;\n while (!controller.signal.aborted) {\n await new Promise((resolve) => unref(setTimeout(resolve, wait)));\n try {\n await connect();\n if (!announced) {\n announced = true;\n options.send({\n jsonrpc: \"2.0\",\n method: \"notifications/tools/list_changed\",\n });\n }\n return;\n } catch {\n wait = Math.min(wait * 2, 5 * 60_000);\n }\n }\n };\n\n const instructions = (upstream: string | undefined) =>\n [\n `Events from ${options.name} arrive here for the whole session, one per message: <channel source=\"${source}\" event=\"…\" …>the event</channel>. Act on each.`,\n `To answer or act on ${options.name}, use this server's tools: they are ${options.name}'s own.`,\n ...(upstream ? [`${options.name} says: ${upstream}`] : []),\n ].join(\" \");\n\n const handle = async (\n request: Channel.Request,\n ): Promise<Record<string, unknown> | undefined> => {\n const result = (value: unknown) => ({\n jsonrpc: \"2.0\",\n id: request.id,\n result: value,\n });\n switch (request.method) {\n case \"initialize\": {\n const kit = await withTimeout(connect(), CONNECT_WAIT_MS);\n return result({\n protocolVersion: protocolFor(request.params?.protocolVersion),\n capabilities: {\n experimental: { \"claude/channel\": {} },\n tools: { listChanged: true },\n },\n serverInfo: { name: `harnessd-${options.name}`, version: \"1.0.0\" },\n instructions: instructions(kit?.description),\n });\n }\n case \"notifications/initialized\":\n unref(\n setTimeout(() => {\n if (!controller.signal.aborted) following ??= follow();\n }, options.startMs ?? START_MS),\n );\n return undefined;\n case \"tools/list\":\n case \"tools/call\": {\n let kit: McpToolkit;\n try {\n kit = await connect();\n } catch (error) {\n options.log(\n `${options.name}: couldn't reach its tools: ${error instanceof Error ? error.message : String(error)}`,\n );\n if (request.method === \"tools/list\") {\n void retryTools();\n return result({ tools: [] });\n }\n return result({\n content: [\n {\n type: \"text\",\n text: `${options.name} can't be reached right now.`,\n },\n ],\n isError: true,\n });\n }\n announced = true;\n return (await handleMcpMessage(kit, request)) ?? undefined;\n }\n case \"ping\":\n return result({});\n default:\n if (request.id === undefined) return undefined;\n return {\n jsonrpc: \"2.0\",\n id: request.id,\n error: {\n code: -32601,\n message: `Method not found: ${request.method}`,\n },\n };\n }\n };\n\n return {\n handle,\n stop: async () => {\n controller.abort();\n clearInterval(check);\n await following;\n await (await toolkit?.catch(() => undefined))?.close();\n },\n };\n};\n\n/** Serves one channel on stdin and stdout until Claude Code closes stdin. */\nexport const serveChannel = async (options: Omit<Channel.Options, \"send\">) => {\n const write = (message: unknown) =>\n void process.stdout.write(`${JSON.stringify(message)}\\n`);\n const server = channelServer({ ...options, send: write });\n const end = () => void server.stop().finally(() => process.exit(0));\n process.once(\"SIGTERM\", end);\n process.once(\"SIGINT\", end);\n for await (const line of createInterface({ input: process.stdin })) {\n if (!line.trim()) continue;\n let request: Channel.Request;\n try {\n request = JSON.parse(line);\n } catch {\n write({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n continue;\n }\n void server.handle(request).then((response) => response && write(response));\n }\n await server.stop();\n};\n"],"mappings":";;;;;;;;;;AAwDA,MAAM,UAAU;AAEhB,MAAM,WAAW;AACjB,MAAM,eAAe,UACnB,OAAO,UAAU,YACjB,sBAAsB,KAAK,KAAK,KAChC,QAAQ,eACJ,QACA;AAEN,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,SAAS,UAAoB,MAAiC,QAAQ;;AAG5E,MAAa,eACX,SAEA,OAAO,QAAQ,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;CAC7C,MAAM,OAAO,IACV,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,MAAM,GAAG,CAAC,CAClB,YAAY;CACf,OAAO,OAAO,UAAU,YACpB,CAAC,QAAQ,KAAK,SAAS,QAAQ,MAAM,IACrC,CAAC,KAAK,QAAQ,OAAO,KAAK,CAAC;AACjC,CAAC;AAEH,MAAa,cAAc,OAAuB,SAChD,KAAK,MAAM,UAAU,GAAG,KAAK,MAAM;AAErC,MAAa,cAAc,SAAiC;CAC1D,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAM,eAAe,MAAc,WAA2B;CAC5D,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAE5C,MAAM,OAAO,GAAG,KAAK,GAAG,QAAQ;CAChC,cAAc,MAAM,GAAG,KAAK,UAAU,MAAM,EAAE,GAAG;CACjD,WAAW,MAAM,IAAI;AACvB;;AAGA,MAAa,kBAAkB,SAKzB;CACJ,IAAI,KA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Q,MAAM,CAAC,GAAG;EAClE,IAAI,CAAC,KAAK,KAAK,GAAG;EAClB,IAAI;EACJ,IAAI;GACF,UAAU,KAAK,MAAM,IAAI;EAC3B,QAAQ;GACN,MAAM;IACJ,SAAS;IACT,IAAI;IACJ,OAAO;KAAE,MAAM;KAAQ,SAAS;IAAc;GAChD,CAAC;GACD;EACF;EACA,OAAY,OAAO,OAAO,CAAC,CAAC,MAAM,aAAa,YAAY,MAAM,QAAQ,CAAC;CAC5E;CACA,MAAM,OAAO,KAAK;AACpB"}
@@ -0,0 +1,42 @@
1
+ import type { Harnessd } from "./config.js";
2
+ import type { Watchdog } from "./watchdog.js";
3
+ /** How Claude Code names a `--plugin-dir` plugin, and what `--channels` takes. */
4
+ export declare const PLUGIN = "harnessd@inline";
5
+ export declare const MANAGED_SETTINGS = "/Library/Application Support/ClaudeCode/managed-settings.json";
6
+ /**
7
+ * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
8
+ * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
9
+ * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.
10
+ */
11
+ export declare const trustFolder: (folder: string, env?: NodeJS.ProcessEnv) => boolean;
12
+ /** A conversation's transcript, wherever Claude Code put it. */
13
+ export declare const findTranscript: (sessionId: string, env?: NodeJS.ProcessEnv) => string | undefined;
14
+ /** The first `name` on `path` that can run. */
15
+ export declare const which: (name: string, path?: string) => string;
16
+ /**
17
+ * harnessd's plugin, written before each start from the config's channels: one MCP server per channel, each
18
+ * `harnessd channel <name>`. None: no plugin.
19
+ */
20
+ export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => boolean;
21
+ /**
22
+ * The claude command line for one start (after the binary). `--channels` names the plugin only when the managed
23
+ * settings let it in: a refused entry there also shuts out the same plugin loaded with the development flag.
24
+ */
25
+ export declare const claudeArgs: (o: {
26
+ start: Watchdog.Start;
27
+ plugin: string | undefined;
28
+ allowed: boolean;
29
+ config: Harnessd.Config;
30
+ extra: readonly string[];
31
+ }) => string[];
32
+ export type Prestart = {
33
+ env: Record<string, string>;
34
+ args: string[];
35
+ };
36
+ /** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
37
+ export declare const prestart: (command: string, folder: string, env: NodeJS.ProcessEnv, log: (line: string) => void) => Promise<Prestart>;
38
+ /** What keeps harnessd's channels out of Claude Code on this Mac: its managed settings must let `harnessd@inline` in. */
39
+ export declare const channelBlockers: (file?: string) => string[];
40
+ /** The managed settings with harnessd's channel let in; a list that wasn't there starts with Anthropic's own channels. */
41
+ export declare const allowChannel: (file?: string) => Record<string, unknown>;
42
+ //# sourceMappingURL=claude.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../src/claude.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,QAAQ,EAAE,oBAAiB;AACzC,OAAO,KAAK,EAAE,QAAQ,EAAE,sBAAmB;AAE3C,kFAAkF;AAClF,eAAO,MAAM,MAAM,oBAAoB,CAAC;AACxC,eAAO,MAAM,gBAAgB,kEACoC,CAAC;AAKlE;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,EACd,MAAK,MAAM,CAAC,UAAwB,KACnC,OAqBF,CAAC;AAEF,gEAAgE;AAChE,eAAO,MAAM,cAAc,GACzB,WAAW,MAAM,EACjB,MAAK,MAAM,CAAC,UAAwB,KACnC,MAAM,GAAG,SASX,CAAC;AAEF,+CAA+C;AAC/C,eAAO,MAAM,KAAK,GAAI,MAAM,MAAM,EAAE,aAA6B,WAYhE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,GACtB,OAAO,QAAQ,CAAC,KAAK,EACrB,QAAQ,QAAQ,CAAC,MAAM,EACvB,KAAK,MAAM,KACV,OA0BF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,UAAU,GAAI,GAAG;IAC5B,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