@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.
Files changed (70) hide show
  1. package/README.md +31 -18
  2. package/dist/accounts.d.ts +66 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +166 -0
  5. package/dist/accounts.js.map +1 -0
  6. package/dist/bin.js +4 -0
  7. package/dist/bin.js.map +1 -1
  8. package/dist/channel.d.ts +15 -10
  9. package/dist/channel.d.ts.map +1 -1
  10. package/dist/channel.js +113 -158
  11. package/dist/channel.js.map +1 -1
  12. package/dist/claude.d.ts +17 -13
  13. package/dist/claude.d.ts.map +1 -1
  14. package/dist/claude.js +69 -59
  15. package/dist/claude.js.map +1 -1
  16. package/dist/cli.d.ts +5 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +317 -131
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config.d.ts +46 -10
  21. package/dist/config.d.ts.map +1 -1
  22. package/dist/config.js +142 -51
  23. package/dist/config.js.map +1 -1
  24. package/dist/daemon.d.ts +29 -4
  25. package/dist/daemon.d.ts.map +1 -1
  26. package/dist/daemon.js +174 -51
  27. package/dist/daemon.js.map +1 -1
  28. package/dist/launchd.d.ts +12 -16
  29. package/dist/launchd.d.ts.map +1 -1
  30. package/dist/launchd.js +28 -25
  31. package/dist/launchd.js.map +1 -1
  32. package/dist/prompts.d.ts +53 -0
  33. package/dist/prompts.d.ts.map +1 -0
  34. package/dist/prompts.js +171 -0
  35. package/dist/prompts.js.map +1 -0
  36. package/dist/service.d.ts +37 -0
  37. package/dist/service.d.ts.map +1 -0
  38. package/dist/service.js +71 -0
  39. package/dist/service.js.map +1 -0
  40. package/dist/setup.d.ts +37 -0
  41. package/dist/setup.d.ts.map +1 -0
  42. package/dist/setup.js +121 -0
  43. package/dist/setup.js.map +1 -0
  44. package/dist/system.d.ts +6 -0
  45. package/dist/system.d.ts.map +1 -0
  46. package/dist/system.js +16 -0
  47. package/dist/system.js.map +1 -0
  48. package/dist/systemd.d.ts +14 -0
  49. package/dist/systemd.d.ts.map +1 -0
  50. package/dist/systemd.js +62 -0
  51. package/dist/systemd.js.map +1 -0
  52. package/dist/watchdog.d.ts +14 -4
  53. package/dist/watchdog.d.ts.map +1 -1
  54. package/dist/watchdog.js +30 -24
  55. package/dist/watchdog.js.map +1 -1
  56. package/package.json +8 -12
  57. package/src/accounts.ts +242 -0
  58. package/src/bin.ts +6 -0
  59. package/src/channel.ts +151 -172
  60. package/src/claude.ts +90 -88
  61. package/src/cli.ts +494 -183
  62. package/src/config.ts +239 -63
  63. package/src/daemon.ts +215 -65
  64. package/src/launchd.ts +40 -35
  65. package/src/prompts.ts +255 -0
  66. package/src/service.ts +145 -0
  67. package/src/setup.ts +188 -0
  68. package/src/system.ts +11 -0
  69. package/src/systemd.ts +78 -0
  70. package/src/watchdog.ts +41 -33
package/src/config.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { join, resolve } from "node:path";
4
+ import { isAbsolute, join, resolve } from "node:path";
5
5
 
6
6
  export namespace Harnessd {
7
- /** `config.json` in harnessd's home, read at every start of Claude Code. */
7
+ /** `config.json`, read at every start of Claude Code. */
8
8
  export type Config = {
9
+ /** The day the file was written, `YYYY-MM-DD`: harnessd behaves as it did on that day. */
10
+ readonly compatibilityDate: string;
9
11
  /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */
10
12
  readonly folder: string;
11
13
  /** More arguments for `claude`. */
@@ -14,62 +16,140 @@ export namespace Harnessd {
14
16
  readonly env: Readonly<Record<string, string>>;
15
17
  /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */
16
18
  readonly prestart?: string;
17
- /** MCP servers whose events reach the agent, by name. */
18
- readonly channels: Readonly<Record<string, Channel>>;
19
+ /** MCP servers by name: each one's tools are a command of that name for the agent. */
20
+ readonly servers: Readonly<Record<string, Server>>;
21
+ /** The one channel: the server events that reach the agent. */
22
+ readonly channel: Channel;
23
+ /** Claude accounts by name, in the order harnessd tries them: when one hits its usage limit or its sign-in fails, Claude Code goes on with the next. */
24
+ readonly accounts: Readonly<Record<string, Account>>;
25
+ };
26
+
27
+ /** One Claude account: the environment that signs Claude Code in to it, such as a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. None: this Mac's own sign-in. */
28
+ export type Account = {
29
+ readonly env: Readonly<Record<string, string>>;
19
30
  };
20
31
 
21
32
  /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */
22
- export type Channel = {
33
+ export type Server = {
23
34
  readonly url: string;
24
35
  readonly headers: Readonly<Record<string, string>>;
25
- /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */
36
+ };
37
+
38
+ export type Channel = {
39
+ /** The events that come in, each with its own arguments; nothing else does. */
40
+ readonly subscribe: readonly Subscription[];
41
+ };
42
+
43
+ /** One event type of one server, such as the board to follow for `task.handed`. */
44
+ export type Subscription = {
45
+ readonly server: string;
46
+ readonly event: string;
26
47
  readonly arguments: Readonly<Record<string, string | number | boolean>>;
27
48
  };
28
49
 
29
50
  /** Where one harnessd keeps its files. */
30
51
  export type Paths = {
52
+ /** The folder harnessd writes to: its state, log and where the channel's events resume. */
31
53
  readonly home: string;
32
54
  readonly config: string;
33
55
  readonly state: string;
34
56
  readonly log: string;
57
+ /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */
58
+ readonly serviceLog: string;
35
59
  readonly socket: string;
36
60
  readonly plugin: string;
37
- readonly channels: string;
61
+ /** The servers' commands, first on Claude Code's PATH. */
62
+ readonly bin: string;
63
+ readonly channel: string;
38
64
  readonly label: string;
65
+ /** The environment that gives another process these same paths. */
66
+ readonly env: Readonly<Record<string, string>>;
39
67
  };
40
68
  }
41
69
 
42
- const DEFAULT_HOME = join(homedir(), ".harnessd");
43
70
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
44
71
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
45
- // toolport's CLI keeps these words for itself
46
- const RESERVED = new Set(["stream", "login", "help"]);
72
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
47
73
  // macOS caps a socket path at 104 bytes
48
74
  const SOCKET_MAX = 103;
49
75
 
76
+ const XDG = ["XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"] as const;
77
+
78
+ const tooLong = (socket: string) => Buffer.byteLength(socket) > SOCKET_MAX;
79
+
80
+ // The XDG base directories: config.json in $XDG_CONFIG_HOME/harnessd (~/.config), everything harnessd writes in
81
+ // $XDG_STATE_HOME/harnessd (~/.local/state). HARNESSD_HOME puts both in one folder. There is no --config flag:
82
+ // the service, the channel's process and the servers' commands must find the same file, and these variables already reach them.
50
83
  export const pathsOf = (
51
84
  env: NodeJS.ProcessEnv = process.env,
52
85
  ): Harnessd.Paths => {
53
- const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);
54
- const socket = join(home, "harnessd.sock");
55
- if (Buffer.byteLength(socket) > SOCKET_MAX)
56
- throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);
86
+ // the XDG spec ignores a relative path
87
+ const xdg = Object.fromEntries(
88
+ XDG.flatMap((key) =>
89
+ env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : [],
90
+ ),
91
+ ) as Partial<Record<(typeof XDG)[number], string>>;
92
+ const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : undefined;
93
+ const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), ".config");
94
+ const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
95
+ const home = one ?? join(stateHome, "harnessd");
96
+ const id = createHash("sha256").update(home).digest("hex").slice(0, 8);
97
+ let socket = join(home, "harnessd.sock");
98
+ if (!one && tooLong(socket))
99
+ socket = xdg.XDG_RUNTIME_DIR
100
+ ? join(xdg.XDG_RUNTIME_DIR, "harnessd", `${id}.sock`)
101
+ : join("/tmp", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);
102
+ if (tooLong(socket))
103
+ throw new Error(
104
+ `${one ? "HARNESSD_HOME" : "XDG_RUNTIME_DIR"} is too long for a socket (${socket})`,
105
+ );
57
106
  return {
58
107
  home,
59
- config: join(home, "config.json"),
108
+ config: join(one ?? join(configHome, "harnessd"), "config.json"),
60
109
  state: join(home, "state.json"),
61
110
  log: join(home, "harnessd.log"),
111
+ serviceLog: join(home, "service.log"),
62
112
  socket,
63
113
  plugin: join(home, "plugin"),
64
- channels: join(home, "channels"),
114
+ bin: join(home, "plugin", "bin"),
115
+ channel: join(home, "channel.json"),
65
116
  label:
66
- home === DEFAULT_HOME
117
+ !one && stateHome === join(homedir(), ".local", "state")
67
118
  ? "dev.harnessd"
68
- : `dev.harnessd.${createHash("sha256").update(home).digest("hex").slice(0, 8)}`,
119
+ : `dev.harnessd.${id}`,
120
+ // every variable these paths came from, so nothing a child inherits moves them; "" reads as not set
121
+ env: one
122
+ ? { HARNESSD_HOME: one }
123
+ : {
124
+ HARNESSD_HOME: "",
125
+ XDG_CONFIG_HOME: configHome,
126
+ XDG_STATE_HOME: stateHome,
127
+ ...(!socket.startsWith(home) && {
128
+ XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? "",
129
+ }),
130
+ },
69
131
  };
70
132
  };
71
133
 
72
- export const DEFAULT_CONFIG = { folder: "~/agent", channels: {} };
134
+ /** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
135
+ export const ownFolder = (dir: string) => {
136
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
137
+ chmodSync(dir, 0o700);
138
+ };
139
+
140
+ /** The local date, as `compatibilityDate` takes it. */
141
+ export const today = (now = new Date()) =>
142
+ [now.getFullYear(), now.getMonth() + 1, now.getDate()]
143
+ .map((part) => String(part).padStart(2, "0"))
144
+ .join("-");
145
+
146
+ /** The file `harnessd service install` writes when there is none. */
147
+ export const defaultConfig = () => ({
148
+ compatibilityDate: today(),
149
+ folder: "~/agent",
150
+ servers: {},
151
+ channel: { subscribe: [] },
152
+ });
73
153
 
74
154
  const fail = (message: string): never => {
75
155
  throw new Error(`config.json: ${message}`);
@@ -105,35 +185,32 @@ const expandHome = (path: string) =>
105
185
  ? join(homedir(), path.slice(2))
106
186
  : path;
107
187
 
108
- export const parseConfig = (raw: unknown): Harnessd.Config => {
109
- if (!isRecord(raw)) fail("must be a JSON object");
110
- const value = raw as Record<string, unknown>;
111
- only(value, ["folder", "args", "env", "prestart", "channels"], "it");
112
- if (typeof value.folder !== "string" || value.folder === "")
113
- fail("folder must be a path");
114
- const args = value.args ?? [];
115
- if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))
116
- fail("args must be a list of strings");
188
+ const scalars = (value: unknown, what: string) => {
189
+ if (value === undefined) return {};
117
190
  if (
118
- value.prestart !== undefined &&
119
- (typeof value.prestart !== "string" || value.prestart === "")
191
+ !isRecord(value) ||
192
+ Object.values(value).some(
193
+ (v) => !["string", "number", "boolean"].includes(typeof v),
194
+ )
120
195
  )
121
- fail("prestart must be a shell command");
122
- const channels: Record<string, Harnessd.Channel> = {};
123
- const listed = value.channels ?? {};
124
- if (!isRecord(listed))
125
- fail("channels must map names to { url, headers, arguments }");
126
- for (const [name, channel] of Object.entries(
127
- listed as Record<string, unknown>,
196
+ fail(`${what} must map names to strings, numbers or booleans`);
197
+ return value as Record<string, string | number | boolean>;
198
+ };
199
+
200
+ const parseServers = (value: unknown) => {
201
+ const servers: Record<string, Harnessd.Server> = {};
202
+ if (value === undefined) return servers;
203
+ if (!isRecord(value)) fail("servers must map names to { url, headers }");
204
+ for (const [name, server] of Object.entries(
205
+ value as Record<string, unknown>,
128
206
  )) {
129
- if (!NAME.test(name) || RESERVED.has(name))
207
+ if (!NAME.test(name))
130
208
  fail(
131
- `channel "${name}" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(", ")}`,
209
+ `server "${name}" needs a name of lowercase letters, digits and dashes`,
132
210
  );
133
- if (!isRecord(channel))
134
- fail(`channels.${name} must be { url, headers, arguments }`);
135
- const entry = channel as Record<string, unknown>;
136
- only(entry, ["url", "headers", "arguments"], `channels.${name}`);
211
+ if (!isRecord(server)) fail(`servers.${name} must be { url, headers }`);
212
+ const entry = server as Record<string, unknown>;
213
+ only(entry, ["url", "headers"], `servers.${name}`);
137
214
  let url: URL | undefined;
138
215
  try {
139
216
  url = new URL(String(entry.url));
@@ -144,36 +221,135 @@ export const parseConfig = (raw: unknown): Harnessd.Config => {
144
221
  !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
145
222
  )
146
223
  fail(
147
- `channels.${name}.url must be an https URL (http only on this Mac: localhost, 127.0.0.1, [::1])`,
224
+ `servers.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`,
148
225
  );
149
- const args = entry.arguments ?? {};
150
- if (
151
- !isRecord(args) ||
152
- Object.values(args).some(
153
- (v) => !["string", "number", "boolean"].includes(typeof v),
154
- )
155
- )
156
- fail(
157
- `channels.${name}.arguments must map names to strings, numbers or booleans`,
158
- );
159
- channels[name] = {
226
+ servers[name] = {
160
227
  url: url!.href,
161
- headers: strings(entry.headers, `channels.${name}.headers`),
162
- arguments: args as Record<string, string | number | boolean>,
228
+ headers: strings(entry.headers, `servers.${name}.headers`),
163
229
  };
164
230
  }
231
+ return servers;
232
+ };
233
+
234
+ const parseChannel = (
235
+ value: unknown,
236
+ servers: Readonly<Record<string, Harnessd.Server>>,
237
+ ): Harnessd.Channel => {
238
+ if (value === undefined) return { subscribe: [] };
239
+ if (!isRecord(value)) fail("channel must be { subscribe }");
240
+ const entry = value as Record<string, unknown>;
241
+ only(entry, ["subscribe"], "channel");
242
+ const listed = entry.subscribe ?? [];
243
+ if (!Array.isArray(listed))
244
+ fail("channel.subscribe must be a list of { server, event, arguments }");
245
+ const seen = new Set<string>();
246
+ const subscribe = (listed as unknown[]).map((item, i) => {
247
+ const what = `channel.subscribe[${i}]`;
248
+ if (!isRecord(item)) fail(`${what} must be { server, event, arguments }`);
249
+ const one = item as Record<string, unknown>;
250
+ only(one, ["server", "event", "arguments"], what);
251
+ if (typeof one.server !== "string" || !Object.hasOwn(servers, one.server))
252
+ fail(`${what}.server must name one of servers`);
253
+ if (typeof one.event !== "string" || one.event === "")
254
+ fail(`${what}.event must name one of the server's events`);
255
+ const subscription: Harnessd.Subscription = {
256
+ server: one.server as string,
257
+ event: one.event as string,
258
+ arguments: scalars(one.arguments, `${what}.arguments`),
259
+ };
260
+ const key = subscriptionKey(subscription);
261
+ if (seen.has(key)) fail(`${what} repeats an earlier subscription`);
262
+ seen.add(key);
263
+ return subscription;
264
+ });
265
+ return { subscribe };
266
+ };
267
+
268
+ /** What tells one subscription from another: its server, event and arguments. */
269
+ export const subscriptionKey = (subscription: Harnessd.Subscription) =>
270
+ JSON.stringify([
271
+ subscription.server,
272
+ subscription.event,
273
+ Object.entries(subscription.arguments).sort(([a], [b]) =>
274
+ a < b ? -1 : a > b ? 1 : 0,
275
+ ),
276
+ ]);
277
+
278
+ export const parseConfig = (raw: unknown): Harnessd.Config => {
279
+ if (!isRecord(raw)) fail("must be a JSON object");
280
+ const value = raw as Record<string, unknown>;
281
+ only(
282
+ value,
283
+ [
284
+ "compatibilityDate",
285
+ "folder",
286
+ "args",
287
+ "env",
288
+ "prestart",
289
+ "servers",
290
+ "channel",
291
+ "accounts",
292
+ ],
293
+ "it",
294
+ );
295
+ const date = value.compatibilityDate;
296
+ if (
297
+ typeof date !== "string" ||
298
+ !DATE.test(date) ||
299
+ // Date rolls a day past the month's end over into the next month
300
+ new Date(Date.parse(date) || 0).toISOString().slice(0, 10) !== date
301
+ )
302
+ fail(
303
+ "compatibilityDate must be a date, YYYY-MM-DD: the day the file was written",
304
+ );
305
+ if (typeof value.folder !== "string" || value.folder === "")
306
+ fail("folder must be a path");
307
+ const args = value.args ?? [];
308
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))
309
+ fail("args must be a list of strings");
310
+ if (
311
+ value.prestart !== undefined &&
312
+ (typeof value.prestart !== "string" || value.prestart === "")
313
+ )
314
+ fail("prestart must be a shell command");
315
+ const servers = parseServers(value.servers);
316
+ const channel = parseChannel(value.channel, servers);
317
+ const accounts: Record<string, Harnessd.Account> = {};
318
+ const named = value.accounts === undefined ? {} : value.accounts;
319
+ if (!isRecord(named)) fail("accounts must map names to { env }");
320
+ for (const [name, account] of Object.entries(
321
+ named as Record<string, unknown>,
322
+ )) {
323
+ if (!NAME.test(name))
324
+ fail(
325
+ `account "${name}" needs a name of lowercase letters, digits and dashes`,
326
+ );
327
+ if (!isRecord(account)) fail(`accounts.${name} must be { env }`);
328
+ const entry = account as Record<string, unknown>;
329
+ only(entry, ["env"], `accounts.${name}`);
330
+ const env = strings(entry.env, `accounts.${name}.env`);
331
+ // every account shares one conversation, so where Claude Code keeps it comes from the top-level env
332
+ if ("CLAUDE_CONFIG_DIR" in env)
333
+ fail(
334
+ `accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`,
335
+ );
336
+ accounts[name] = { env };
337
+ }
165
338
  return {
339
+ compatibilityDate: date as string,
166
340
  folder: resolve(expandHome(value.folder as string)),
167
341
  args: args as string[],
168
342
  env: strings(value.env, "env"),
169
343
  ...(value.prestart !== undefined && { prestart: value.prestart as string }),
170
- channels,
344
+ servers,
345
+ channel,
346
+ accounts,
171
347
  };
172
348
  };
173
349
 
174
350
  export const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {
175
351
  if (!existsSync(paths.config))
176
- throw new Error(`No ${paths.config}: run harnessd install`);
352
+ throw new Error(`No ${paths.config}: run harnessd service install`);
177
353
  let raw: unknown;
178
354
  try {
179
355
  raw = JSON.parse(readFileSync(paths.config, "utf8"));
@@ -185,13 +361,13 @@ export const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {
185
361
  return parseConfig(raw);
186
362
  };
187
363
 
188
- /** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
364
+ /** A server's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
189
365
  export const headersOf = (
190
- channel: Harnessd.Channel,
366
+ server: Harnessd.Server,
191
367
  env: NodeJS.ProcessEnv,
192
368
  ): Record<string, string> =>
193
369
  Object.fromEntries(
194
- Object.entries(channel.headers).map(([key, value]) => [
370
+ Object.entries(server.headers).map(([key, value]) => [
195
371
  key,
196
372
  value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name: string) => {
197
373
  const found = env[name];