@harness-sdk/harnessd 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -18
- 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.js +4 -0
- package/dist/bin.js.map +1 -1
- package/dist/channel.d.ts +15 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +113 -158
- package/dist/channel.js.map +1 -1
- package/dist/claude.d.ts +17 -13
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +69 -59
- package/dist/claude.js.map +1 -1
- package/dist/cli.d.ts +5 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +317 -131
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +46 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +142 -51
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +29 -4
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +174 -51
- package/dist/daemon.js.map +1 -1
- package/dist/launchd.d.ts +12 -16
- package/dist/launchd.d.ts.map +1 -1
- package/dist/launchd.js +28 -25
- package/dist/launchd.js.map +1 -1
- 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/watchdog.d.ts +14 -4
- package/dist/watchdog.d.ts.map +1 -1
- package/dist/watchdog.js +30 -24
- package/dist/watchdog.js.map +1 -1
- package/package.json +8 -12
- package/src/accounts.ts +242 -0
- package/src/bin.ts +6 -0
- package/src/channel.ts +151 -172
- package/src/claude.ts +90 -88
- package/src/cli.ts +494 -183
- package/src/config.ts +239 -63
- package/src/daemon.ts +215 -65
- package/src/launchd.ts +40 -35
- 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/watchdog.ts +41 -33
package/dist/channel.js
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
|
-
import { findTranscript } from "./claude.js";
|
|
2
|
-
import { headersOf } from "./config.js";
|
|
1
|
+
import { CHANNEL_SERVER, findTranscript } from "./claude.js";
|
|
2
|
+
import { headersOf, subscriptionKey } from "./config.js";
|
|
3
3
|
import { closeSync, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { createInterface } from "node:readline";
|
|
5
4
|
import { dirname, join } from "node:path";
|
|
6
|
-
import {
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
7
6
|
import { runCli } from "toolport/cli";
|
|
8
|
-
import {
|
|
9
|
-
import { fromMcpServer } from "toolport/mcp-client";
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
10
8
|
// src/channel.ts
|
|
11
9
|
const CHANNEL = "notifications/claude/channel";
|
|
12
10
|
const PROTOCOL = "2025-06-18";
|
|
13
11
|
const protocolFor = (asked) => typeof asked === "string" && /^\d{4}-\d{2}-\d{2}$/.test(asked) && asked < "2026-07-28" ? asked : PROTOCOL;
|
|
14
12
|
const START_MS = 1500;
|
|
15
13
|
const CHECK_MS = 5e3;
|
|
16
|
-
const CONNECT_WAIT_MS = 5e3;
|
|
17
14
|
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
18
15
|
const unref = (timer) => timer.unref?.();
|
|
19
16
|
/** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */
|
|
@@ -21,7 +18,23 @@ const streamFlags = (args) => Object.entries(args).flatMap(([key, value]) => {
|
|
|
21
18
|
const flag = key.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
|
|
22
19
|
return typeof value === "boolean" ? [value ? `--${flag}` : `--no-${flag}`] : [`--${flag}`, String(value)];
|
|
23
20
|
});
|
|
24
|
-
|
|
21
|
+
/** A server's command, `harnessd tools <server>`, which the channel's subscriptions run too: one sign-in serves both. */
|
|
22
|
+
const serverCli = (paths, name, server, env, fetch) => ({
|
|
23
|
+
name,
|
|
24
|
+
configDir: join(paths.home, "auth"),
|
|
25
|
+
servers: { [name]: {
|
|
26
|
+
url: server.url,
|
|
27
|
+
headers: headersOf(server, env),
|
|
28
|
+
root: true,
|
|
29
|
+
...fetch && { fetch }
|
|
30
|
+
} }
|
|
31
|
+
});
|
|
32
|
+
/** A subscription as the log and `harnessd status` name it: `board task.handed --board AUI`. */
|
|
33
|
+
const subscriptionLabel = (subscription) => [
|
|
34
|
+
subscription.server,
|
|
35
|
+
subscription.event,
|
|
36
|
+
...streamFlags(subscription.arguments)
|
|
37
|
+
].join(" ");
|
|
25
38
|
const readStatus = (file) => {
|
|
26
39
|
try {
|
|
27
40
|
return JSON.parse(readFileSync(file, "utf8"));
|
|
@@ -29,17 +42,12 @@ const readStatus = (file) => {
|
|
|
29
42
|
return {};
|
|
30
43
|
}
|
|
31
44
|
};
|
|
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
45
|
/** 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
46
|
const channelMessage = (line) => {
|
|
40
47
|
if (line.gap) return {
|
|
41
|
-
content: `Some ${line.name} events were missed (
|
|
48
|
+
content: `Some ${line.name} events were missed (${line.server} no longer had them): read its state again.`,
|
|
42
49
|
meta: {
|
|
50
|
+
server: line.server,
|
|
43
51
|
event: line.name,
|
|
44
52
|
gap: "true",
|
|
45
53
|
delivery: line.delivery
|
|
@@ -51,6 +59,7 @@ const channelMessage = (line) => {
|
|
|
51
59
|
if (key === "text" || key === "source" || !IDENTIFIER.test(key)) continue;
|
|
52
60
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") meta[key] = String(value).replace(/[<>"]/g, "").slice(0, 200);
|
|
53
61
|
}
|
|
62
|
+
meta.server = line.server;
|
|
54
63
|
meta.event = line.name;
|
|
55
64
|
meta.delivery = line.delivery;
|
|
56
65
|
const text = data?.text;
|
|
@@ -96,116 +105,125 @@ const sizeOf = (file) => {
|
|
|
96
105
|
}
|
|
97
106
|
};
|
|
98
107
|
/**
|
|
99
|
-
* `harnessd channel
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
108
|
+
* `harnessd channel`: the stdio MCP server Claude Code runs for harnessd's one channel. It follows each subscription
|
|
109
|
+
* of the config (one `events/stream` each) and hands every event to Claude Code as a channel message. Where a
|
|
110
|
+
* subscription's events resume is saved only once Claude Code is seen to hear them: an event it dropped (a channel it
|
|
111
|
+
* didn't let in) comes again at the next start. The agent answers with the servers' commands, not here.
|
|
103
112
|
*/
|
|
104
113
|
const channelServer = (options) => {
|
|
105
114
|
const env = options.env ?? process.env;
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
115
|
+
const { servers } = options.config;
|
|
116
|
+
const subscriptions = options.config.channel.subscribe.map((subscription) => ({
|
|
117
|
+
subscription,
|
|
118
|
+
key: subscriptionKey(subscription)
|
|
119
|
+
}));
|
|
120
|
+
const source = `plugin:harnessd:${CHANNEL_SERVER}`;
|
|
121
|
+
const file = options.paths.channel;
|
|
122
|
+
const saved = readStatus(file).cursors ?? {};
|
|
123
|
+
const cursors = Object.fromEntries(subscriptions.flatMap(({ key }) => typeof saved[key] === "string" ? [[key, saved[key]]] : []));
|
|
124
|
+
let status = { cursors };
|
|
125
|
+
const save = (patch) => {
|
|
126
|
+
status = {
|
|
127
|
+
...status,
|
|
128
|
+
...patch
|
|
129
|
+
};
|
|
130
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
131
|
+
const temp = `${file}.${process.pid}`;
|
|
132
|
+
writeFileSync(temp, `${JSON.stringify(status)}\n`);
|
|
133
|
+
renameSync(temp, file);
|
|
134
|
+
};
|
|
135
|
+
save({});
|
|
111
136
|
const controller = new AbortController();
|
|
112
137
|
let following;
|
|
113
138
|
const transcript = () => env.CLAUDE_CODE_SESSION_ID ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env) : void 0;
|
|
114
139
|
let from = sizeOf(transcript());
|
|
115
140
|
const nonce = randomBytes(4).toString("hex");
|
|
116
141
|
let delivery = 0;
|
|
117
|
-
let lastCursor = status.cursor;
|
|
118
142
|
const unconfirmed = [];
|
|
119
143
|
const heard = /* @__PURE__ */ new Set();
|
|
120
144
|
let check;
|
|
121
|
-
const save = (patch) => {
|
|
122
|
-
status = {
|
|
123
|
-
...status,
|
|
124
|
-
...patch
|
|
125
|
-
};
|
|
126
|
-
writeStatus(file, status);
|
|
127
|
-
};
|
|
128
145
|
const confirm = () => {
|
|
129
146
|
const at = transcript();
|
|
130
147
|
if (at === void 0) return;
|
|
131
148
|
const read = deliveriesIn(at, from, source);
|
|
132
149
|
from = read.next;
|
|
133
150
|
for (const n of read.found) heard.add(n);
|
|
134
|
-
|
|
151
|
+
const moved = {};
|
|
135
152
|
while (unconfirmed.length > 0 && heard.has(unconfirmed[0].delivery)) {
|
|
136
153
|
const event = unconfirmed.shift();
|
|
137
154
|
heard.delete(event.delivery);
|
|
138
|
-
cursor
|
|
155
|
+
if (event.cursor !== void 0) moved[event.key] = event.cursor;
|
|
139
156
|
if (!status.heardAt) {
|
|
140
157
|
save({ heardAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
141
|
-
options.log(
|
|
158
|
+
options.log("Claude Code hears the channel's events");
|
|
142
159
|
}
|
|
143
160
|
}
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
});
|
|
161
|
+
if (Object.keys(moved).length > 0) save({ cursors: {
|
|
162
|
+
...status.cursors,
|
|
163
|
+
...moved
|
|
164
|
+
} });
|
|
176
165
|
};
|
|
177
|
-
const follow = async () => {
|
|
166
|
+
const follow = async ({ subscription, key }) => {
|
|
167
|
+
const label = subscriptionLabel(subscription);
|
|
168
|
+
const server = servers[subscription.server];
|
|
169
|
+
let lastCursor = cursors[key];
|
|
170
|
+
const onLine = (raw) => {
|
|
171
|
+
let line;
|
|
172
|
+
try {
|
|
173
|
+
line = JSON.parse(raw);
|
|
174
|
+
} catch {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (typeof line.name !== "string") return;
|
|
178
|
+
if (!status.pushedAt) save({ pushedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
179
|
+
if (!check) {
|
|
180
|
+
check = setInterval(confirm, options.checkMs ?? CHECK_MS);
|
|
181
|
+
unref(check);
|
|
182
|
+
}
|
|
183
|
+
const cursor = typeof line.cursor === "string" && line.cursor ? line.cursor : void 0;
|
|
184
|
+
if (cursor) lastCursor = cursor;
|
|
185
|
+
const id = `${nonce}.${++delivery}`;
|
|
186
|
+
unconfirmed.push({
|
|
187
|
+
delivery: id,
|
|
188
|
+
key,
|
|
189
|
+
cursor
|
|
190
|
+
});
|
|
191
|
+
options.send({
|
|
192
|
+
jsonrpc: "2.0",
|
|
193
|
+
method: CHANNEL,
|
|
194
|
+
params: channelMessage({
|
|
195
|
+
server: subscription.server,
|
|
196
|
+
name: line.name,
|
|
197
|
+
data: line.data ?? null,
|
|
198
|
+
...line.gap && { gap: true },
|
|
199
|
+
delivery: id
|
|
200
|
+
})
|
|
201
|
+
});
|
|
202
|
+
};
|
|
178
203
|
let backoff = 5e3;
|
|
179
204
|
while (!controller.signal.aborted) {
|
|
180
205
|
const startedAt = Date.now();
|
|
181
206
|
let code;
|
|
182
207
|
try {
|
|
183
208
|
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
|
-
}, {
|
|
209
|
+
code = await runCli(serverCli(options.paths, subscription.server, server, env, options.fetch), {
|
|
193
210
|
argv: [
|
|
194
211
|
"stream",
|
|
212
|
+
subscription.event,
|
|
195
213
|
...cursor ? ["--from", cursor] : [],
|
|
196
|
-
...streamFlags(
|
|
214
|
+
...streamFlags(subscription.arguments)
|
|
197
215
|
],
|
|
198
216
|
stdout: onLine,
|
|
199
|
-
stderr: (line) => options.log(`${
|
|
217
|
+
stderr: (line) => options.log(`${label}: ${line}`),
|
|
200
218
|
signal: controller.signal
|
|
201
219
|
});
|
|
202
220
|
} catch (error) {
|
|
203
221
|
code = 1;
|
|
204
|
-
options.log(`${
|
|
222
|
+
options.log(`${label}: ${error instanceof Error ? error.message : String(error)}`);
|
|
205
223
|
}
|
|
206
224
|
if (controller.signal.aborted) return;
|
|
207
225
|
if (Date.now() - startedAt > 6e5) backoff = 5e3;
|
|
208
|
-
options.log(`${
|
|
226
|
+
options.log(`${label}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1e3)}s`);
|
|
209
227
|
await new Promise((resolve) => {
|
|
210
228
|
const timer = setTimeout(resolve, backoff);
|
|
211
229
|
controller.signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
|
|
@@ -213,42 +231,8 @@ const channelServer = (options) => {
|
|
|
213
231
|
backoff = Math.min(backoff * 2, 3e5);
|
|
214
232
|
}
|
|
215
233
|
};
|
|
216
|
-
|
|
217
|
-
|
|
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(" ");
|
|
234
|
+
const names = Object.keys(servers);
|
|
235
|
+
const instructions = [`Events arrive here for the whole session, one per message: <channel source="${source}" server="…" event="…" …>the event</channel>. Act on each.`, `To answer or act, run the server's command in the shell: ${names.map((name) => `\`${name}\``).join(", ")}. \`<command> --help\` lists its tools.`].join(" ");
|
|
252
236
|
const handle = async (request) => {
|
|
253
237
|
const result = (value) => ({
|
|
254
238
|
jsonrpc: "2.0",
|
|
@@ -256,48 +240,20 @@ const channelServer = (options) => {
|
|
|
256
240
|
result: value
|
|
257
241
|
});
|
|
258
242
|
switch (request.method) {
|
|
259
|
-
case "initialize": {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
name: `harnessd-${options.name}`,
|
|
269
|
-
version: "1.0.0"
|
|
270
|
-
},
|
|
271
|
-
instructions: instructions(kit?.description)
|
|
272
|
-
});
|
|
273
|
-
}
|
|
243
|
+
case "initialize": return result({
|
|
244
|
+
protocolVersion: protocolFor(request.params?.protocolVersion),
|
|
245
|
+
capabilities: { experimental: { "claude/channel": {} } },
|
|
246
|
+
serverInfo: {
|
|
247
|
+
name: "harnessd",
|
|
248
|
+
version: "1.0.0"
|
|
249
|
+
},
|
|
250
|
+
instructions
|
|
251
|
+
});
|
|
274
252
|
case "notifications/initialized":
|
|
275
253
|
unref(setTimeout(() => {
|
|
276
|
-
if (!controller.signal.aborted) following ??= follow
|
|
254
|
+
if (!controller.signal.aborted) following ??= Promise.all(subscriptions.map(follow));
|
|
277
255
|
}, options.startMs ?? START_MS));
|
|
278
256
|
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
257
|
case "ping": return result({});
|
|
302
258
|
default:
|
|
303
259
|
if (request.id === void 0) return void 0;
|
|
@@ -317,11 +273,10 @@ const channelServer = (options) => {
|
|
|
317
273
|
controller.abort();
|
|
318
274
|
clearInterval(check);
|
|
319
275
|
await following;
|
|
320
|
-
await (await toolkit?.catch(() => void 0))?.close();
|
|
321
276
|
}
|
|
322
277
|
};
|
|
323
278
|
};
|
|
324
|
-
/** Serves
|
|
279
|
+
/** Serves the channel on stdin and stdout until Claude Code closes stdin. */
|
|
325
280
|
const serveChannel = async (options) => {
|
|
326
281
|
const write = (message) => void process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
327
282
|
const server = channelServer({
|
|
@@ -351,6 +306,6 @@ const serveChannel = async (options) => {
|
|
|
351
306
|
}
|
|
352
307
|
await server.stop();
|
|
353
308
|
};
|
|
354
|
-
export { channelMessage, channelServer, readStatus, serveChannel,
|
|
309
|
+
export { channelMessage, channelServer, readStatus, serveChannel, serverCli, streamFlags, subscriptionLabel };
|
|
355
310
|
|
|
356
311
|
//# sourceMappingURL=channel.js.map
|
package/dist/channel.js.map
CHANGED
|
@@ -1 +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,CAA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AAO,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"}
|
|
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, type CliOptions } from \"toolport/cli\";\nimport { CHANNEL_SERVER, findTranscript } from \"./claude\";\nimport { headersOf, subscriptionKey, type Harnessd } from \"./config\";\n\nexport namespace Channel {\n /** What the channel keeps in harnessd's home: where each subscription's events resume, and whether Claude Code hears them. */\n export type Status = {\n /** Each subscription's cursor, by its key. */\n readonly cursors?: Readonly<Record<string, 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 config: Harnessd.Config;\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 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\n/** A server's command, `harnessd tools <server>`, which the channel's subscriptions run too: one sign-in serves both. */\nexport const serverCli = (\n paths: Harnessd.Paths,\n name: string,\n server: Harnessd.Server,\n env: NodeJS.ProcessEnv,\n fetch?: typeof globalThis.fetch,\n): CliOptions => ({\n name,\n configDir: join(paths.home, \"auth\"),\n servers: {\n [name]: {\n url: server.url,\n headers: headersOf(server, env),\n root: true,\n ...(fetch && { fetch }),\n },\n },\n});\n\n/** A subscription as the log and `harnessd status` name it: `board task.handed --board AUI`. */\nexport const subscriptionLabel = (subscription: Harnessd.Subscription) =>\n [\n subscription.server,\n subscription.event,\n ...streamFlags(subscription.arguments),\n ].join(\" \");\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\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 server: string;\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 (${line.server} no longer had them): read its state again.`,\n meta: {\n server: line.server,\n event: line.name,\n gap: \"true\",\n delivery: line.delivery,\n },\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.server = line.server;\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`: the stdio MCP server Claude Code runs for harnessd's one channel. It follows each subscription\n * of the config (one `events/stream` each) and hands every event to Claude Code as a channel message. Where a\n * subscription's events resume is saved only once Claude Code is seen to hear them: an event it dropped (a channel it\n * didn't let in) comes again at the next start. The agent answers with the servers' commands, not here.\n */\nexport const channelServer = (options: Channel.Options): Channel.Server => {\n const env = options.env ?? process.env;\n const { servers } = options.config;\n const subscriptions = options.config.channel.subscribe.map(\n (subscription) => ({ subscription, key: subscriptionKey(subscription) }),\n );\n const source = `plugin:harnessd:${CHANNEL_SERVER}`;\n const file = options.paths.channel;\n const saved = readStatus(file).cursors ?? {};\n // a subscription no longer in the config leaves no cursor behind\n const cursors: Record<string, string> = Object.fromEntries(\n subscriptions.flatMap(({ key }) =>\n typeof saved[key] === \"string\" ? [[key, saved[key]]] : [],\n ),\n );\n let status: Channel.Status = { cursors };\n const save = (patch: Channel.Status) => {\n status = { ...status, ...patch };\n mkdirSync(dirname(file), { recursive: true });\n // replaced whole, so a crash mid-write never loses a cursor\n const temp = `${file}.${process.pid}`;\n writeFileSync(temp, `${JSON.stringify(status)}\\n`);\n renameSync(temp, file);\n };\n save({});\n const controller = new AbortController();\n let following: Promise<unknown> | 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 const unconfirmed: {\n delivery: string;\n key: string;\n cursor: string | undefined;\n }[] = [];\n const heard = new Set<string>();\n let check: ReturnType<typeof setInterval> | undefined;\n\n // A 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 const moved: Record<string, string> = {};\n while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {\n const event = unconfirmed.shift()!;\n heard.delete(event.delivery);\n if (event.cursor !== undefined) moved[event.key] = event.cursor;\n if (!status.heardAt) {\n save({ heardAt: new Date().toISOString() });\n options.log(\"Claude Code hears the channel's events\");\n }\n }\n if (Object.keys(moved).length > 0)\n save({ cursors: { ...status.cursors, ...moved } });\n };\n\n const follow = async ({\n subscription,\n key,\n }: (typeof subscriptions)[number]) => {\n const label = subscriptionLabel(subscription);\n const server = servers[subscription.server]!;\n // where a reconnect of this process resumes: past every event sent, heard or not\n let lastCursor: string | undefined = cursors[key];\n const onLine = (raw: string) => {\n let line: {\n name?: string;\n data?: unknown;\n cursor?: string;\n gap?: boolean;\n };\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\n ? line.cursor\n : undefined;\n if (cursor) lastCursor = cursor;\n const id = `${nonce}.${++delivery}`;\n unconfirmed.push({ delivery: id, key, cursor });\n options.send({\n jsonrpc: \"2.0\",\n method: CHANNEL,\n params: channelMessage({\n server: subscription.server,\n name: line.name,\n data: line.data ?? null,\n ...(line.gap && { gap: true }),\n delivery: id,\n }),\n });\n };\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 serverCli(\n options.paths,\n subscription.server,\n server,\n env,\n options.fetch,\n ),\n {\n argv: [\n \"stream\",\n subscription.event,\n ...(cursor ? [\"--from\", cursor] : []),\n ...streamFlags(subscription.arguments),\n ],\n stdout: onLine,\n stderr: (line) => options.log(`${label}: ${line}`),\n signal: controller.signal,\n },\n );\n } catch (error) {\n code = 1;\n options.log(\n `${label}: ${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 `${label}: 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 const names = Object.keys(servers);\n const instructions = [\n `Events arrive here for the whole session, one per message: <channel source=\"${source}\" server=\"…\" event=\"…\" …>the event</channel>. Act on each.`,\n `To answer or act, run the server's command in the shell: ${names.map((name) => `\\`${name}\\``).join(\", \")}. \\`<command> --help\\` lists its tools.`,\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 return result({\n protocolVersion: protocolFor(request.params?.protocolVersion),\n capabilities: { experimental: { \"claude/channel\": {} } },\n serverInfo: { name: \"harnessd\", version: \"1.0.0\" },\n instructions,\n });\n case \"notifications/initialized\":\n unref(\n setTimeout(() => {\n if (!controller.signal.aborted)\n following ??= Promise.all(subscriptions.map(follow));\n }, options.startMs ?? START_MS),\n );\n return undefined;\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 },\n };\n};\n\n/** Serves the 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":";;;;;;;;AAsDA,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,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;;AAGH,MAAa,aACX,OACA,MACA,QACA,KACA,WACgB;CAChB;CACA,WAAW,KAAK,MAAM,MAAM,MAAM;CAClC,SAAS,GACN,OAAO;EACN,KAAK,OAAO;EACZ,SAAS,UAAU,QAAQ,GAAG;EAC9B,MAAM;EACN,GAAI,SAAS,EAAE,MAAM;CACvB,EACF;AACF;;AAGA,MAA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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;EACR;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
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { Harnessd } from "./config.js";
|
|
2
2
|
import type { Watchdog } from "./watchdog.js";
|
|
3
|
-
/** How Claude Code names a `--plugin-dir` plugin
|
|
3
|
+
/** How Claude Code names a `--plugin-dir` plugin. */
|
|
4
4
|
export declare const PLUGIN = "harnessd@inline";
|
|
5
|
-
|
|
5
|
+
/** The channel's MCP server in harnessd's plugin, and so each event's `source`: `plugin:harnessd:channel`. */
|
|
6
|
+
export declare const CHANNEL_SERVER = "channel";
|
|
6
7
|
/**
|
|
7
8
|
* Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
|
|
8
9
|
* `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
|
|
@@ -14,18 +15,25 @@ export declare const findTranscript: (sessionId: string, env?: NodeJS.ProcessEnv
|
|
|
14
15
|
/** The first `name` on `path` that can run. */
|
|
15
16
|
export declare const which: (name: string, path?: string) => string;
|
|
16
17
|
/**
|
|
17
|
-
* harnessd's plugin, written before each start
|
|
18
|
-
* `harnessd
|
|
18
|
+
* harnessd's plugin, written before each start: the channel's MCP server (`harnessd channel`) when the config
|
|
19
|
+
* subscribes to events, a command per server in its `bin` (`harnessd tools <server>`), a SessionStart hook that
|
|
20
|
+
* tells harnessd which conversation Claude Code is in, so a /clear or a /resume is the conversation the next start
|
|
21
|
+
* resumes, and a Notification hook that tells harnessd when Claude Code waits for input with nothing running.
|
|
19
22
|
*/
|
|
20
|
-
export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) =>
|
|
23
|
+
export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => void;
|
|
24
|
+
/** The version a claude command prints, such as `2.1.335`; none when it doesn't run or prints no version. */
|
|
25
|
+
export declare const claudeVersion: (file: string, env: NodeJS.ProcessEnv) => Promise<string | undefined>;
|
|
26
|
+
/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
|
|
27
|
+
export declare const skipsPermissions: (args: readonly string[]) => boolean;
|
|
21
28
|
/**
|
|
22
|
-
* The claude command line for one start (after the binary).
|
|
23
|
-
*
|
|
29
|
+
* The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
|
|
30
|
+
* decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
|
|
31
|
+
* its channel loads with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
|
|
32
|
+
* Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
|
|
24
33
|
*/
|
|
25
34
|
export declare const claudeArgs: (o: {
|
|
26
35
|
start: Watchdog.Start;
|
|
27
|
-
plugin: string
|
|
28
|
-
allowed: boolean;
|
|
36
|
+
plugin: string;
|
|
29
37
|
config: Harnessd.Config;
|
|
30
38
|
extra: readonly string[];
|
|
31
39
|
}) => string[];
|
|
@@ -35,8 +43,4 @@ export type Prestart = {
|
|
|
35
43
|
};
|
|
36
44
|
/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
|
|
37
45
|
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
46
|
//# sourceMappingURL=claude.d.ts.map
|
package/dist/claude.d.ts.map
CHANGED
|
@@ -1 +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,
|
|
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;AAExC,8GAA8G;AAC9G,eAAO,MAAM,cAAc,YAAY,CAAC;AAKxC;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,EACd,MAAK,M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