@harness-sdk/harnessd 0.0.2 → 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 +20 -8
- package/dist/channel.d.ts +15 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +112 -157
- package/dist/channel.js.map +1 -1
- package/dist/claude.d.ts +9 -4
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +53 -29
- package/dist/claude.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +58 -27
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +33 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +94 -43
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +12 -0
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +66 -4
- package/dist/daemon.js.map +1 -1
- package/package.json +4 -10
- package/src/channel.ts +151 -172
- package/src/claude.ts +55 -28
- package/src/cli.ts +98 -48
- package/src/config.ts +155 -57
- package/src/daemon.ts +86 -3
package/README.md
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
harnessd keeps Claude Code running on your Mac or Linux machine, day and night, connected to the events of your agentic apps. Put it on a Mac mini and you have an agent that's always on.
|
|
4
4
|
|
|
5
5
|
- It starts at login and after any crash, and picks up the same conversation.
|
|
6
|
-
-
|
|
6
|
+
- When Claude Code's own updater installs a new version, it restarts Claude Code into it once the agent is idle.
|
|
7
|
+
- Each agentic app you connect is a server. The events you subscribe to reach the agent as they happen, and its tools are a command the agent runs to answer.
|
|
7
8
|
- Its terminal is there whenever you want it, on the Mac or over SSH.
|
|
8
9
|
|
|
9
10
|
## Install
|
|
@@ -18,37 +19,47 @@ harnessd attach
|
|
|
18
19
|
|
|
19
20
|
The agent works in `~/agent`, which harnessd marks as trusted in Claude Code. Its standing instructions go in `~/agent/CLAUDE.md`, the file Claude Code already reads. Claude Code runs in its auto permission mode, which decides each action itself. To turn permission prompts off instead, add `"args": ["--dangerously-skip-permissions"]` to the config file, and give the agent a machine of its own.
|
|
20
21
|
|
|
22
|
+
Claude Code updates itself, but a running Claude Code keeps its version until it restarts. harnessd checks for a newer installed version every hour and each time Claude Code says it's idle: no turn, no background agent, nothing on screen to answer. Once the agent is idle, harnessd restarts Claude Code into the new version, in the same conversation, and tells it it was updated. To hold a version, set `DISABLE_AUTOUPDATER=1` in Claude Code's settings and install that version with `claude install <version>`.
|
|
23
|
+
|
|
21
24
|
harnessd starts when you log in. On a Mac, turn on automatic login (System Settings, Users & Groups), so the agent comes back after a power cut. Or install it with `sudo harnessd service install`: it then starts at boot, with nobody logged in, and still runs as your user. Linux needs systemd, on x64 or arm64.
|
|
22
25
|
|
|
23
|
-
## Connect a
|
|
26
|
+
## Connect a server
|
|
24
27
|
|
|
25
|
-
A
|
|
28
|
+
A server is an MCP server, such as a [Statewire](https://www.npmjs.com/package/statewire) host. List it in `~/.config/harnessd/config.json`, and subscribe the channel to the events the agent should get:
|
|
26
29
|
|
|
27
30
|
```json
|
|
28
31
|
{
|
|
32
|
+
"compatibilityDate": "2026-12-02",
|
|
29
33
|
"folder": "~/agent",
|
|
30
|
-
"
|
|
34
|
+
"servers": {
|
|
31
35
|
"board": {
|
|
32
36
|
"url": "https://board.example.com/api/board/mcp",
|
|
33
37
|
"headers": { "Authorization": "Bearer ${BOARD_TOKEN}" }
|
|
34
38
|
}
|
|
39
|
+
},
|
|
40
|
+
"channel": {
|
|
41
|
+
"subscribe": [
|
|
42
|
+
{ "server": "board", "event": "task.handed", "arguments": { "board": "main" } }
|
|
43
|
+
]
|
|
35
44
|
}
|
|
36
45
|
}
|
|
37
46
|
```
|
|
38
47
|
|
|
39
|
-
Each event reaches the conversation as `<channel source="plugin:harnessd:board" event="
|
|
48
|
+
Each subscribed event reaches the conversation as `<channel source="plugin:harnessd:channel" server="board" event="task.handed">…</channel>`, and no other event does. The server's tools are the `board` command in the agent's shell: `board --help` lists them. If the agent restarts, the events it missed come when it's back.
|
|
40
49
|
|
|
41
|
-
harnessd loads its
|
|
50
|
+
harnessd loads its channel with Claude Code's flag for local channels and answers its start-up warning. `harnessd status` shows whether the events arrive, and says so when managed settings turn channels off.
|
|
42
51
|
|
|
43
52
|
## The config file
|
|
44
53
|
|
|
45
54
|
| Key | What it does |
|
|
46
55
|
| --- | --- |
|
|
56
|
+
| `compatibilityDate` | The date the file was written. `harnessd service install` writes it, and harnessd behaves as it did on that date. |
|
|
47
57
|
| `folder` | Where Claude Code runs. |
|
|
48
58
|
| `args` | More arguments for `claude`, such as `["--model", "opus"]` or `["--remote-control"]`. |
|
|
49
59
|
| `env` | More environment for `claude`. |
|
|
50
60
|
| `prestart` | A shell command run before each start. It prints `{ "env": {…}, "args": […] }` for that start, so a token is fetched fresh and never kept on disk. |
|
|
51
|
-
| `
|
|
61
|
+
| `servers` | MCP servers by name: a `url` (https, or http on this Mac) and `headers` that read `${VAR}` from the environment. Each one's tools are a command of its name for the agent. |
|
|
62
|
+
| `channel` | `subscribe`: the events that reach the agent, each a `server`, an `event` and its `arguments`. |
|
|
52
63
|
| `accounts` | Claude accounts by name, each with the `env` that signs it in, such as a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. When the one in use hits its usage limit or its sign-in fails, Claude Code goes on with the next, in the same conversation. |
|
|
53
64
|
|
|
54
65
|
A change takes effect at the next start: `harnessd stop`, then `harnessd start`.
|
|
@@ -59,7 +70,8 @@ A change takes effect at the next start: `harnessd stop`, then `harnessd start`.
|
|
|
59
70
|
| --- | --- |
|
|
60
71
|
| `harnessd service install` | Start harnessd now and at every login. With `sudo`: at every boot, as your user (`--user <name>` for another). Run it again after an upgrade. |
|
|
61
72
|
| `harnessd service uninstall` | Stop harnessd and remove its service (with `sudo` for a boot service). Your settings and conversation stay. |
|
|
62
|
-
| `harnessd status` | What runs, which conversation, whether events arrive, and the log's last lines and path. `--json` for scripts. |
|
|
73
|
+
| `harnessd status` | What runs, which Claude Code version and conversation, an update waiting for the agent to be idle, whether events arrive, and the log's last lines and path. `--json` for scripts. |
|
|
63
74
|
| `harnessd attach` | Claude Code's terminal. `/clear` there starts a new conversation, and restarts resume that one. |
|
|
64
75
|
| `harnessd stop`, `harnessd start` | Stop Claude Code until you start it again. harnessd itself stays up and answers `status`. |
|
|
76
|
+
| `harnessd tools <server>` | A server's tools, the same command the agent runs as `<server>`. `harnessd tools <server> login` signs in to a server that asks for OAuth. |
|
|
65
77
|
| `harnessd --version` | harnessd's version. |
|
package/dist/channel.d.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
+
import { type CliOptions } from "toolport/cli";
|
|
1
2
|
import { type Harnessd } from "./config.js";
|
|
2
3
|
export declare namespace Channel {
|
|
3
|
-
/** What
|
|
4
|
+
/** What the channel keeps in harnessd's home: where each subscription's events resume, and whether Claude Code hears them. */
|
|
4
5
|
type Status = {
|
|
5
|
-
|
|
6
|
+
/** Each subscription's cursor, by its key. */
|
|
7
|
+
readonly cursors?: Readonly<Record<string, string>>;
|
|
6
8
|
/** When this Claude Code process got its first event. */
|
|
7
9
|
readonly pushedAt?: string;
|
|
8
10
|
/** When one of its events first showed up in the conversation's transcript. */
|
|
9
11
|
readonly heardAt?: string;
|
|
10
12
|
};
|
|
11
13
|
type Options = {
|
|
12
|
-
readonly
|
|
13
|
-
readonly channel: Harnessd.Channel;
|
|
14
|
+
readonly config: Harnessd.Config;
|
|
14
15
|
readonly paths: Harnessd.Paths;
|
|
15
16
|
readonly send: (message: Record<string, unknown>) => void;
|
|
16
17
|
readonly log: (line: string) => void;
|
|
@@ -32,10 +33,14 @@ export declare namespace Channel {
|
|
|
32
33
|
}
|
|
33
34
|
/** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */
|
|
34
35
|
export declare const streamFlags: (args: Readonly<Record<string, string | number | boolean>>) => string[];
|
|
35
|
-
|
|
36
|
+
/** A server's command, `harnessd tools <server>`, which the channel's subscriptions run too: one sign-in serves both. */
|
|
37
|
+
export declare const serverCli: (paths: Harnessd.Paths, name: string, server: Harnessd.Server, env: NodeJS.ProcessEnv, fetch?: typeof globalThis.fetch) => CliOptions;
|
|
38
|
+
/** A subscription as the log and `harnessd status` name it: `board task.handed --board AUI`. */
|
|
39
|
+
export declare const subscriptionLabel: (subscription: Harnessd.Subscription) => string;
|
|
36
40
|
export declare const readStatus: (file: string) => Channel.Status;
|
|
37
41
|
/** One event as Claude Code shows it: its `text`, else its data as JSON, with its scalar fields as tag attributes and its delivery id. */
|
|
38
42
|
export declare const channelMessage: (line: {
|
|
43
|
+
server: string;
|
|
39
44
|
name: string;
|
|
40
45
|
data: unknown;
|
|
41
46
|
gap?: boolean;
|
|
@@ -45,12 +50,12 @@ export declare const channelMessage: (line: {
|
|
|
45
50
|
meta: Record<string, string>;
|
|
46
51
|
};
|
|
47
52
|
/**
|
|
48
|
-
* `harnessd channel
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
53
|
+
* `harnessd channel`: the stdio MCP server Claude Code runs for harnessd's one channel. It follows each subscription
|
|
54
|
+
* of the config (one `events/stream` each) and hands every event to Claude Code as a channel message. Where a
|
|
55
|
+
* subscription's events resume is saved only once Claude Code is seen to hear them: an event it dropped (a channel it
|
|
56
|
+
* didn't let in) comes again at the next start. The agent answers with the servers' commands, not here.
|
|
52
57
|
*/
|
|
53
58
|
export declare const channelServer: (options: Channel.Options) => Channel.Server;
|
|
54
|
-
/** Serves
|
|
59
|
+
/** Serves the channel on stdin and stdout until Claude Code closes stdin. */
|
|
55
60
|
export declare const serveChannel: (options: Omit<Channel.Options, "send">) => Promise<void>;
|
|
56
61
|
//# sourceMappingURL=channel.d.ts.map
|
package/dist/channel.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"m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
|
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
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { createInterface } from "node:readline";
|
|
6
|
-
import { randomBytes } from "node:crypto";
|
|
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
|