@harness-sdk/harnessd 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +14 -13
  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.js +1 -1
  9. package/dist/claude.d.ts +12 -13
  10. package/dist/claude.d.ts.map +1 -1
  11. package/dist/claude.js +45 -59
  12. package/dist/claude.js.map +1 -1
  13. package/dist/cli.d.ts +5 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +269 -114
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +14 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +53 -13
  20. package/dist/config.js.map +1 -1
  21. package/dist/daemon.d.ts +17 -4
  22. package/dist/daemon.d.ts.map +1 -1
  23. package/dist/daemon.js +112 -51
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/launchd.d.ts +12 -16
  26. package/dist/launchd.d.ts.map +1 -1
  27. package/dist/launchd.js +28 -25
  28. package/dist/launchd.js.map +1 -1
  29. package/dist/prompts.d.ts +53 -0
  30. package/dist/prompts.d.ts.map +1 -0
  31. package/dist/prompts.js +171 -0
  32. package/dist/prompts.js.map +1 -0
  33. package/dist/service.d.ts +37 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +71 -0
  36. package/dist/service.js.map +1 -0
  37. package/dist/setup.d.ts +37 -0
  38. package/dist/setup.d.ts.map +1 -0
  39. package/dist/setup.js +121 -0
  40. package/dist/setup.js.map +1 -0
  41. package/dist/system.d.ts +6 -0
  42. package/dist/system.d.ts.map +1 -0
  43. package/dist/system.js +16 -0
  44. package/dist/system.js.map +1 -0
  45. package/dist/systemd.d.ts +14 -0
  46. package/dist/systemd.d.ts.map +1 -0
  47. package/dist/systemd.js +62 -0
  48. package/dist/systemd.js.map +1 -0
  49. package/dist/watchdog.d.ts +14 -4
  50. package/dist/watchdog.d.ts.map +1 -1
  51. package/dist/watchdog.js +30 -24
  52. package/dist/watchdog.js.map +1 -1
  53. package/package.json +5 -3
  54. package/src/accounts.ts +242 -0
  55. package/src/bin.ts +6 -0
  56. package/src/claude.ts +65 -90
  57. package/src/cli.ts +413 -152
  58. package/src/config.ts +92 -14
  59. package/src/daemon.ts +131 -64
  60. package/src/launchd.ts +40 -35
  61. package/src/prompts.ts +255 -0
  62. package/src/service.ts +145 -0
  63. package/src/setup.ts +188 -0
  64. package/src/system.ts +11 -0
  65. package/src/systemd.ts +78 -0
  66. package/src/watchdog.ts +41 -33
package/src/config.ts CHANGED
@@ -1,10 +1,10 @@
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
9
  /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */
10
10
  readonly folder: string;
@@ -16,6 +16,13 @@ export namespace Harnessd {
16
16
  readonly prestart?: string;
17
17
  /** MCP servers whose events reach the agent, by name. */
18
18
  readonly channels: Readonly<Record<string, Channel>>;
19
+ /** 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. */
20
+ readonly accounts: Readonly<Record<string, Account>>;
21
+ };
22
+
23
+ /** 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. */
24
+ export type Account = {
25
+ readonly env: Readonly<Record<string, string>>;
19
26
  };
20
27
 
21
28
  /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */
@@ -28,18 +35,22 @@ export namespace Harnessd {
28
35
 
29
36
  /** Where one harnessd keeps its files. */
30
37
  export type Paths = {
38
+ /** The folder harnessd writes to: its state, log and each channel's place. */
31
39
  readonly home: string;
32
40
  readonly config: string;
33
41
  readonly state: string;
34
42
  readonly log: string;
43
+ /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */
44
+ readonly serviceLog: string;
35
45
  readonly socket: string;
36
46
  readonly plugin: string;
37
47
  readonly channels: string;
38
48
  readonly label: string;
49
+ /** The environment that gives another process these same paths. */
50
+ readonly env: Readonly<Record<string, string>>;
39
51
  };
40
52
  }
41
53
 
42
- const DEFAULT_HOME = join(homedir(), ".harnessd");
43
54
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
44
55
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
45
56
  // toolport's CLI keeps these words for itself
@@ -47,28 +58,69 @@ const RESERVED = new Set(["stream", "login", "help"]);
47
58
  // macOS caps a socket path at 104 bytes
48
59
  const SOCKET_MAX = 103;
49
60
 
61
+ const XDG = ["XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"] as const;
62
+
63
+ const tooLong = (socket: string) => Buffer.byteLength(socket) > SOCKET_MAX;
64
+
65
+ // The XDG base directories: config.json in $XDG_CONFIG_HOME/harnessd (~/.config), everything harnessd writes in
66
+ // $XDG_STATE_HOME/harnessd (~/.local/state). HARNESSD_HOME puts both in one folder. There is no --config flag:
67
+ // the service and each channel's process must find the same file, and these variables already reach them.
50
68
  export const pathsOf = (
51
69
  env: NodeJS.ProcessEnv = process.env,
52
70
  ): 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})`);
71
+ // the XDG spec ignores a relative path
72
+ const xdg = Object.fromEntries(
73
+ XDG.flatMap((key) =>
74
+ env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : [],
75
+ ),
76
+ ) as Partial<Record<(typeof XDG)[number], string>>;
77
+ const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : undefined;
78
+ const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), ".config");
79
+ const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
80
+ const home = one ?? join(stateHome, "harnessd");
81
+ const id = createHash("sha256").update(home).digest("hex").slice(0, 8);
82
+ let socket = join(home, "harnessd.sock");
83
+ if (!one && tooLong(socket))
84
+ socket = xdg.XDG_RUNTIME_DIR
85
+ ? join(xdg.XDG_RUNTIME_DIR, "harnessd", `${id}.sock`)
86
+ : join("/tmp", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);
87
+ if (tooLong(socket))
88
+ throw new Error(
89
+ `${one ? "HARNESSD_HOME" : "XDG_RUNTIME_DIR"} is too long for a socket (${socket})`,
90
+ );
57
91
  return {
58
92
  home,
59
- config: join(home, "config.json"),
93
+ config: join(one ?? join(configHome, "harnessd"), "config.json"),
60
94
  state: join(home, "state.json"),
61
95
  log: join(home, "harnessd.log"),
96
+ serviceLog: join(home, "service.log"),
62
97
  socket,
63
98
  plugin: join(home, "plugin"),
64
99
  channels: join(home, "channels"),
65
100
  label:
66
- home === DEFAULT_HOME
101
+ !one && stateHome === join(homedir(), ".local", "state")
67
102
  ? "dev.harnessd"
68
- : `dev.harnessd.${createHash("sha256").update(home).digest("hex").slice(0, 8)}`,
103
+ : `dev.harnessd.${id}`,
104
+ // every variable these paths came from, so nothing a child inherits moves them; "" reads as not set
105
+ env: one
106
+ ? { HARNESSD_HOME: one }
107
+ : {
108
+ HARNESSD_HOME: "",
109
+ XDG_CONFIG_HOME: configHome,
110
+ XDG_STATE_HOME: stateHome,
111
+ ...(!socket.startsWith(home) && {
112
+ XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? "",
113
+ }),
114
+ },
69
115
  };
70
116
  };
71
117
 
118
+ /** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
119
+ export const ownFolder = (dir: string) => {
120
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
121
+ chmodSync(dir, 0o700);
122
+ };
123
+
72
124
  export const DEFAULT_CONFIG = { folder: "~/agent", channels: {} };
73
125
 
74
126
  const fail = (message: string): never => {
@@ -108,7 +160,11 @@ const expandHome = (path: string) =>
108
160
  export const parseConfig = (raw: unknown): Harnessd.Config => {
109
161
  if (!isRecord(raw)) fail("must be a JSON object");
110
162
  const value = raw as Record<string, unknown>;
111
- only(value, ["folder", "args", "env", "prestart", "channels"], "it");
163
+ only(
164
+ value,
165
+ ["folder", "args", "env", "prestart", "channels", "accounts"],
166
+ "it",
167
+ );
112
168
  if (typeof value.folder !== "string" || value.folder === "")
113
169
  fail("folder must be a path");
114
170
  const args = value.args ?? [];
@@ -144,7 +200,7 @@ export const parseConfig = (raw: unknown): Harnessd.Config => {
144
200
  !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
145
201
  )
146
202
  fail(
147
- `channels.${name}.url must be an https URL (http only on this Mac: localhost, 127.0.0.1, [::1])`,
203
+ `channels.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`,
148
204
  );
149
205
  const args = entry.arguments ?? {};
150
206
  if (
@@ -162,18 +218,40 @@ export const parseConfig = (raw: unknown): Harnessd.Config => {
162
218
  arguments: args as Record<string, string | number | boolean>,
163
219
  };
164
220
  }
221
+ const accounts: Record<string, Harnessd.Account> = {};
222
+ const named = value.accounts === undefined ? {} : value.accounts;
223
+ if (!isRecord(named)) fail("accounts must map names to { env }");
224
+ for (const [name, account] of Object.entries(
225
+ named as Record<string, unknown>,
226
+ )) {
227
+ if (!NAME.test(name))
228
+ fail(
229
+ `account "${name}" needs a name of lowercase letters, digits and dashes`,
230
+ );
231
+ if (!isRecord(account)) fail(`accounts.${name} must be { env }`);
232
+ const entry = account as Record<string, unknown>;
233
+ only(entry, ["env"], `accounts.${name}`);
234
+ const env = strings(entry.env, `accounts.${name}.env`);
235
+ // every account shares one conversation, so where Claude Code keeps it comes from the top-level env
236
+ if ("CLAUDE_CONFIG_DIR" in env)
237
+ fail(
238
+ `accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`,
239
+ );
240
+ accounts[name] = { env };
241
+ }
165
242
  return {
166
243
  folder: resolve(expandHome(value.folder as string)),
167
244
  args: args as string[],
168
245
  env: strings(value.env, "env"),
169
246
  ...(value.prestart !== undefined && { prestart: value.prestart as string }),
170
247
  channels,
248
+ accounts,
171
249
  };
172
250
  };
173
251
 
174
252
  export const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {
175
253
  if (!existsSync(paths.config))
176
- throw new Error(`No ${paths.config}: run harnessd install`);
254
+ throw new Error(`No ${paths.config}: run harnessd service install`);
177
255
  let raw: unknown;
178
256
  try {
179
257
  raw = JSON.parse(readFileSync(paths.config, "utf8"));
package/src/daemon.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import {
2
- chmodSync,
3
2
  existsSync,
4
3
  mkdirSync,
5
4
  readFileSync,
@@ -7,30 +6,32 @@ import {
7
6
  statSync,
8
7
  writeFileSync,
9
8
  } from "node:fs";
10
- import { createRequire } from "node:module";
11
9
  import { createConnection, createServer, type Socket } from "node:net";
12
- import { dirname, join } from "node:path";
10
+ import { dirname } from "node:path";
13
11
  import { createInterface } from "node:readline";
14
- import type { IPty } from "node-pty";
12
+ import type { IPty } from "@lydell/node-pty";
13
+ import { accountRun, rotation } from "./accounts";
15
14
  import {
16
- channelBlockers,
17
15
  claudeArgs,
16
+ skipsPermissions,
18
17
  findTranscript,
19
18
  prestart,
20
19
  trustFolder,
21
20
  which,
22
21
  writePlugin,
23
22
  } from "./claude";
24
- import { readConfig, type Harnessd } from "./config";
23
+ import { ownFolder, readConfig, type Harnessd } from "./config";
25
24
  import { logTo } from "./log";
25
+ import { promptWatcher } from "./prompts";
26
26
  import { IDLE_SIZE, scrollback } from "./terminal";
27
- import { watchdog, type Watchdog } from "./watchdog";
27
+ import { NOT_STARTED, watchdog, type Watchdog } from "./watchdog";
28
28
 
29
29
  export namespace Daemon {
30
30
  /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
31
31
  export type Request =
32
32
  | { readonly command: "status" | "stop" | "start" }
33
- | { readonly command: "new"; readonly message?: string }
33
+ /** From Claude Code's SessionStart hook: the conversation it is in now. */
34
+ | { readonly command: "session-start"; readonly sessionId: string }
34
35
  | {
35
36
  readonly command: "attach";
36
37
  readonly cols: number;
@@ -40,6 +41,16 @@ export namespace Daemon {
40
41
  export type Status = Watchdog.Status & {
41
42
  readonly daemonPid: number;
42
43
  readonly folder?: string;
44
+ /** The account Claude Code runs on, when the config names accounts. */
45
+ readonly account?: string;
46
+ /** The accounts passed over, and until when. */
47
+ readonly accountsStopped?: Readonly<
48
+ Record<string, { readonly why: string; readonly until: string }>
49
+ >;
50
+ /** The prompt Claude Code waits at until a person answers it. */
51
+ readonly waitingOn?: string;
52
+ /** Claude Code said managed settings keep channels out: it drops their events. */
53
+ readonly channelsRefused?: true;
43
54
  };
44
55
  }
45
56
 
@@ -49,24 +60,14 @@ const OWN_ENV =
49
60
 
50
61
  const VIEWER_BUFFER = 8 * 1024 * 1024;
51
62
 
63
+ const SESSION_ID =
64
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
65
+
52
66
  const clamp = (value: unknown, min: number, max: number, fallback: number) =>
53
67
  typeof value === "number" && Number.isFinite(value)
54
68
  ? Math.max(min, Math.min(max, Math.floor(value)))
55
69
  : fallback;
56
70
 
57
- // node-pty's prebuilt spawn-helper ships without its executable bit; its install script, which pnpm skips, sets it
58
- const loadPty = async () => {
59
- const helper = join(
60
- dirname(createRequire(import.meta.url).resolve("node-pty/package.json")),
61
- "prebuilds",
62
- `${process.platform}-${process.arch}`,
63
- "spawn-helper",
64
- );
65
- if (existsSync(helper) && (statSync(helper).mode & 0o111) === 0)
66
- chmodSync(helper, 0o755);
67
- return import("node-pty");
68
- };
69
-
70
71
  /** Sends one request to a running harnessd; undefined when none answers. */
71
72
  export const ask = (socket: string, request: Daemon.Request) =>
72
73
  new Promise<Record<string, unknown> | undefined>((resolve) => {
@@ -77,6 +78,8 @@ export const ask = (socket: string, request: Daemon.Request) =>
77
78
  connection.write(`${JSON.stringify(request)}\n`),
78
79
  );
79
80
  const lines = createInterface({ input: connection });
81
+ // readline passes the connection's error on: a socket file nobody listens on (harnessd was killed) is no answer
82
+ lines.once("error", () => resolve(undefined));
80
83
  lines.once("line", (line) => {
81
84
  connection.end();
82
85
  try {
@@ -88,9 +91,17 @@ export const ask = (socket: string, request: Daemon.Request) =>
88
91
  lines.once("close", () => resolve(undefined));
89
92
  });
90
93
 
91
- /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
94
+ /** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
92
95
  export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
93
- mkdirSync(paths.home, { recursive: true });
96
+ ownFolder(paths.home);
97
+ ownFolder(dirname(paths.config));
98
+ const socketDir = dirname(paths.socket);
99
+ if (socketDir !== paths.home) {
100
+ mkdirSync(socketDir, { recursive: true, mode: 0o700 });
101
+ // a socket outside harnessd's folder sits in a shared one, where another user may have made its folder first
102
+ if (statSync(socketDir).uid !== process.getuid!())
103
+ throw new Error(`${socketDir} belongs to another user`);
104
+ }
94
105
  const log = logTo(paths.log);
95
106
  if (await ask(paths.socket, { command: "status" }))
96
107
  throw new Error(`Another harnessd already runs in ${paths.home}`);
@@ -111,6 +122,12 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
111
122
  }
112
123
  };
113
124
 
125
+ const prompts = promptWatcher({
126
+ write: (keys) => pty?.write(keys),
127
+ log,
128
+ ...size,
129
+ });
130
+
114
131
  const state = {
115
132
  read: (): Watchdog.State => {
116
133
  try {
@@ -133,8 +150,19 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
133
150
  return process.env;
134
151
  }
135
152
  };
153
+ let accounts: Harnessd.Config["accounts"] = {};
154
+ let account: string | undefined;
155
+ const rota = rotation({
156
+ accounts: () =>
157
+ Object.fromEntries(
158
+ Object.entries(accounts).map(([name, { env }]) => [name, env]),
159
+ ),
160
+ });
136
161
  const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {
137
162
  const config = readConfig(paths);
163
+ accounts = config.accounts;
164
+ account = rota.pick(state.read().account);
165
+ if (account !== undefined) state.write({ ...state.read(), account });
138
166
  folder = config.folder;
139
167
  mkdirSync(config.folder, { recursive: true });
140
168
  const inherited = Object.fromEntries(
@@ -143,56 +171,80 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
143
171
  const base: Record<string, string> = {
144
172
  ...inherited,
145
173
  ...config.env,
146
- HARNESSD_HOME: paths.home,
174
+ ...(account !== undefined && {
175
+ ...config.accounts[account]!.env,
176
+ HARNESSD_ACCOUNT: account,
177
+ }),
178
+ ...paths.env,
147
179
  };
180
+ if (account !== undefined) log(`Claude Code runs on account ${account}`);
148
181
  const hook = config.prestart
149
182
  ? await prestart(config.prestart, config.folder, base, log)
150
183
  : { env: {}, args: [] };
151
184
  const env = { ...base, ...hook.env };
152
185
  claudeEnv = env;
153
- if (!trustFolder(config.folder, env))
154
- log(
155
- "Claude Code has no settings yet: harnessd attach, then sign in and trust the folder",
156
- );
157
- const plugin = writePlugin(paths, config, bin) ? paths.plugin : undefined;
158
- const blockers = plugin ? channelBlockers() : [];
159
- if (blockers.length > 0)
160
- log(
161
- `Claude Code won't let the channels in: ${blockers.join("; ")} (harnessd install lets them in)`,
162
- );
163
- const file = which("claude", env.PATH);
164
- const { spawn } = await loadPty();
165
- const p = spawn(
166
- file,
167
- claudeArgs({
186
+ trustFolder(config.folder, env);
187
+ writePlugin(paths, config, bin);
188
+ // from before the start, so a refusal Claude Code writes at once is read
189
+ const onAccount =
190
+ account !== undefined && Object.keys(config.accounts).length > 1
191
+ ? accountRun({
192
+ account,
193
+ rotation: rota,
194
+ sessionId: () => dog.status().sessionId ?? start.sessionId,
195
+ file: (id) => findTranscript(id, env),
196
+ restart: (reason, pid) => void dog.restart(reason, pid),
197
+ log,
198
+ })
199
+ : undefined;
200
+ let handover: string | undefined;
201
+ let p: IPty;
202
+ let args: string[];
203
+ try {
204
+ const file = which("claude", env.PATH);
205
+ const { spawn } = await import("@lydell/node-pty");
206
+ args = claudeArgs({
168
207
  start,
169
- plugin,
170
- allowed: blockers.length === 0,
208
+ plugin: paths.plugin,
171
209
  config,
172
210
  extra: hook.args,
173
- }),
174
- {
211
+ });
212
+ p = spawn(file, args, {
175
213
  name: "xterm-256color",
176
214
  cols: size.cols,
177
215
  rows: size.rows,
178
216
  cwd: config.folder,
179
217
  env,
180
- },
181
- );
218
+ });
219
+ } catch (error) {
220
+ onAccount?.exited();
221
+ throw error;
222
+ }
223
+ onAccount?.started(p.pid);
182
224
  pty = p;
225
+ prompts.reset({ skipsPermissions: skipsPermissions(args) });
183
226
  show(
184
227
  `\r\n\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\x1b[0m\r\n`,
185
228
  );
186
- p.onData(show);
229
+ p.onData((data) => {
230
+ show(data);
231
+ prompts.push(data);
232
+ });
187
233
  const exited = new Promise<number>((resolve) =>
188
234
  p.onExit(({ exitCode, signal }) => {
189
- if (pty === p) pty = undefined;
235
+ // the last lines too: an account that stopped right before the exit isn't started again
236
+ handover = onAccount?.exited();
237
+ if (pty === p) {
238
+ pty = undefined;
239
+ prompts.reset();
240
+ }
190
241
  resolve(signal ? 128 + signal : exitCode);
191
242
  }),
192
243
  );
193
244
  return {
194
245
  pid: p.pid,
195
246
  exited,
247
+ ended: () => handover,
196
248
  kill: (signal) => {
197
249
  try {
198
250
  p.kill(signal);
@@ -204,6 +256,7 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
204
256
  const resize = (cols: number, rows: number) => {
205
257
  if (cols === size.cols && rows === size.rows) return;
206
258
  size = { cols, rows };
259
+ prompts.resize(cols, rows);
207
260
  try {
208
261
  pty?.resize(cols, rows);
209
262
  } catch {}
@@ -216,15 +269,32 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
216
269
  log,
217
270
  });
218
271
 
219
- const status = (): Daemon.Status => ({
220
- ...dog.status(),
221
- daemonPid: process.pid,
222
- ...(folder && { folder }),
223
- });
272
+ const status = (): Daemon.Status => {
273
+ const waitingOn = prompts.waitingOn();
274
+ const stops = rota.marks();
275
+ return {
276
+ ...dog.status(),
277
+ daemonPid: process.pid,
278
+ ...(folder && { folder }),
279
+ ...(waitingOn && { waitingOn }),
280
+ ...(prompts.channelsRefused() && { channelsRefused: true as const }),
281
+ ...(account !== undefined && { account }),
282
+ ...(Object.keys(stops).length > 0 && {
283
+ accountsStopped: Object.fromEntries(
284
+ Object.entries(stops).map(([name, { why, until }]) => [
285
+ name,
286
+ { why, until: new Date(until).toISOString() },
287
+ ]),
288
+ ),
289
+ }),
290
+ };
291
+ };
224
292
 
225
293
  const serve = (connection: Socket) => {
226
294
  const reply = (value: unknown) =>
227
295
  connection.end(`${JSON.stringify(value)}\n`);
296
+ const done = (message: string) =>
297
+ reply({ ok: message !== NOT_STARTED, message });
228
298
  const lines = createInterface({ input: connection });
229
299
  let attached = false;
230
300
  connection.on("error", () => {});
@@ -252,18 +322,15 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
252
322
  return void reply({ ok: true, status: status() });
253
323
  if (request.command === "stop")
254
324
  return void reply({ ok: true, message: await dog.stop() });
255
- if (request.command === "start")
256
- return void reply({ ok: true, message: await dog.start() });
257
- if (request.command === "new") {
258
- if (
259
- request.message !== undefined &&
260
- typeof request.message !== "string"
261
- )
262
- return void reply({ ok: false, message: "message must be text." });
263
- return void reply({
264
- ok: true,
265
- message: await dog.fresh(request.message),
266
- });
325
+ if (request.command === "start") return void done(await dog.start());
326
+ if (request.command === "session-start") {
327
+ if (!SESSION_ID.test(String(request.sessionId)))
328
+ return void reply({
329
+ ok: false,
330
+ message: "sessionId must be a conversation id.",
331
+ });
332
+ dog.follow(request.sessionId);
333
+ return void reply({ ok: true });
267
334
  }
268
335
  if (request.command === "attach") {
269
336
  attached = true;
package/src/launchd.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { spawnSync } from "node:child_process";
2
1
  import {
3
2
  accessSync,
4
3
  constants,
@@ -9,14 +8,15 @@ import {
9
8
  writeFileSync,
10
9
  } from "node:fs";
11
10
  import { homedir } from "node:os";
12
- import { delimiter, join } from "node:path";
13
- import type { Harnessd } from "./config";
11
+ import { delimiter, dirname, join } from "node:path";
12
+ import type { Service } from "./service";
13
+ import { system } from "./system";
14
14
 
15
15
  const xml = (value: string) =>
16
16
  value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
17
17
 
18
18
  /**
19
- * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
19
+ * The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
20
20
  * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
21
21
  * harnessd unable to start. None that is this one: `process.execPath`.
22
22
  */
@@ -41,23 +41,26 @@ export const stableNode = (
41
41
  return execPath;
42
42
  };
43
43
 
44
- export const plistPath = (label: string) =>
45
- join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
44
+ /** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
45
+ export const plistFolder = (home: string) =>
46
+ ` <key>WorkingDirectory</key>\n <string>${xml(home)}</string>`;
46
47
 
47
- /** The LaunchAgent: `node <bin> run` at login and after any exit. */
48
- export const plistOf = (o: {
49
- label: string;
50
- node: string;
51
- bin: string;
52
- env: Readonly<Record<string, string>>;
53
- paths: Harnessd.Paths;
54
- }) => `<?xml version="1.0" encoding="UTF-8"?>
48
+ /** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
49
+ export const plistPath = (label: string, boot = false) =>
50
+ boot
51
+ ? `/Library/LaunchDaemons/${label}.plist`
52
+ : join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
53
+
54
+ /** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
55
+ export const plistOf = (
56
+ o: Service.Spec,
57
+ ) => `<?xml version="1.0" encoding="UTF-8"?>
55
58
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
56
59
  <plist version="1.0">
57
60
  <dict>
58
61
  <key>Label</key>
59
62
  <string>${xml(o.label)}</string>
60
- <key>ProgramArguments</key>
63
+ ${o.user === undefined ? "" : ` <key>UserName</key>\n <string>${xml(o.user)}</string>\n`} <key>ProgramArguments</key>
61
64
  <array>
62
65
  <string>${xml(o.node)}</string>
63
66
  <string>${xml(o.bin)}</string>
@@ -72,8 +75,7 @@ ${Object.entries(o.env)
72
75
  )
73
76
  .join("\n")}
74
77
  </dict>
75
- <key>WorkingDirectory</key>
76
- <string>${xml(o.paths.home)}</string>
78
+ ${plistFolder(o.paths.home)}
77
79
  <key>RunAtLoad</key>
78
80
  <true/>
79
81
  <key>KeepAlive</key>
@@ -83,43 +85,46 @@ ${Object.entries(o.env)
83
85
  <key>ProcessType</key>
84
86
  <string>Interactive</string>
85
87
  <key>StandardOutPath</key>
86
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
88
+ <string>${xml(o.paths.serviceLog)}</string>
87
89
  <key>StandardErrorPath</key>
88
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
90
+ <string>${xml(o.paths.serviceLog)}</string>
89
91
  </dict>
90
92
  </plist>
91
93
  `;
92
94
 
93
- const domain = () => `gui/${process.getuid!()}`;
95
+ const domain = (boot: boolean) =>
96
+ boot ? "system" : `gui/${process.getuid!()}`;
94
97
 
95
- const launchctl = (...args: string[]) =>
96
- spawnSync("launchctl", args, { encoding: "utf8" });
98
+ const launchctl = (...args: string[]) => system("launchctl", args);
97
99
 
98
- export const loaded = (label: string) =>
99
- launchctl("print", `${domain()}/${label}`).status === 0;
100
+ const loaded = (label: string, boot: boolean) =>
101
+ launchctl("print", `${domain(boot)}/${label}`).status === 0;
100
102
 
101
- /** Writes the LaunchAgent and (re)loads it, which starts harnessd. */
102
- export const load = (label: string, plist: string) => {
103
- mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
104
- if (loaded(label)) launchctl("bootout", `${domain()}/${label}`);
105
- writeFileSync(plistPath(label), plist);
106
- const result = launchctl("bootstrap", domain(), plistPath(label));
103
+ /** Writes the launchd entry and (re)loads it, which starts harnessd. */
104
+ export const load = async (label: string, plist: string, boot: boolean) => {
105
+ mkdirSync(dirname(plistPath(label, boot)), { recursive: true });
106
+ if (loaded(label, boot)) launchctl("bootout", `${domain(boot)}/${label}`);
107
+ // bootout returns while the old harnessd still stops Claude Code; a bootstrap before it is gone fails
108
+ for (let i = 0; loaded(label, boot) && i < 400; i++)
109
+ await new Promise((resolve) => setTimeout(resolve, 100));
110
+ writeFileSync(plistPath(label, boot), plist, { mode: 0o644 });
111
+ const result = launchctl("bootstrap", domain(boot), plistPath(label, boot));
107
112
  if (result.status !== 0)
108
113
  throw new Error(
109
114
  `launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`,
110
115
  );
111
116
  };
112
117
 
113
- /** Stops harnessd (it stops Claude Code first) and removes the LaunchAgent. */
114
- export const unload = (label: string) => {
115
- if (loaded(label)) {
116
- const result = launchctl("bootout", `${domain()}/${label}`);
118
+ /** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
119
+ export const unload = (label: string, boot: boolean) => {
120
+ if (loaded(label, boot)) {
121
+ const result = launchctl("bootout", `${domain(boot)}/${label}`);
117
122
  if (result.status !== 0)
118
123
  throw new Error(
119
124
  `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,
120
125
  );
121
126
  }
122
- const plist = plistPath(label);
127
+ const plist = plistPath(label, boot);
123
128
  const had = existsSync(plist);
124
129
  rmSync(plist, { force: true });
125
130
  return had;