@harness-sdk/harnessd 0.0.0 → 0.0.2
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 +21 -0
- package/README.md +64 -2
- package/dist/accounts.d.ts +66 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +166 -0
- package/dist/accounts.js.map +1 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +19 -0
- package/dist/bin.js.map +1 -0
- package/dist/channel.d.ts +56 -0
- package/dist/channel.d.ts.map +1 -0
- package/dist/channel.js +356 -0
- package/dist/channel.js.map +1 -0
- package/dist/claude.d.ts +41 -0
- package/dist/claude.d.ts.map +1 -0
- package/dist/claude.js +152 -0
- package/dist/claude.js.map +1 -0
- package/dist/cli.d.ts +13 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +413 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +56 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +161 -0
- package/dist/config.js.map +1 -0
- package/dist/daemon.d.ts +37 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/daemon.js +300 -0
- package/dist/daemon.js.map +1 -0
- package/dist/launchd.d.ts +18 -0
- package/dist/launchd.d.ts.map +1 -0
- package/dist/launchd.js +91 -0
- package/dist/launchd.js.map +1 -0
- package/dist/log.d.ts +3 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +17 -0
- package/dist/log.js.map +1 -0
- package/dist/prompts.d.ts +53 -0
- package/dist/prompts.d.ts.map +1 -0
- package/dist/prompts.js +171 -0
- package/dist/prompts.js.map +1 -0
- package/dist/service.d.ts +37 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +71 -0
- package/dist/service.js.map +1 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +121 -0
- package/dist/setup.js.map +1 -0
- package/dist/system.d.ts +6 -0
- package/dist/system.d.ts.map +1 -0
- package/dist/system.js +16 -0
- package/dist/system.js.map +1 -0
- package/dist/systemd.d.ts +14 -0
- package/dist/systemd.d.ts.map +1 -0
- package/dist/systemd.js +62 -0
- package/dist/systemd.js.map +1 -0
- package/dist/terminal.d.ts +11 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +36 -0
- package/dist/terminal.js.map +1 -0
- package/dist/watchdog.d.ts +83 -0
- package/dist/watchdog.d.ts.map +1 -0
- package/dist/watchdog.js +236 -0
- package/dist/watchdog.js.map +1 -0
- package/package.json +55 -6
- package/src/accounts.ts +242 -0
- package/src/bin.ts +24 -0
- package/src/channel.ts +461 -0
- package/src/claude.ts +249 -0
- package/src/cli.ts +633 -0
- package/src/config.ts +281 -0
- package/src/daemon.ts +379 -0
- package/src/launchd.ts +131 -0
- package/src/log.ts +17 -0
- package/src/prompts.ts +255 -0
- package/src/service.ts +145 -0
- package/src/setup.ts +188 -0
- package/src/system.ts +11 -0
- package/src/systemd.ts +78 -0
- package/src/terminal.ts +33 -0
- package/src/watchdog.ts +318 -0
package/dist/channel.js
ADDED
|
@@ -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 { dirname, join } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
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,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AAO,KAAA;IACrC,OAAO;KACL,SAAS;KACT,IAAI,QAAQ;KACZ,OAAO;MACL,MAAM;MACN,SAAS,qBAAqB,QAAQ;KACxC;IACF;EACJ;CACF;CAEA,OAAO;EACL;EACA,MAAM,YAAY;GAChB,WAAW,MAAM;GACjB,cAAc,KAAK;GACnB,MAAM;GACN,OAAO,MAAM,SAAS,YAAY,KAAA,CAAS,EAAA,EAAI,MAAM;EACvD;CACF;AACF;;AAGA,MAAa,eAAe,OAAO,YAA2C;CAC5E,MAAM,SAAS,YACb,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG;CAC1D,MAAM,SAAS,cAAc;EAAE,GAAG;EAAS,MAAM;CAAM,CAAC;CACxD,MAAM,YAAY,KAAK,OAAO,KAAK,CAAC,CAAC,cAAc,QAAQ,KAAK,CAAC,CAAC;CAClE,QAAQ,KAAK,WAAW,GAAG;CAC3B,QAAQ,KAAK,UAAU,GAAG;CAC1B,WAAW,MAAM,QAAQ,gBAAgB,EAAE,OAAO,QAAQ,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"}
|
package/dist/claude.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Harnessd } from "./config.js";
|
|
2
|
+
import type { Watchdog } from "./watchdog.js";
|
|
3
|
+
/** How Claude Code names a `--plugin-dir` plugin. */
|
|
4
|
+
export declare const PLUGIN = "harnessd@inline";
|
|
5
|
+
/**
|
|
6
|
+
* Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
|
|
7
|
+
* `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
|
|
8
|
+
* changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.
|
|
9
|
+
*/
|
|
10
|
+
export declare const trustFolder: (folder: string, env?: NodeJS.ProcessEnv) => boolean;
|
|
11
|
+
/** A conversation's transcript, wherever Claude Code put it. */
|
|
12
|
+
export declare const findTranscript: (sessionId: string, env?: NodeJS.ProcessEnv) => string | undefined;
|
|
13
|
+
/** The first `name` on `path` that can run. */
|
|
14
|
+
export declare const which: (name: string, path?: string) => string;
|
|
15
|
+
/**
|
|
16
|
+
* harnessd's plugin, written before each start: one MCP server per channel of the config, each
|
|
17
|
+
* `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
|
|
18
|
+
* /clear or a /resume is the conversation the next start resumes.
|
|
19
|
+
*/
|
|
20
|
+
export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => void;
|
|
21
|
+
/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
|
|
22
|
+
export declare const skipsPermissions: (args: readonly string[]) => boolean;
|
|
23
|
+
/**
|
|
24
|
+
* The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
|
|
25
|
+
* decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
|
|
26
|
+
* its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
|
|
27
|
+
* Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
|
|
28
|
+
*/
|
|
29
|
+
export declare const claudeArgs: (o: {
|
|
30
|
+
start: Watchdog.Start;
|
|
31
|
+
plugin: string;
|
|
32
|
+
config: Harnessd.Config;
|
|
33
|
+
extra: readonly string[];
|
|
34
|
+
}) => string[];
|
|
35
|
+
export type Prestart = {
|
|
36
|
+
env: Record<string, string>;
|
|
37
|
+
args: string[];
|
|
38
|
+
};
|
|
39
|
+
/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
|
|
40
|
+
export declare const prestart: (command: string, folder: string, env: NodeJS.ProcessEnv, log: (line: string) => void) => Promise<Prestart>;
|
|
41
|
+
//# 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,qDAAqD;AACrD,eAAO,MAAM,MAAM,oBAAoB,CAAC;AAKxC;;;;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;AAIF;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,OAAO,QAAQ,CAAC,KAAK,EACrB,QAAQ,QAAQ,CAAC,MAAM,EACvB,KAAK,MAAM,SAuCZ,CAAC;AAWF,uIAAuI;AACvI,eAAO,MAAM,gBAAgB,GAAI,MAAM,SAAS,MAAM,EAAE,YAMrD,CAAC;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,UAAU,GAAI,GAAG;IAC5B,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC;IACxB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CAC1B,aAgBA,CAAC;AAEF,MAAM,MAAM,QAAQ,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAEvE,kHAAkH;AAClH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,EACf,QAAQ,MAAM,EACd,KAAK,MAAM,CAAC,UAAU,EACtB,KAAK,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,sBAyDzB,CAAC"}
|
package/dist/claude.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { delimiter, join } from "node:path";
|
|
5
|
+
// src/claude.ts
|
|
6
|
+
/** How Claude Code names a `--plugin-dir` plugin. */
|
|
7
|
+
const PLUGIN = "harnessd@inline";
|
|
8
|
+
const claudeDir = (env) => env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
9
|
+
/**
|
|
10
|
+
* Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
|
|
11
|
+
* `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
|
|
12
|
+
* changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.
|
|
13
|
+
*/
|
|
14
|
+
const trustFolder = (folder, env = process.env) => {
|
|
15
|
+
const file = env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(homedir(), ".claude.json");
|
|
16
|
+
if (!existsSync(file)) return false;
|
|
17
|
+
const text = readFileSync(file, "utf8");
|
|
18
|
+
const config = JSON.parse(text);
|
|
19
|
+
const key = realpathSync(folder);
|
|
20
|
+
if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;
|
|
21
|
+
config.projects = {
|
|
22
|
+
...config.projects,
|
|
23
|
+
[key]: {
|
|
24
|
+
...config.projects?.[key],
|
|
25
|
+
hasTrustDialogAccepted: true
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
const written = `${text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2) ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith("\n") ? "\n" : ""}`;
|
|
29
|
+
const temp = `${file}.harnessd-${process.pid}`;
|
|
30
|
+
writeFileSync(temp, written, { mode: statSync(file).mode & 511 });
|
|
31
|
+
renameSync(temp, file);
|
|
32
|
+
return true;
|
|
33
|
+
};
|
|
34
|
+
/** A conversation's transcript, wherever Claude Code put it. */
|
|
35
|
+
const findTranscript = (sessionId, env = process.env) => {
|
|
36
|
+
const projects = join(claudeDir(env), "projects");
|
|
37
|
+
try {
|
|
38
|
+
for (const dir of readdirSync(projects)) {
|
|
39
|
+
const file = join(projects, dir, `${sessionId}.jsonl`);
|
|
40
|
+
if (existsSync(file)) return file;
|
|
41
|
+
}
|
|
42
|
+
} catch {}
|
|
43
|
+
};
|
|
44
|
+
/** The first `name` on `path` that can run. */
|
|
45
|
+
const which = (name, path = process.env.PATH ?? "") => {
|
|
46
|
+
if (name.includes("/")) return name;
|
|
47
|
+
for (const dir of path.split(delimiter)) {
|
|
48
|
+
if (!dir) continue;
|
|
49
|
+
try {
|
|
50
|
+
accessSync(join(dir, name), constants.X_OK);
|
|
51
|
+
return join(dir, name);
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
throw new Error(`${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`);
|
|
55
|
+
};
|
|
56
|
+
const shellQuote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
|
|
57
|
+
/**
|
|
58
|
+
* harnessd's plugin, written before each start: one MCP server per channel of the config, each
|
|
59
|
+
* `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
|
|
60
|
+
* /clear or a /resume is the conversation the next start resumes.
|
|
61
|
+
*/
|
|
62
|
+
const writePlugin = (paths, config, bin) => {
|
|
63
|
+
rmSync(paths.plugin, {
|
|
64
|
+
recursive: true,
|
|
65
|
+
force: true
|
|
66
|
+
});
|
|
67
|
+
mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
|
|
68
|
+
const names = Object.keys(config.channels);
|
|
69
|
+
const sessionStart = [
|
|
70
|
+
...Object.entries(paths.env).map(([name, value]) => `${name}=${shellQuote(value)}`),
|
|
71
|
+
shellQuote(process.execPath),
|
|
72
|
+
shellQuote(bin),
|
|
73
|
+
"session-start"
|
|
74
|
+
].join(" ");
|
|
75
|
+
const manifest = {
|
|
76
|
+
name: "harnessd",
|
|
77
|
+
version: "1.0.0",
|
|
78
|
+
description: "harnessd's channels, each one's events and tools, and its SessionStart hook",
|
|
79
|
+
...names.length > 0 && {
|
|
80
|
+
mcpServers: Object.fromEntries(names.map((name) => [name, {
|
|
81
|
+
command: process.execPath,
|
|
82
|
+
args: [
|
|
83
|
+
bin,
|
|
84
|
+
"channel",
|
|
85
|
+
name
|
|
86
|
+
],
|
|
87
|
+
env: paths.env
|
|
88
|
+
}])),
|
|
89
|
+
channels: names.map((name) => ({
|
|
90
|
+
server: name,
|
|
91
|
+
displayName: name
|
|
92
|
+
}))
|
|
93
|
+
},
|
|
94
|
+
hooks: { SessionStart: [{ hooks: [{
|
|
95
|
+
type: "command",
|
|
96
|
+
command: sessionStart
|
|
97
|
+
}] }] }
|
|
98
|
+
};
|
|
99
|
+
writeFileSync(join(paths.plugin, ".claude-plugin", "plugin.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
100
|
+
};
|
|
101
|
+
/** Whether these claude arguments pick a permission mode themselves. */
|
|
102
|
+
const picksPermissionMode = (args) => args.some((arg) => arg === "--dangerously-skip-permissions" || arg === "--permission-mode" || arg.startsWith("--permission-mode="));
|
|
103
|
+
/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
|
|
104
|
+
const skipsPermissions = (args) => args.some((arg, i) => arg === "--dangerously-skip-permissions" || arg === "--permission-mode=bypassPermissions" || arg === "bypassPermissions" && args[i - 1] === "--permission-mode");
|
|
105
|
+
/**
|
|
106
|
+
* The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
|
|
107
|
+
* decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
|
|
108
|
+
* its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
|
|
109
|
+
* Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
|
|
110
|
+
*/
|
|
111
|
+
const claudeArgs = (o) => [
|
|
112
|
+
...picksPermissionMode([...o.config.args, ...o.extra]) ? [] : ["--permission-mode", "auto"],
|
|
113
|
+
"--plugin-dir",
|
|
114
|
+
o.plugin,
|
|
115
|
+
...Object.keys(o.config.channels).length > 0 ? ["--dangerously-load-development-channels", `plugin:${PLUGIN}`] : [],
|
|
116
|
+
...o.start.resume ? ["--resume", o.start.sessionId] : ["--session-id", o.start.sessionId],
|
|
117
|
+
...o.start.prompt ? [o.start.prompt] : [],
|
|
118
|
+
...o.config.args,
|
|
119
|
+
...o.extra
|
|
120
|
+
];
|
|
121
|
+
/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
|
|
122
|
+
const prestart = (command, folder, env, log) => new Promise((resolve, reject) => {
|
|
123
|
+
execFile("/bin/sh", ["-c", command], {
|
|
124
|
+
cwd: folder,
|
|
125
|
+
env,
|
|
126
|
+
timeout: 6e4,
|
|
127
|
+
maxBuffer: 16777216
|
|
128
|
+
}, (error, stdout, stderr) => {
|
|
129
|
+
for (const line of stderr.split("\n")) if (line.trim()) log(`prestart: ${line}`);
|
|
130
|
+
if (error) return reject(/* @__PURE__ */ new Error(`prestart failed: ${error.message.split("\n")[0]}`));
|
|
131
|
+
if (!stdout.trim()) return resolve({
|
|
132
|
+
env: {},
|
|
133
|
+
args: []
|
|
134
|
+
});
|
|
135
|
+
let parsed;
|
|
136
|
+
try {
|
|
137
|
+
parsed = JSON.parse(stdout);
|
|
138
|
+
} catch {
|
|
139
|
+
return reject(/* @__PURE__ */ new Error("prestart printed something other than JSON { env?, args? }"));
|
|
140
|
+
}
|
|
141
|
+
const { env: more = {}, args = [], ...rest } = parsed ?? {};
|
|
142
|
+
if (typeof parsed !== "object" || Object.keys(rest).length > 0 || typeof more !== "object" || more === null || Object.values(more).some((v) => typeof v !== "string") || !Array.isArray(args) || args.some((a) => typeof a !== "string")) return reject(/* @__PURE__ */ new Error("prestart's JSON must be { env?: { NAME: string }, args?: string[] }"));
|
|
143
|
+
if ("CLAUDE_CONFIG_DIR" in more) return reject(/* @__PURE__ */ new Error("prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env"));
|
|
144
|
+
resolve({
|
|
145
|
+
env: more,
|
|
146
|
+
args
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
export { PLUGIN, claudeArgs, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin };
|
|
151
|
+
|
|
152
|
+
//# sourceMappingURL=claude.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude.js","names":[],"sources":["../src/claude.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\nimport type { Watchdog } from \"./watchdog\";\n\n/** How Claude Code names a `--plugin-dir` plugin. */\nexport const PLUGIN = \"harnessd@inline\";\n\nconst claudeDir = (env: NodeJS.ProcessEnv) =>\n env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n\n/**\n * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's\n * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field\n * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.\n */\nexport const trustFolder = (\n folder: string,\n env: NodeJS.ProcessEnv = process.env,\n): boolean => {\n const file = env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, \".claude.json\")\n : join(homedir(), \".claude.json\");\n if (!existsSync(file)) return false;\n const text = readFileSync(file, \"utf8\");\n const config = JSON.parse(text) as {\n projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;\n };\n const key = realpathSync(folder);\n if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;\n config.projects = {\n ...config.projects,\n [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },\n };\n const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);\n const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n const temp = `${file}.harnessd-${process.pid}`;\n writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });\n renameSync(temp, file);\n return true;\n};\n\n/** A conversation's transcript, wherever Claude Code put it. */\nexport const findTranscript = (\n sessionId: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n const projects = join(claudeDir(env), \"projects\");\n try {\n for (const dir of readdirSync(projects)) {\n const file = join(projects, dir, `${sessionId}.jsonl`);\n if (existsSync(file)) return file;\n }\n } catch {}\n return undefined;\n};\n\n/** The first `name` on `path` that can run. */\nexport const which = (name: string, path = process.env.PATH ?? \"\") => {\n if (name.includes(\"/\")) return name;\n for (const dir of path.split(delimiter)) {\n if (!dir) continue;\n try {\n accessSync(join(dir, name), constants.X_OK);\n return join(dir, name);\n } catch {}\n }\n throw new Error(\n `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,\n );\n};\n\nconst shellQuote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/**\n * harnessd's plugin, written before each start: one MCP server per channel of the config, each\n * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a\n * /clear or a /resume is the conversation the next start resumes.\n */\nexport const writePlugin = (\n paths: Harnessd.Paths,\n config: Harnessd.Config,\n bin: string,\n) => {\n rmSync(paths.plugin, { recursive: true, force: true });\n mkdirSync(join(paths.plugin, \".claude-plugin\"), { recursive: true });\n const names = Object.keys(config.channels);\n const sessionStart = [\n ...Object.entries(paths.env).map(\n ([name, value]) => `${name}=${shellQuote(value)}`,\n ),\n shellQuote(process.execPath),\n shellQuote(bin),\n \"session-start\",\n ].join(\" \");\n const manifest = {\n name: \"harnessd\",\n version: \"1.0.0\",\n description:\n \"harnessd's channels, each one's events and tools, and its SessionStart hook\",\n ...(names.length > 0 && {\n mcpServers: Object.fromEntries(\n names.map((name) => [\n name,\n {\n command: process.execPath,\n args: [bin, \"channel\", name],\n env: paths.env,\n },\n ]),\n ),\n channels: names.map((name) => ({ server: name, displayName: name })),\n }),\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: sessionStart }] }],\n },\n };\n writeFileSync(\n join(paths.plugin, \".claude-plugin\", \"plugin.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n};\n\n/** Whether these claude arguments pick a permission mode themselves. */\nconst picksPermissionMode = (args: readonly string[]) =>\n args.some(\n (arg) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode\" ||\n arg.startsWith(\"--permission-mode=\"),\n );\n\n/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */\nexport const skipsPermissions = (args: readonly string[]) =>\n args.some(\n (arg, i) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode=bypassPermissions\" ||\n (arg === \"bypassPermissions\" && args[i - 1] === \"--permission-mode\"),\n );\n\n/**\n * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which\n * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so\n * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude\n * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).\n */\nexport const claudeArgs = (o: {\n start: Watchdog.Start;\n plugin: string;\n config: Harnessd.Config;\n extra: readonly string[];\n}) => [\n ...(picksPermissionMode([...o.config.args, ...o.extra])\n ? []\n : [\"--permission-mode\", \"auto\"]),\n \"--plugin-dir\",\n o.plugin,\n ...(Object.keys(o.config.channels).length > 0\n ? [\"--dangerously-load-development-channels\", `plugin:${PLUGIN}`]\n : []),\n ...(o.start.resume\n ? [\"--resume\", o.start.sessionId]\n : [\"--session-id\", o.start.sessionId]),\n // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value\n ...(o.start.prompt ? [o.start.prompt] : []),\n ...o.config.args,\n ...o.extra,\n];\n\nexport type Prestart = { env: Record<string, string>; args: string[] };\n\n/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */\nexport const prestart = (\n command: string,\n folder: string,\n env: NodeJS.ProcessEnv,\n log: (line: string) => void,\n) =>\n new Promise<Prestart>((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n for (const line of stderr.split(\"\\n\"))\n if (line.trim()) log(`prestart: ${line}`);\n if (error)\n return reject(\n new Error(`prestart failed: ${error.message.split(\"\\n\")[0]}`),\n );\n if (!stdout.trim()) return resolve({ env: {}, args: [] });\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n return reject(\n new Error(\n \"prestart printed something other than JSON { env?, args? }\",\n ),\n );\n }\n const {\n env: more = {},\n args = [],\n ...rest\n } = (parsed ?? {}) as { env?: unknown; args?: unknown };\n if (\n typeof parsed !== \"object\" ||\n Object.keys(rest).length > 0 ||\n typeof more !== \"object\" ||\n more === null ||\n Object.values(more).some((v) => typeof v !== \"string\") ||\n !Array.isArray(args) ||\n args.some((a) => typeof a !== \"string\")\n )\n return reject(\n new Error(\n \"prestart's JSON must be { env?: { NAME: string }, args?: string[] }\",\n ),\n );\n // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json\n if (\"CLAUDE_CONFIG_DIR\" in more)\n return reject(\n new Error(\n \"prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env\",\n ),\n );\n resolve({\n env: more as Record<string, string>,\n args: args as string[],\n });\n },\n );\n });\n"],"mappings":";;;;;;AAoBA,MAAa,SAAS;AAEtB,MAAM,aAAa,QACjB,IAAI,qBAAqB,KAAK,QAAQ,GAAG,SAAS;;;;;;AAOpD,MAAa,eACX,QACA,MAAyB,QAAQ,QACrB;CACZ,MAAM,OAAO,IAAI,oBACb,KAAK,IAAI,mBAAmB,cAAc,IAC1C,KAAK,QAAQ,GAAG,cAAc;CAClC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,MAAM,OAAO,aAAa,MAAM,MAAM;CACtC,MAAM,SAAS,KAAK,MAAM,IAAI;CAG9B,MAAM,MAAM,aAAa,MAAM;CAC/B,IAAI,OAAO,WAAW,IAAI,EAAE,2BAA2B,MAAM,OAAO;CACpE,OAAO,WAAW;EAChB,GAAG,OAAO;GACT,MAAM;GAAE,GAAG,OAAO,WAAW;GAAM,wBAAwB;EAAK;CACnE;CAEA,MAAM,UAAU,GADD,KAAK,QAAQ,MAAM,KAAK,UAAU,KAAK,MAAM,IAAI,GAAG,MAAM,CAAC,IAC9C,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,KAAK,UAAU,MAAM,IAAI,KAAK,SAAS,IAAI,IAAI,OAAO;CACpH,MAAM,OAAO,GAAG,KAAK,YAAY,QAAQ;CACzC,cAAc,MAAM,SAAS,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC,OAAO,IAAM,CAAC;CAClE,WAAW,MAAM,IAAI;CACrB,OAAO;AACT;;AAGA,MAAa,kBACX,WACA,MAAyB,QAAQ,QACV;CACvB,MAAM,WAAW,KAAK,UAA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KAAK,GAAG,IAAI,aAAa,MAAM;EAC1C,IAAI,OACF,OAAO,uBACL,IAAI,MAAM,oBAAoB,MAAM,QAAQ,MAAM,IAAI,CAAC,CAAC,IAAI,CAC9D;EACF,IAAI,CAAC,OAAO,KAAK,GAAG,OAAO,QAAQ;GAAE,KAAK,CAAC;GAAG,MAAM,CAAC;EAAE,CAAC;EACxD,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,MAAM,MAAM;EAC5B,QAAQ;GACN,OAAO,uBACL,IAAI,MACF,4DACF,CACF;EACF;EACA,MAAM,EACJ,KAAK,OAAO,CAAC,GACb,OAAO,CAAC,GACR,GAAG,SACA,UAAU,CAAC;EAChB,IACE,OAAO,WAAW,YAClB,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,KAC3B,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,OAAO,IAAI,CAAC,CAAC,MAAM,MAAM,OAAO,MAAM,QAAQ,KACrD,CAAC,MAAM,QAAQ,IAAI,KACnB,KAAK,MAAM,MAAM,OAAO,MAAM,QAAQ,GAEtC,OAAO,uBACL,IAAI,MACF,qEACF,CACF;EAEF,IAAI,uBAAuB,MACzB,OAAO,uBACL,IAAI,MACF,mEACF,CACF;EACF,QAAQ;GACN,KAAK;GACC;EACR,CAAC;CACH,CACF;AACF,CAAC"}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Setup } from "./setup.js";
|
|
2
|
+
type Io = {
|
|
3
|
+
out: (line: string) => void;
|
|
4
|
+
err: (line: string) => void;
|
|
5
|
+
/** The person to ask; none when harnessd runs from a script. */
|
|
6
|
+
terminal?: Setup.Terminal | undefined;
|
|
7
|
+
/** What the command was given on stdin, for a hook. */
|
|
8
|
+
stdin?: () => Promise<string>;
|
|
9
|
+
};
|
|
10
|
+
/** Runs one harnessd command; resolves to the exit code. */
|
|
11
|
+
export declare const runHarnessd: (argv: readonly string[], bin: string, io?: Io) => Promise<number>;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=cli.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAyBA,OAAO,EAA6C,KAAK,KAAK,EAAE,mBAAgB;AAyChF,KAAK,EAAE,GAAG;IACR,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,gEAAgE;IAChE,QAAQ,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;IACtC,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;CAC/B,CAAC;AAgcF,4DAA4D;AAC5D,eAAO,MAAM,WAAW,GACtB,MAAM,SAAS,MAAM,EAAE,EACvB,KAAK,MAAM,EACX,KAAI,EAIH,KACA,OAAO,CAAC,MAAM,CAiBhB,CAAC"}
|