@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/src/channel.ts CHANGED
@@ -11,16 +11,15 @@ import {
11
11
  import { randomBytes } from "node:crypto";
12
12
  import { dirname, join } from "node:path";
13
13
  import { createInterface } from "node:readline";
14
- import { runCli } from "toolport/cli";
15
- import { handleMcpMessage } from "toolport/mcp";
16
- import { fromMcpServer, type McpToolkit } from "toolport/mcp-client";
17
- import { findTranscript } from "./claude";
18
- import { headersOf, type Harnessd } from "./config";
14
+ import { runCli, type CliOptions } from "toolport/cli";
15
+ import { CHANNEL_SERVER, findTranscript } from "./claude";
16
+ import { headersOf, subscriptionKey, type Harnessd } from "./config";
19
17
 
20
18
  export namespace Channel {
21
- /** What a channel keeps in harnessd's home: where its events resume, and whether Claude Code hears them. */
19
+ /** What the channel keeps in harnessd's home: where each subscription's events resume, and whether Claude Code hears them. */
22
20
  export type Status = {
23
- readonly cursor?: string;
21
+ /** Each subscription's cursor, by its key. */
22
+ readonly cursors?: Readonly<Record<string, string>>;
24
23
  /** When this Claude Code process got its first event. */
25
24
  readonly pushedAt?: string;
26
25
  /** When one of its events first showed up in the conversation's transcript. */
@@ -28,8 +27,7 @@ export namespace Channel {
28
27
  };
29
28
 
30
29
  export type Options = {
31
- readonly name: string;
32
- readonly channel: Harnessd.Channel;
30
+ readonly config: Harnessd.Config;
33
31
  readonly paths: Harnessd.Paths;
34
32
  readonly send: (message: Record<string, unknown>) => void;
35
33
  readonly log: (line: string) => void;
@@ -66,7 +64,6 @@ const protocolFor = (asked: unknown) =>
66
64
  // Claude Code drops what a channel sends before it registers, just after `initialized`
67
65
  const START_MS = 1500;
68
66
  const CHECK_MS = 5000;
69
- const CONNECT_WAIT_MS = 5000;
70
67
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
71
68
  const unref = (timer: unknown) => (timer as { unref?: () => void }).unref?.();
72
69
 
@@ -84,8 +81,33 @@ export const streamFlags = (
84
81
  : [`--${flag}`, String(value)];
85
82
  });
86
83
 
87
- export const statusFile = (paths: Harnessd.Paths, name: string) =>
88
- join(paths.channels, `${name}.json`);
84
+ /** A server's command, `harnessd tools <server>`, which the channel's subscriptions run too: one sign-in serves both. */
85
+ export const serverCli = (
86
+ paths: Harnessd.Paths,
87
+ name: string,
88
+ server: Harnessd.Server,
89
+ env: NodeJS.ProcessEnv,
90
+ fetch?: typeof globalThis.fetch,
91
+ ): CliOptions => ({
92
+ name,
93
+ configDir: join(paths.home, "auth"),
94
+ servers: {
95
+ [name]: {
96
+ url: server.url,
97
+ headers: headersOf(server, env),
98
+ root: true,
99
+ ...(fetch && { fetch }),
100
+ },
101
+ },
102
+ });
103
+
104
+ /** A subscription as the log and `harnessd status` name it: `board task.handed --board AUI`. */
105
+ export const subscriptionLabel = (subscription: Harnessd.Subscription) =>
106
+ [
107
+ subscription.server,
108
+ subscription.event,
109
+ ...streamFlags(subscription.arguments),
110
+ ].join(" ");
89
111
 
90
112
  export const readStatus = (file: string): Channel.Status => {
91
113
  try {
@@ -95,16 +117,9 @@ export const readStatus = (file: string): Channel.Status => {
95
117
  }
96
118
  };
97
119
 
98
- const writeStatus = (file: string, status: Channel.Status) => {
99
- mkdirSync(dirname(file), { recursive: true });
100
- // replaced whole, so a crash mid-write never loses the cursor
101
- const temp = `${file}.${process.pid}`;
102
- writeFileSync(temp, `${JSON.stringify(status)}\n`);
103
- renameSync(temp, file);
104
- };
105
-
106
120
  /** 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. */
107
121
  export const channelMessage = (line: {
122
+ server: string;
108
123
  name: string;
109
124
  data: unknown;
110
125
  gap?: boolean;
@@ -112,8 +127,13 @@ export const channelMessage = (line: {
112
127
  }) => {
113
128
  if (line.gap)
114
129
  return {
115
- content: `Some ${line.name} events were missed (the server no longer had them): read its state again.`,
116
- meta: { event: line.name, gap: "true", delivery: line.delivery },
130
+ content: `Some ${line.name} events were missed (${line.server} no longer had them): read its state again.`,
131
+ meta: {
132
+ server: line.server,
133
+ event: line.name,
134
+ gap: "true",
135
+ delivery: line.delivery,
136
+ },
117
137
  };
118
138
  const data = line.data;
119
139
  const meta: Record<string, string> = {};
@@ -127,6 +147,7 @@ export const channelMessage = (line: {
127
147
  )
128
148
  meta[key] = String(value).replace(/[<>"]/g, "").slice(0, 200);
129
149
  }
150
+ meta.server = line.server;
130
151
  meta.event = line.name;
131
152
  meta.delivery = line.delivery;
132
153
  const text = (data as { text?: unknown } | null)?.text;
@@ -173,20 +194,38 @@ const sizeOf = (file: string | undefined) => {
173
194
  };
174
195
 
175
196
  /**
176
- * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push
177
- * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so
178
- * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it
179
- * dropped (a channel it didn't let in) comes again at the next start.
197
+ * `harnessd channel`: the stdio MCP server Claude Code runs for harnessd's one channel. It follows each subscription
198
+ * of the config (one `events/stream` each) and hands every event to Claude Code as a channel message. Where a
199
+ * subscription's events resume is saved only once Claude Code is seen to hear them: an event it dropped (a channel it
200
+ * didn't let in) comes again at the next start. The agent answers with the servers' commands, not here.
180
201
  */
181
202
  export const channelServer = (options: Channel.Options): Channel.Server => {
182
203
  const env = options.env ?? process.env;
183
- const source = `plugin:harnessd:${options.name}`;
184
- const file = statusFile(options.paths, options.name);
185
- const saved = readStatus(file);
186
- let status: Channel.Status = saved.cursor ? { cursor: saved.cursor } : {};
187
- writeStatus(file, status);
204
+ const { servers } = options.config;
205
+ const subscriptions = options.config.channel.subscribe.map(
206
+ (subscription) => ({ subscription, key: subscriptionKey(subscription) }),
207
+ );
208
+ const source = `plugin:harnessd:${CHANNEL_SERVER}`;
209
+ const file = options.paths.channel;
210
+ const saved = readStatus(file).cursors ?? {};
211
+ // a subscription no longer in the config leaves no cursor behind
212
+ const cursors: Record<string, string> = Object.fromEntries(
213
+ subscriptions.flatMap(({ key }) =>
214
+ typeof saved[key] === "string" ? [[key, saved[key]]] : [],
215
+ ),
216
+ );
217
+ let status: Channel.Status = { cursors };
218
+ const save = (patch: Channel.Status) => {
219
+ status = { ...status, ...patch };
220
+ mkdirSync(dirname(file), { recursive: true });
221
+ // replaced whole, so a crash mid-write never loses a cursor
222
+ const temp = `${file}.${process.pid}`;
223
+ writeFileSync(temp, `${JSON.stringify(status)}\n`);
224
+ renameSync(temp, file);
225
+ };
226
+ save({});
188
227
  const controller = new AbortController();
189
- let following: Promise<void> | undefined;
228
+ let following: Promise<unknown> | undefined;
190
229
  const transcript = () =>
191
230
  env.CLAUDE_CODE_SESSION_ID
192
231
  ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env)
@@ -196,67 +235,80 @@ export const channelServer = (options: Channel.Options): Channel.Server => {
196
235
  // a payload can't name a later event's delivery: each run's numbers carry a random prefix
197
236
  const nonce = randomBytes(4).toString("hex");
198
237
  let delivery = 0;
199
- let lastCursor = status.cursor;
200
- const unconfirmed: { delivery: string; cursor: string | undefined }[] = [];
238
+ const unconfirmed: {
239
+ delivery: string;
240
+ key: string;
241
+ cursor: string | undefined;
242
+ }[] = [];
201
243
  const heard = new Set<string>();
202
244
  let check: ReturnType<typeof setInterval> | undefined;
203
245
 
204
- const save = (patch: Channel.Status) => {
205
- status = { ...status, ...patch };
206
- writeStatus(file, status);
207
- };
208
-
209
- // The cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.
246
+ // A cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.
210
247
  const confirm = () => {
211
248
  const at = transcript();
212
249
  if (at === undefined) return;
213
250
  const read = deliveriesIn(at, from, source);
214
251
  from = read.next;
215
252
  for (const n of read.found) heard.add(n);
216
- let cursor: string | undefined;
253
+ const moved: Record<string, string> = {};
217
254
  while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {
218
255
  const event = unconfirmed.shift()!;
219
256
  heard.delete(event.delivery);
220
- cursor = event.cursor ?? cursor;
257
+ if (event.cursor !== undefined) moved[event.key] = event.cursor;
221
258
  if (!status.heardAt) {
222
259
  save({ heardAt: new Date().toISOString() });
223
- options.log(`Claude Code hears ${options.name}'s events`);
260
+ options.log("Claude Code hears the channel's events");
224
261
  }
225
262
  }
226
- if (cursor !== undefined) save({ cursor });
263
+ if (Object.keys(moved).length > 0)
264
+ save({ cursors: { ...status.cursors, ...moved } });
227
265
  };
228
266
 
229
- const onLine = (raw: string) => {
230
- let line: { name?: string; data?: unknown; cursor?: string; gap?: boolean };
231
- try {
232
- line = JSON.parse(raw);
233
- } catch {
234
- return;
235
- }
236
- if (typeof line.name !== "string") return;
237
- if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });
238
- if (!check) {
239
- check = setInterval(confirm, options.checkMs ?? CHECK_MS);
240
- unref(check);
241
- }
242
- const cursor =
243
- typeof line.cursor === "string" && line.cursor ? line.cursor : undefined;
244
- if (cursor) lastCursor = cursor;
245
- const id = `${nonce}.${++delivery}`;
246
- unconfirmed.push({ delivery: id, cursor });
247
- options.send({
248
- jsonrpc: "2.0",
249
- method: CHANNEL,
250
- params: channelMessage({
251
- name: line.name,
252
- data: line.data ?? null,
253
- ...(line.gap && { gap: true }),
254
- delivery: id,
255
- }),
256
- });
257
- };
258
-
259
- const follow = async () => {
267
+ const follow = async ({
268
+ subscription,
269
+ key,
270
+ }: (typeof subscriptions)[number]) => {
271
+ const label = subscriptionLabel(subscription);
272
+ const server = servers[subscription.server]!;
273
+ // where a reconnect of this process resumes: past every event sent, heard or not
274
+ let lastCursor: string | undefined = cursors[key];
275
+ const onLine = (raw: string) => {
276
+ let line: {
277
+ name?: string;
278
+ data?: unknown;
279
+ cursor?: string;
280
+ gap?: boolean;
281
+ };
282
+ try {
283
+ line = JSON.parse(raw);
284
+ } catch {
285
+ return;
286
+ }
287
+ if (typeof line.name !== "string") return;
288
+ if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });
289
+ if (!check) {
290
+ check = setInterval(confirm, options.checkMs ?? CHECK_MS);
291
+ unref(check);
292
+ }
293
+ const cursor =
294
+ typeof line.cursor === "string" && line.cursor
295
+ ? line.cursor
296
+ : undefined;
297
+ if (cursor) lastCursor = cursor;
298
+ const id = `${nonce}.${++delivery}`;
299
+ unconfirmed.push({ delivery: id, key, cursor });
300
+ options.send({
301
+ jsonrpc: "2.0",
302
+ method: CHANNEL,
303
+ params: channelMessage({
304
+ server: subscription.server,
305
+ name: line.name,
306
+ data: line.data ?? null,
307
+ ...(line.gap && { gap: true }),
308
+ delivery: id,
309
+ }),
310
+ });
311
+ };
260
312
  let backoff = 5000;
261
313
  while (!controller.signal.aborted) {
262
314
  const startedAt = Date.now();
@@ -264,38 +316,35 @@ export const channelServer = (options: Channel.Options): Channel.Server => {
264
316
  try {
265
317
  const cursor = lastCursor;
266
318
  code = await runCli(
267
- {
268
- name: "harnessd",
269
- configDir: join(options.paths.home, "auth"),
270
- servers: {
271
- [options.name]: {
272
- url: options.channel.url,
273
- headers: headersOf(options.channel, env),
274
- ...(options.fetch && { fetch: options.fetch }),
275
- },
276
- },
277
- },
319
+ serverCli(
320
+ options.paths,
321
+ subscription.server,
322
+ server,
323
+ env,
324
+ options.fetch,
325
+ ),
278
326
  {
279
327
  argv: [
280
328
  "stream",
329
+ subscription.event,
281
330
  ...(cursor ? ["--from", cursor] : []),
282
- ...streamFlags(options.channel.arguments),
331
+ ...streamFlags(subscription.arguments),
283
332
  ],
284
333
  stdout: onLine,
285
- stderr: (line) => options.log(`${options.name}: ${line}`),
334
+ stderr: (line) => options.log(`${label}: ${line}`),
286
335
  signal: controller.signal,
287
336
  },
288
337
  );
289
338
  } catch (error) {
290
339
  code = 1;
291
340
  options.log(
292
- `${options.name}: ${error instanceof Error ? error.message : String(error)}`,
341
+ `${label}: ${error instanceof Error ? error.message : String(error)}`,
293
342
  );
294
343
  }
295
344
  if (controller.signal.aborted) return;
296
345
  if (Date.now() - startedAt > 10 * 60_000) backoff = 5000;
297
346
  options.log(
298
- `${options.name}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,
347
+ `${label}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,
299
348
  );
300
349
  await new Promise<void>((resolve) => {
301
350
  const timer = setTimeout(resolve, backoff);
@@ -309,50 +358,11 @@ export const channelServer = (options: Channel.Options): Channel.Server => {
309
358
  }
310
359
  };
311
360
 
312
- let toolkit: Promise<McpToolkit> | undefined;
313
- let announced = false;
314
- const connect = () =>
315
- (toolkit ??= fromMcpServer({
316
- url: options.channel.url,
317
- headers: () => headersOf(options.channel, env),
318
- ...(options.fetch && { fetch: options.fetch }),
319
- name: options.name,
320
- }).catch((error: unknown) => {
321
- toolkit = undefined;
322
- throw error;
323
- }));
324
- const withTimeout = <T>(promise: Promise<T>, ms: number) =>
325
- Promise.race([
326
- promise,
327
- new Promise<undefined>((resolve) => unref(setTimeout(resolve, ms))),
328
- ]).catch(() => undefined);
329
- // The server was down when Claude Code asked for the tools: list them once it's back.
330
- const retryTools = async () => {
331
- let wait = 5000;
332
- while (!controller.signal.aborted) {
333
- await new Promise((resolve) => unref(setTimeout(resolve, wait)));
334
- try {
335
- await connect();
336
- if (!announced) {
337
- announced = true;
338
- options.send({
339
- jsonrpc: "2.0",
340
- method: "notifications/tools/list_changed",
341
- });
342
- }
343
- return;
344
- } catch {
345
- wait = Math.min(wait * 2, 5 * 60_000);
346
- }
347
- }
348
- };
349
-
350
- const instructions = (upstream: string | undefined) =>
351
- [
352
- `Events from ${options.name} arrive here for the whole session, one per message: <channel source="${source}" event="…" …>the event</channel>. Act on each.`,
353
- `To answer or act on ${options.name}, use this server's tools: they are ${options.name}'s own.`,
354
- ...(upstream ? [`${options.name} says: ${upstream}`] : []),
355
- ].join(" ");
361
+ const names = Object.keys(servers);
362
+ const instructions = [
363
+ `Events arrive here for the whole session, one per message: <channel source="${source}" server="…" event="…" …>the event</channel>. Act on each.`,
364
+ `To answer or act, run the server's command in the shell: ${names.map((name) => `\`${name}\``).join(", ")}. \`<command> --help\` lists its tools.`,
365
+ ].join(" ");
356
366
 
357
367
  const handle = async (
358
368
  request: Channel.Request,
@@ -363,51 +373,21 @@ export const channelServer = (options: Channel.Options): Channel.Server => {
363
373
  result: value,
364
374
  });
365
375
  switch (request.method) {
366
- case "initialize": {
367
- const kit = await withTimeout(connect(), CONNECT_WAIT_MS);
376
+ case "initialize":
368
377
  return result({
369
378
  protocolVersion: protocolFor(request.params?.protocolVersion),
370
- capabilities: {
371
- experimental: { "claude/channel": {} },
372
- tools: { listChanged: true },
373
- },
374
- serverInfo: { name: `harnessd-${options.name}`, version: "1.0.0" },
375
- instructions: instructions(kit?.description),
379
+ capabilities: { experimental: { "claude/channel": {} } },
380
+ serverInfo: { name: "harnessd", version: "1.0.0" },
381
+ instructions,
376
382
  });
377
- }
378
383
  case "notifications/initialized":
379
384
  unref(
380
385
  setTimeout(() => {
381
- if (!controller.signal.aborted) following ??= follow();
386
+ if (!controller.signal.aborted)
387
+ following ??= Promise.all(subscriptions.map(follow));
382
388
  }, options.startMs ?? START_MS),
383
389
  );
384
390
  return undefined;
385
- case "tools/list":
386
- case "tools/call": {
387
- let kit: McpToolkit;
388
- try {
389
- kit = await connect();
390
- } catch (error) {
391
- options.log(
392
- `${options.name}: couldn't reach its tools: ${error instanceof Error ? error.message : String(error)}`,
393
- );
394
- if (request.method === "tools/list") {
395
- void retryTools();
396
- return result({ tools: [] });
397
- }
398
- return result({
399
- content: [
400
- {
401
- type: "text",
402
- text: `${options.name} can't be reached right now.`,
403
- },
404
- ],
405
- isError: true,
406
- });
407
- }
408
- announced = true;
409
- return (await handleMcpMessage(kit, request)) ?? undefined;
410
- }
411
391
  case "ping":
412
392
  return result({});
413
393
  default:
@@ -429,12 +409,11 @@ export const channelServer = (options: Channel.Options): Channel.Server => {
429
409
  controller.abort();
430
410
  clearInterval(check);
431
411
  await following;
432
- await (await toolkit?.catch(() => undefined))?.close();
433
412
  },
434
413
  };
435
414
  };
436
415
 
437
- /** Serves one channel on stdin and stdout until Claude Code closes stdin. */
416
+ /** Serves the channel on stdin and stdout until Claude Code closes stdin. */
438
417
  export const serveChannel = async (options: Omit<Channel.Options, "send">) => {
439
418
  const write = (message: unknown) =>
440
419
  void process.stdout.write(`${JSON.stringify(message)}\n`);
package/src/claude.ts CHANGED
@@ -20,6 +20,9 @@ import type { Watchdog } from "./watchdog";
20
20
  /** How Claude Code names a `--plugin-dir` plugin. */
21
21
  export const PLUGIN = "harnessd@inline";
22
22
 
23
+ /** The channel's MCP server in harnessd's plugin, and so each event's `source`: `plugin:harnessd:channel`. */
24
+ export const CHANNEL_SERVER = "channel";
25
+
23
26
  const claudeDir = (env: NodeJS.ProcessEnv) =>
24
27
  env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
25
28
 
@@ -87,9 +90,10 @@ export const which = (name: string, path = process.env.PATH ?? "") => {
87
90
  const shellQuote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`;
88
91
 
89
92
  /**
90
- * harnessd's plugin, written before each start: one MCP server per channel of the config, each
91
- * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
92
- * /clear or a /resume is the conversation the next start resumes.
93
+ * harnessd's plugin, written before each start: the channel's MCP server (`harnessd channel`) when the config
94
+ * subscribes to events, a command per server in its `bin` (`harnessd tools <server>`), a SessionStart hook that
95
+ * tells harnessd which conversation Claude Code is in, so a /clear or a /resume is the conversation the next start
96
+ * resumes, and a Notification hook that tells harnessd when Claude Code waits for input with nothing running.
93
97
  */
94
98
  export const writePlugin = (
95
99
  paths: Harnessd.Paths,
@@ -98,35 +102,50 @@ export const writePlugin = (
98
102
  ) => {
99
103
  rmSync(paths.plugin, { recursive: true, force: true });
100
104
  mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
101
- const names = Object.keys(config.channels);
102
- const sessionStart = [
103
- ...Object.entries(paths.env).map(
104
- ([name, value]) => `${name}=${shellQuote(value)}`,
105
- ),
106
- shellQuote(process.execPath),
107
- shellQuote(bin),
108
- "session-start",
109
- ].join(" ");
105
+ mkdirSync(paths.bin, { recursive: true });
106
+ const exports = Object.entries(paths.env).map(
107
+ ([name, value]) => `${name}=${shellQuote(value)}`,
108
+ );
109
+ const harnessd = [shellQuote(process.execPath), shellQuote(bin)];
110
+ for (const name of Object.keys(config.servers))
111
+ writeFileSync(
112
+ join(paths.bin, name),
113
+ [
114
+ "#!/bin/sh",
115
+ ...exports.map((line) => `export ${line}`),
116
+ `exec ${[...harnessd, "tools", name].join(" ")} "$@"`,
117
+ "",
118
+ ].join("\n"),
119
+ { mode: 0o755 },
120
+ );
121
+ const hook = (command: string) =>
122
+ [...exports, ...harnessd, command].join(" ");
110
123
  const manifest = {
111
124
  name: "harnessd",
112
125
  version: "1.0.0",
113
126
  description:
114
- "harnessd's channels, each one's events and tools, and its SessionStart hook",
115
- ...(names.length > 0 && {
116
- mcpServers: Object.fromEntries(
117
- names.map((name) => [
118
- name,
119
- {
120
- command: process.execPath,
121
- args: [bin, "channel", name],
122
- env: paths.env,
123
- },
124
- ]),
125
- ),
126
- channels: names.map((name) => ({ server: name, displayName: name })),
127
+ "harnessd's channel of the servers' events, and its SessionStart and Notification hooks",
128
+ ...(config.channel.subscribe.length > 0 && {
129
+ mcpServers: {
130
+ [CHANNEL_SERVER]: {
131
+ command: process.execPath,
132
+ args: [bin, "channel"],
133
+ env: paths.env,
134
+ },
135
+ },
136
+ channels: [{ server: CHANNEL_SERVER, displayName: "harnessd" }],
127
137
  }),
128
138
  hooks: {
129
- SessionStart: [{ hooks: [{ type: "command", command: sessionStart }] }],
139
+ SessionStart: [
140
+ { hooks: [{ type: "command", command: hook("session-start") }] },
141
+ ],
142
+ // Claude Code's own idle: a minute after a turn, with no background agent or dialog
143
+ Notification: [
144
+ {
145
+ matcher: "idle_prompt",
146
+ hooks: [{ type: "command", command: hook("idle") }],
147
+ },
148
+ ],
130
149
  },
131
150
  };
132
151
  writeFileSync(
@@ -135,6 +154,14 @@ export const writePlugin = (
135
154
  );
136
155
  };
137
156
 
157
+ /** The version a claude command prints, such as `2.1.335`; none when it doesn't run or prints no version. */
158
+ export const claudeVersion = (file: string, env: NodeJS.ProcessEnv) =>
159
+ new Promise<string | undefined>((resolve) =>
160
+ execFile(file, ["--version"], { env, timeout: 30_000 }, (error, stdout) =>
161
+ resolve(error ? undefined : /^\s*(\d+\.\d+\.\d+\S*)/.exec(stdout)?.[1]),
162
+ ),
163
+ );
164
+
138
165
  /** Whether these claude arguments pick a permission mode themselves. */
139
166
  const picksPermissionMode = (args: readonly string[]) =>
140
167
  args.some(
@@ -156,7 +183,7 @@ export const skipsPermissions = (args: readonly string[]) =>
156
183
  /**
157
184
  * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
158
185
  * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
159
- * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
186
+ * its channel loads with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
160
187
  * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
161
188
  */
162
189
  export const claudeArgs = (o: {
@@ -170,7 +197,7 @@ export const claudeArgs = (o: {
170
197
  : ["--permission-mode", "auto"]),
171
198
  "--plugin-dir",
172
199
  o.plugin,
173
- ...(Object.keys(o.config.channels).length > 0
200
+ ...(o.config.channel.subscribe.length > 0
174
201
  ? ["--dangerously-load-development-channels", `plugin:${PLUGIN}`]
175
202
  : []),
176
203
  ...(o.start.resume