@harness-sdk/harnessd 0.0.0 → 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.
- package/LICENSE +21 -0
- package/README.md +64 -2
- package/dist/accounts.d.ts +66 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +166 -0
- package/dist/accounts.js.map +1 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +19 -0
- package/dist/bin.js.map +1 -0
- package/dist/channel.d.ts +56 -0
- package/dist/channel.d.ts.map +1 -0
- package/dist/channel.js +356 -0
- package/dist/channel.js.map +1 -0
- package/dist/claude.d.ts +41 -0
- package/dist/claude.d.ts.map +1 -0
- package/dist/claude.js +152 -0
- package/dist/claude.js.map +1 -0
- package/dist/cli.d.ts +13 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +413 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +56 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +161 -0
- package/dist/config.js.map +1 -0
- package/dist/daemon.d.ts +37 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/daemon.js +300 -0
- package/dist/daemon.js.map +1 -0
- package/dist/launchd.d.ts +18 -0
- package/dist/launchd.d.ts.map +1 -0
- package/dist/launchd.js +91 -0
- package/dist/launchd.js.map +1 -0
- package/dist/log.d.ts +3 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +17 -0
- package/dist/log.js.map +1 -0
- package/dist/prompts.d.ts +53 -0
- package/dist/prompts.d.ts.map +1 -0
- package/dist/prompts.js +171 -0
- package/dist/prompts.js.map +1 -0
- package/dist/service.d.ts +37 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +71 -0
- package/dist/service.js.map +1 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +121 -0
- package/dist/setup.js.map +1 -0
- package/dist/system.d.ts +6 -0
- package/dist/system.d.ts.map +1 -0
- package/dist/system.js +16 -0
- package/dist/system.js.map +1 -0
- package/dist/systemd.d.ts +14 -0
- package/dist/systemd.d.ts.map +1 -0
- package/dist/systemd.js +62 -0
- package/dist/systemd.js.map +1 -0
- package/dist/terminal.d.ts +11 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +36 -0
- package/dist/terminal.js.map +1 -0
- package/dist/watchdog.d.ts +83 -0
- package/dist/watchdog.d.ts.map +1 -0
- package/dist/watchdog.js +236 -0
- package/dist/watchdog.js.map +1 -0
- package/package.json +55 -6
- package/src/accounts.ts +242 -0
- package/src/bin.ts +24 -0
- package/src/channel.ts +461 -0
- package/src/claude.ts +249 -0
- package/src/cli.ts +633 -0
- package/src/config.ts +281 -0
- package/src/daemon.ts +379 -0
- package/src/launchd.ts +131 -0
- package/src/log.ts +17 -0
- package/src/prompts.ts +255 -0
- package/src/service.ts +145 -0
- package/src/setup.ts +188 -0
- package/src/system.ts +11 -0
- package/src/systemd.ts +78 -0
- package/src/terminal.ts +33 -0
- package/src/watchdog.ts +318 -0
package/dist/config.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
// src/config.ts
|
|
6
|
+
const LOOPBACK = /* @__PURE__ */ new Set([
|
|
7
|
+
"localhost",
|
|
8
|
+
"127.0.0.1",
|
|
9
|
+
"[::1]"
|
|
10
|
+
]);
|
|
11
|
+
const NAME = /^[a-z][a-z0-9-]{0,31}$/;
|
|
12
|
+
const RESERVED = /* @__PURE__ */ new Set([
|
|
13
|
+
"stream",
|
|
14
|
+
"login",
|
|
15
|
+
"help"
|
|
16
|
+
]);
|
|
17
|
+
const SOCKET_MAX = 103;
|
|
18
|
+
const XDG = [
|
|
19
|
+
"XDG_CONFIG_HOME",
|
|
20
|
+
"XDG_STATE_HOME",
|
|
21
|
+
"XDG_RUNTIME_DIR"
|
|
22
|
+
];
|
|
23
|
+
const tooLong = (socket) => Buffer.byteLength(socket) > SOCKET_MAX;
|
|
24
|
+
const pathsOf = (env = process.env) => {
|
|
25
|
+
const xdg = Object.fromEntries(XDG.flatMap((key) => env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : []));
|
|
26
|
+
const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : void 0;
|
|
27
|
+
const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
28
|
+
const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
|
|
29
|
+
const home = one ?? join(stateHome, "harnessd");
|
|
30
|
+
const id = createHash("sha256").update(home).digest("hex").slice(0, 8);
|
|
31
|
+
let socket = join(home, "harnessd.sock");
|
|
32
|
+
if (!one && tooLong(socket)) socket = xdg.XDG_RUNTIME_DIR ? join(xdg.XDG_RUNTIME_DIR, "harnessd", `${id}.sock`) : join("/tmp", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);
|
|
33
|
+
if (tooLong(socket)) throw new Error(`${one ? "HARNESSD_HOME" : "XDG_RUNTIME_DIR"} is too long for a socket (${socket})`);
|
|
34
|
+
return {
|
|
35
|
+
home,
|
|
36
|
+
config: join(one ?? join(configHome, "harnessd"), "config.json"),
|
|
37
|
+
state: join(home, "state.json"),
|
|
38
|
+
log: join(home, "harnessd.log"),
|
|
39
|
+
serviceLog: join(home, "service.log"),
|
|
40
|
+
socket,
|
|
41
|
+
plugin: join(home, "plugin"),
|
|
42
|
+
channels: join(home, "channels"),
|
|
43
|
+
label: !one && stateHome === join(homedir(), ".local", "state") ? "dev.harnessd" : `dev.harnessd.${id}`,
|
|
44
|
+
env: one ? { HARNESSD_HOME: one } : {
|
|
45
|
+
HARNESSD_HOME: "",
|
|
46
|
+
XDG_CONFIG_HOME: configHome,
|
|
47
|
+
XDG_STATE_HOME: stateHome,
|
|
48
|
+
...!socket.startsWith(home) && { XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? "" }
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
/** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
|
|
53
|
+
const ownFolder = (dir) => {
|
|
54
|
+
mkdirSync(dir, {
|
|
55
|
+
recursive: true,
|
|
56
|
+
mode: 448
|
|
57
|
+
});
|
|
58
|
+
chmodSync(dir, 448);
|
|
59
|
+
};
|
|
60
|
+
const DEFAULT_CONFIG = {
|
|
61
|
+
folder: "~/agent",
|
|
62
|
+
channels: {}
|
|
63
|
+
};
|
|
64
|
+
const fail = (message) => {
|
|
65
|
+
throw new Error(`config.json: ${message}`);
|
|
66
|
+
};
|
|
67
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
68
|
+
const strings = (value, what) => {
|
|
69
|
+
if (value === void 0) return {};
|
|
70
|
+
if (!isRecord(value) || Object.values(value).some((v) => typeof v !== "string")) fail(`${what} must map names to strings`);
|
|
71
|
+
return value;
|
|
72
|
+
};
|
|
73
|
+
const only = (value, keys, what) => {
|
|
74
|
+
const unknown = Object.keys(value).find((key) => !keys.includes(key));
|
|
75
|
+
if (unknown !== void 0) fail(`${what} has no "${unknown}"; it takes ${keys.join(", ")}`);
|
|
76
|
+
};
|
|
77
|
+
const expandHome = (path) => path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
|
|
78
|
+
const parseConfig = (raw) => {
|
|
79
|
+
if (!isRecord(raw)) fail("must be a JSON object");
|
|
80
|
+
const value = raw;
|
|
81
|
+
only(value, [
|
|
82
|
+
"folder",
|
|
83
|
+
"args",
|
|
84
|
+
"env",
|
|
85
|
+
"prestart",
|
|
86
|
+
"channels",
|
|
87
|
+
"accounts"
|
|
88
|
+
], "it");
|
|
89
|
+
if (typeof value.folder !== "string" || value.folder === "") fail("folder must be a path");
|
|
90
|
+
const args = value.args ?? [];
|
|
91
|
+
if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) fail("args must be a list of strings");
|
|
92
|
+
if (value.prestart !== void 0 && (typeof value.prestart !== "string" || value.prestart === "")) fail("prestart must be a shell command");
|
|
93
|
+
const channels = {};
|
|
94
|
+
const listed = value.channels ?? {};
|
|
95
|
+
if (!isRecord(listed)) fail("channels must map names to { url, headers, arguments }");
|
|
96
|
+
for (const [name, channel] of Object.entries(listed)) {
|
|
97
|
+
if (!NAME.test(name) || RESERVED.has(name)) fail(`channel "${name}" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(", ")}`);
|
|
98
|
+
if (!isRecord(channel)) fail(`channels.${name} must be { url, headers, arguments }`);
|
|
99
|
+
const entry = channel;
|
|
100
|
+
only(entry, [
|
|
101
|
+
"url",
|
|
102
|
+
"headers",
|
|
103
|
+
"arguments"
|
|
104
|
+
], `channels.${name}`);
|
|
105
|
+
let url;
|
|
106
|
+
try {
|
|
107
|
+
url = new URL(String(entry.url));
|
|
108
|
+
} catch {}
|
|
109
|
+
if (!url || url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname))) fail(`channels.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`);
|
|
110
|
+
const args = entry.arguments ?? {};
|
|
111
|
+
if (!isRecord(args) || Object.values(args).some((v) => ![
|
|
112
|
+
"string",
|
|
113
|
+
"number",
|
|
114
|
+
"boolean"
|
|
115
|
+
].includes(typeof v))) fail(`channels.${name}.arguments must map names to strings, numbers or booleans`);
|
|
116
|
+
channels[name] = {
|
|
117
|
+
url: url.href,
|
|
118
|
+
headers: strings(entry.headers, `channels.${name}.headers`),
|
|
119
|
+
arguments: args
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const accounts = {};
|
|
123
|
+
const named = value.accounts === void 0 ? {} : value.accounts;
|
|
124
|
+
if (!isRecord(named)) fail("accounts must map names to { env }");
|
|
125
|
+
for (const [name, account] of Object.entries(named)) {
|
|
126
|
+
if (!NAME.test(name)) fail(`account "${name}" needs a name of lowercase letters, digits and dashes`);
|
|
127
|
+
if (!isRecord(account)) fail(`accounts.${name} must be { env }`);
|
|
128
|
+
const entry = account;
|
|
129
|
+
only(entry, ["env"], `accounts.${name}`);
|
|
130
|
+
const env = strings(entry.env, `accounts.${name}.env`);
|
|
131
|
+
if ("CLAUDE_CONFIG_DIR" in env) fail(`accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`);
|
|
132
|
+
accounts[name] = { env };
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
folder: resolve(expandHome(value.folder)),
|
|
136
|
+
args,
|
|
137
|
+
env: strings(value.env, "env"),
|
|
138
|
+
...value.prestart !== void 0 && { prestart: value.prestart },
|
|
139
|
+
channels,
|
|
140
|
+
accounts
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
const readConfig = (paths) => {
|
|
144
|
+
if (!existsSync(paths.config)) throw new Error(`No ${paths.config}: run harnessd service install`);
|
|
145
|
+
let raw;
|
|
146
|
+
try {
|
|
147
|
+
raw = JSON.parse(readFileSync(paths.config, "utf8"));
|
|
148
|
+
} catch (error) {
|
|
149
|
+
throw new Error(`config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
150
|
+
}
|
|
151
|
+
return parseConfig(raw);
|
|
152
|
+
};
|
|
153
|
+
/** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
|
|
154
|
+
const headersOf = (channel, env) => Object.fromEntries(Object.entries(channel.headers).map(([key, value]) => [key, value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
|
|
155
|
+
const found = env[name];
|
|
156
|
+
if (found === void 0) throw new Error(`header ${key} needs $${name}, which isn't set`);
|
|
157
|
+
return found;
|
|
158
|
+
})]));
|
|
159
|
+
export { DEFAULT_CONFIG, headersOf, ownFolder, parseConfig, pathsOf, readConfig };
|
|
160
|
+
|
|
161
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\nexport namespace Harnessd {\n /** `config.json`, read at every start of Claude Code. */\n export type Config = {\n /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */\n readonly folder: string;\n /** More arguments for `claude`. */\n readonly args: readonly string[];\n /** More environment for `claude`. */\n readonly env: Readonly<Record<string, string>>;\n /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */\n readonly prestart?: string;\n /** MCP servers whose events reach the agent, by name. */\n readonly channels: Readonly<Record<string, Channel>>;\n /** 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. */\n readonly accounts: Readonly<Record<string, Account>>;\n };\n\n /** 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. */\n export type Account = {\n readonly env: Readonly<Record<string, string>>;\n };\n\n /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */\n export type Channel = {\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */\n readonly arguments: Readonly<Record<string, string | number | boolean>>;\n };\n\n /** Where one harnessd keeps its files. */\n export type Paths = {\n /** The folder harnessd writes to: its state, log and each channel's place. */\n readonly home: string;\n readonly config: string;\n readonly state: string;\n readonly log: string;\n /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */\n readonly serviceLog: string;\n readonly socket: string;\n readonly plugin: string;\n readonly channels: string;\n readonly label: string;\n /** The environment that gives another process these same paths. */\n readonly env: Readonly<Record<string, string>>;\n };\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\nconst NAME = /^[a-z][a-z0-9-]{0,31}$/;\n// toolport's CLI keeps these words for itself\nconst RESERVED = new Set([\"stream\", \"login\", \"help\"]);\n// macOS caps a socket path at 104 bytes\nconst SOCKET_MAX = 103;\n\nconst XDG = [\"XDG_CONFIG_HOME\", \"XDG_STATE_HOME\", \"XDG_RUNTIME_DIR\"] as const;\n\nconst tooLong = (socket: string) => Buffer.byteLength(socket) > SOCKET_MAX;\n\n// The XDG base directories: config.json in $XDG_CONFIG_HOME/harnessd (~/.config), everything harnessd writes in\n// $XDG_STATE_HOME/harnessd (~/.local/state). HARNESSD_HOME puts both in one folder. There is no --config flag:\n// the service and each channel's process must find the same file, and these variables already reach them.\nexport const pathsOf = (\n env: NodeJS.ProcessEnv = process.env,\n): Harnessd.Paths => {\n // the XDG spec ignores a relative path\n const xdg = Object.fromEntries(\n XDG.flatMap((key) =>\n env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : [],\n ),\n ) as Partial<Record<(typeof XDG)[number], string>>;\n const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : undefined;\n const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\");\n const home = one ?? join(stateHome, \"harnessd\");\n const id = createHash(\"sha256\").update(home).digest(\"hex\").slice(0, 8);\n let socket = join(home, \"harnessd.sock\");\n if (!one && tooLong(socket))\n socket = xdg.XDG_RUNTIME_DIR\n ? join(xdg.XDG_RUNTIME_DIR, \"harnessd\", `${id}.sock`)\n : join(\"/tmp\", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);\n if (tooLong(socket))\n throw new Error(\n `${one ? \"HARNESSD_HOME\" : \"XDG_RUNTIME_DIR\"} is too long for a socket (${socket})`,\n );\n return {\n home,\n config: join(one ?? join(configHome, \"harnessd\"), \"config.json\"),\n state: join(home, \"state.json\"),\n log: join(home, \"harnessd.log\"),\n serviceLog: join(home, \"service.log\"),\n socket,\n plugin: join(home, \"plugin\"),\n channels: join(home, \"channels\"),\n label:\n !one && stateHome === join(homedir(), \".local\", \"state\")\n ? \"dev.harnessd\"\n : `dev.harnessd.${id}`,\n // every variable these paths came from, so nothing a child inherits moves them; \"\" reads as not set\n env: one\n ? { HARNESSD_HOME: one }\n : {\n HARNESSD_HOME: \"\",\n XDG_CONFIG_HOME: configHome,\n XDG_STATE_HOME: stateHome,\n ...(!socket.startsWith(home) && {\n XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? \"\",\n }),\n },\n };\n};\n\n/** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */\nexport const ownFolder = (dir: string) => {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n};\n\nexport const DEFAULT_CONFIG = { folder: \"~/agent\", channels: {} };\n\nconst fail = (message: string): never => {\n throw new Error(`config.json: ${message}`);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst strings = (value: unknown, what: string): Record<string, string> => {\n if (value === undefined) return {};\n if (\n !isRecord(value) ||\n Object.values(value).some((v) => typeof v !== \"string\")\n )\n fail(`${what} must map names to strings`);\n return value as Record<string, string>;\n};\n\nconst only = (\n value: Record<string, unknown>,\n keys: readonly string[],\n what: string,\n) => {\n const unknown = Object.keys(value).find((key) => !keys.includes(key));\n if (unknown !== undefined)\n fail(`${what} has no \"${unknown}\"; it takes ${keys.join(\", \")}`);\n};\n\nconst expandHome = (path: string) =>\n path === \"~\"\n ? homedir()\n : path.startsWith(\"~/\")\n ? join(homedir(), path.slice(2))\n : path;\n\nexport const parseConfig = (raw: unknown): Harnessd.Config => {\n if (!isRecord(raw)) fail(\"must be a JSON object\");\n const value = raw as Record<string, unknown>;\n only(\n value,\n [\"folder\", \"args\", \"env\", \"prestart\", \"channels\", \"accounts\"],\n \"it\",\n );\n if (typeof value.folder !== \"string\" || value.folder === \"\")\n fail(\"folder must be a path\");\n const args = value.args ?? [];\n if (!Array.isArray(args) || args.some((arg) => typeof arg !== \"string\"))\n fail(\"args must be a list of strings\");\n if (\n value.prestart !== undefined &&\n (typeof value.prestart !== \"string\" || value.prestart === \"\")\n )\n fail(\"prestart must be a shell command\");\n const channels: Record<string, Harnessd.Channel> = {};\n const listed = value.channels ?? {};\n if (!isRecord(listed))\n fail(\"channels must map names to { url, headers, arguments }\");\n for (const [name, channel] of Object.entries(\n listed as Record<string, unknown>,\n )) {\n if (!NAME.test(name) || RESERVED.has(name))\n fail(\n `channel \"${name}\" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(\", \")}`,\n );\n if (!isRecord(channel))\n fail(`channels.${name} must be { url, headers, arguments }`);\n const entry = channel as Record<string, unknown>;\n only(entry, [\"url\", \"headers\", \"arguments\"], `channels.${name}`);\n let url: URL | undefined;\n try {\n url = new URL(String(entry.url));\n } catch {}\n if (\n !url ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && LOOPBACK.has(url.hostname)))\n )\n fail(\n `channels.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`,\n );\n const args = entry.arguments ?? {};\n if (\n !isRecord(args) ||\n Object.values(args).some(\n (v) => ![\"string\", \"number\", \"boolean\"].includes(typeof v),\n )\n )\n fail(\n `channels.${name}.arguments must map names to strings, numbers or booleans`,\n );\n channels[name] = {\n url: url!.href,\n headers: strings(entry.headers, `channels.${name}.headers`),\n arguments: args as Record<string, string | number | boolean>,\n };\n }\n const accounts: Record<string, Harnessd.Account> = {};\n const named = value.accounts === undefined ? {} : value.accounts;\n if (!isRecord(named)) fail(\"accounts must map names to { env }\");\n for (const [name, account] of Object.entries(\n named as Record<string, unknown>,\n )) {\n if (!NAME.test(name))\n fail(\n `account \"${name}\" needs a name of lowercase letters, digits and dashes`,\n );\n if (!isRecord(account)) fail(`accounts.${name} must be { env }`);\n const entry = account as Record<string, unknown>;\n only(entry, [\"env\"], `accounts.${name}`);\n const env = strings(entry.env, `accounts.${name}.env`);\n // every account shares one conversation, so where Claude Code keeps it comes from the top-level env\n if (\"CLAUDE_CONFIG_DIR\" in env)\n fail(\n `accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`,\n );\n accounts[name] = { env };\n }\n return {\n folder: resolve(expandHome(value.folder as string)),\n args: args as string[],\n env: strings(value.env, \"env\"),\n ...(value.prestart !== undefined && { prestart: value.prestart as string }),\n channels,\n accounts,\n };\n};\n\nexport const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {\n if (!existsSync(paths.config))\n throw new Error(`No ${paths.config}: run harnessd service install`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(paths.config, \"utf8\"));\n } catch (error) {\n throw new Error(\n `config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return parseConfig(raw);\n};\n\n/** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */\nexport const headersOf = (\n channel: Harnessd.Channel,\n env: NodeJS.ProcessEnv,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(channel.headers).map(([key, value]) => [\n key,\n value.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => {\n const found = env[name];\n if (found === undefined)\n throw new Error(`header ${key} needs $${name}, which isn't set`);\n return found;\n }),\n ]),\n );\n"],"mappings":";;;;;AAqDA,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAC5D,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAU;CAAS;AAAM,CAAC;AAEpD,MAAM,aAAa;AAEnB,MAAM,MAAM;CAAC;CAAmB;CAAkB;AAAiB;AAEnE,MAAM,WAAW,WAAmB,OAAO,WAAW,MAAM,IAAI;AAKhE,MAAa,WACX,MAAyB,QAAQ,QACd;CAEnB,MAAM,MAAM,OAAO,YACjB,IAAI,SAAS,QACX,IA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,37 @@
|
|
|
1
|
+
import { type Harnessd } from "./config.js";
|
|
2
|
+
import { type Watchdog } from "./watchdog.js";
|
|
3
|
+
export declare namespace Daemon {
|
|
4
|
+
/** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
|
|
5
|
+
type Request = {
|
|
6
|
+
readonly command: "status" | "stop" | "start";
|
|
7
|
+
}
|
|
8
|
+
/** From Claude Code's SessionStart hook: the conversation it is in now. */
|
|
9
|
+
| {
|
|
10
|
+
readonly command: "session-start";
|
|
11
|
+
readonly sessionId: string;
|
|
12
|
+
} | {
|
|
13
|
+
readonly command: "attach";
|
|
14
|
+
readonly cols: number;
|
|
15
|
+
readonly rows: number;
|
|
16
|
+
};
|
|
17
|
+
type Status = Watchdog.Status & {
|
|
18
|
+
readonly daemonPid: number;
|
|
19
|
+
readonly folder?: string;
|
|
20
|
+
/** The account Claude Code runs on, when the config names accounts. */
|
|
21
|
+
readonly account?: string;
|
|
22
|
+
/** The accounts passed over, and until when. */
|
|
23
|
+
readonly accountsStopped?: Readonly<Record<string, {
|
|
24
|
+
readonly why: string;
|
|
25
|
+
readonly until: string;
|
|
26
|
+
}>>;
|
|
27
|
+
/** The prompt Claude Code waits at until a person answers it. */
|
|
28
|
+
readonly waitingOn?: string;
|
|
29
|
+
/** Claude Code said managed settings keep channels out: it drops their events. */
|
|
30
|
+
readonly channelsRefused?: true;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Sends one request to a running harnessd; undefined when none answers. */
|
|
34
|
+
export declare const ask: (socket: string, request: Daemon.Request) => Promise<Record<string, unknown> | undefined>;
|
|
35
|
+
/** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
|
|
36
|
+
export declare const runDaemon: (paths: Harnessd.Paths, bin: string) => Promise<void>;
|
|
37
|
+
//# sourceMappingURL=daemon.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon.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AAM,SAAS,GAAU,OAAO,QAAQ,CAAC,KAAK,EAAE,KAAK,MAAM,kBA4RjE,CAAC"}
|
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { accountRun, rotation } from "./accounts.js";
|
|
2
|
+
import { claudeArgs, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin } from "./claude.js";
|
|
3
|
+
import { ownFolder, readConfig } from "./config.js";
|
|
4
|
+
import { logTo } from "./log.js";
|
|
5
|
+
import { promptWatcher } from "./prompts.js";
|
|
6
|
+
import { IDLE_SIZE, scrollback } from "./terminal.js";
|
|
7
|
+
import { NOT_STARTED, watchdog } from "./watchdog.js";
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { createConnection, createServer } from "node:net";
|
|
10
|
+
import { dirname } from "node:path";
|
|
11
|
+
import { createInterface } from "node:readline";
|
|
12
|
+
// src/daemon.ts
|
|
13
|
+
const OWN_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;
|
|
14
|
+
const VIEWER_BUFFER = 8388608;
|
|
15
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
const clamp = (value, min, max, fallback) => typeof value === "number" && Number.isFinite(value) ? Math.max(min, Math.min(max, Math.floor(value))) : fallback;
|
|
17
|
+
/** Sends one request to a running harnessd; undefined when none answers. */
|
|
18
|
+
const ask = (socket, request) => new Promise((resolve) => {
|
|
19
|
+
if (!existsSync(socket)) return resolve(void 0);
|
|
20
|
+
const connection = createConnection(socket);
|
|
21
|
+
connection.once("error", () => resolve(void 0));
|
|
22
|
+
connection.once("connect", () => connection.write(`${JSON.stringify(request)}\n`));
|
|
23
|
+
const lines = createInterface({ input: connection });
|
|
24
|
+
lines.once("error", () => resolve(void 0));
|
|
25
|
+
lines.once("line", (line) => {
|
|
26
|
+
connection.end();
|
|
27
|
+
try {
|
|
28
|
+
resolve(JSON.parse(line));
|
|
29
|
+
} catch {
|
|
30
|
+
resolve(void 0);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
lines.once("close", () => resolve(void 0));
|
|
34
|
+
});
|
|
35
|
+
/** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
|
|
36
|
+
const runDaemon = async (paths, bin) => {
|
|
37
|
+
ownFolder(paths.home);
|
|
38
|
+
ownFolder(dirname(paths.config));
|
|
39
|
+
const socketDir = dirname(paths.socket);
|
|
40
|
+
if (socketDir !== paths.home) {
|
|
41
|
+
mkdirSync(socketDir, {
|
|
42
|
+
recursive: true,
|
|
43
|
+
mode: 448
|
|
44
|
+
});
|
|
45
|
+
if (statSync(socketDir).uid !== process.getuid()) throw new Error(`${socketDir} belongs to another user`);
|
|
46
|
+
}
|
|
47
|
+
const log = logTo(paths.log);
|
|
48
|
+
if (await ask(paths.socket, { command: "status" })) throw new Error(`Another harnessd already runs in ${paths.home}`);
|
|
49
|
+
rmSync(paths.socket, { force: true });
|
|
50
|
+
const term = scrollback();
|
|
51
|
+
const viewers = /* @__PURE__ */ new Set();
|
|
52
|
+
let size = IDLE_SIZE;
|
|
53
|
+
let pty;
|
|
54
|
+
let folder;
|
|
55
|
+
const show = (data) => {
|
|
56
|
+
term.push(data);
|
|
57
|
+
const line = `${JSON.stringify({ output: data })}\n`;
|
|
58
|
+
for (const viewer of viewers) if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();
|
|
59
|
+
else viewer.write(line);
|
|
60
|
+
};
|
|
61
|
+
const prompts = promptWatcher({
|
|
62
|
+
write: (keys) => pty?.write(keys),
|
|
63
|
+
log,
|
|
64
|
+
...size
|
|
65
|
+
});
|
|
66
|
+
const state = {
|
|
67
|
+
read: () => {
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(readFileSync(paths.state, "utf8"));
|
|
70
|
+
} catch {
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
write: (value) => writeFileSync(paths.state, `${JSON.stringify(value)}\n`)
|
|
75
|
+
};
|
|
76
|
+
let claudeEnv;
|
|
77
|
+
const transcriptEnv = () => {
|
|
78
|
+
if (claudeEnv) return claudeEnv;
|
|
79
|
+
try {
|
|
80
|
+
return {
|
|
81
|
+
...process.env,
|
|
82
|
+
...readConfig(paths).env
|
|
83
|
+
};
|
|
84
|
+
} catch {
|
|
85
|
+
return process.env;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
let accounts = {};
|
|
89
|
+
let account;
|
|
90
|
+
const rota = rotation({ accounts: () => Object.fromEntries(Object.entries(accounts).map(([name, { env }]) => [name, env])) });
|
|
91
|
+
const launch = async (start) => {
|
|
92
|
+
const config = readConfig(paths);
|
|
93
|
+
accounts = config.accounts;
|
|
94
|
+
account = rota.pick(state.read().account);
|
|
95
|
+
if (account !== void 0) state.write({
|
|
96
|
+
...state.read(),
|
|
97
|
+
account
|
|
98
|
+
});
|
|
99
|
+
folder = config.folder;
|
|
100
|
+
mkdirSync(config.folder, { recursive: true });
|
|
101
|
+
const base = {
|
|
102
|
+
...Object.fromEntries(Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key))),
|
|
103
|
+
...config.env,
|
|
104
|
+
...account !== void 0 && {
|
|
105
|
+
...config.accounts[account].env,
|
|
106
|
+
HARNESSD_ACCOUNT: account
|
|
107
|
+
},
|
|
108
|
+
...paths.env
|
|
109
|
+
};
|
|
110
|
+
if (account !== void 0) log(`Claude Code runs on account ${account}`);
|
|
111
|
+
const hook = config.prestart ? await prestart(config.prestart, config.folder, base, log) : {
|
|
112
|
+
env: {},
|
|
113
|
+
args: []
|
|
114
|
+
};
|
|
115
|
+
const env = {
|
|
116
|
+
...base,
|
|
117
|
+
...hook.env
|
|
118
|
+
};
|
|
119
|
+
claudeEnv = env;
|
|
120
|
+
trustFolder(config.folder, env);
|
|
121
|
+
writePlugin(paths, config, bin);
|
|
122
|
+
const onAccount = account !== void 0 && Object.keys(config.accounts).length > 1 ? accountRun({
|
|
123
|
+
account,
|
|
124
|
+
rotation: rota,
|
|
125
|
+
sessionId: () => dog.status().sessionId ?? start.sessionId,
|
|
126
|
+
file: (id) => findTranscript(id, env),
|
|
127
|
+
restart: (reason, pid) => void dog.restart(reason, pid),
|
|
128
|
+
log
|
|
129
|
+
}) : void 0;
|
|
130
|
+
let handover;
|
|
131
|
+
let p;
|
|
132
|
+
let args;
|
|
133
|
+
try {
|
|
134
|
+
const file = which("claude", env.PATH);
|
|
135
|
+
const { spawn } = await import("@lydell/node-pty");
|
|
136
|
+
args = claudeArgs({
|
|
137
|
+
start,
|
|
138
|
+
plugin: paths.plugin,
|
|
139
|
+
config,
|
|
140
|
+
extra: hook.args
|
|
141
|
+
});
|
|
142
|
+
p = spawn(file, args, {
|
|
143
|
+
name: "xterm-256color",
|
|
144
|
+
cols: size.cols,
|
|
145
|
+
rows: size.rows,
|
|
146
|
+
cwd: config.folder,
|
|
147
|
+
env
|
|
148
|
+
});
|
|
149
|
+
} catch (error) {
|
|
150
|
+
onAccount?.exited();
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
onAccount?.started(p.pid);
|
|
154
|
+
pty = p;
|
|
155
|
+
prompts.reset({ skipsPermissions: skipsPermissions(args) });
|
|
156
|
+
show(`\r\n\x1b[2m── harnessd started Claude Code ${(/* @__PURE__ */ new Date()).toLocaleString()} ──\x1b[0m\r\n`);
|
|
157
|
+
p.onData((data) => {
|
|
158
|
+
show(data);
|
|
159
|
+
prompts.push(data);
|
|
160
|
+
});
|
|
161
|
+
const exited = new Promise((resolve) => p.onExit(({ exitCode, signal }) => {
|
|
162
|
+
handover = onAccount?.exited();
|
|
163
|
+
if (pty === p) {
|
|
164
|
+
pty = void 0;
|
|
165
|
+
prompts.reset();
|
|
166
|
+
}
|
|
167
|
+
resolve(signal ? 128 + signal : exitCode);
|
|
168
|
+
}));
|
|
169
|
+
return {
|
|
170
|
+
pid: p.pid,
|
|
171
|
+
exited,
|
|
172
|
+
ended: () => handover,
|
|
173
|
+
kill: (signal) => {
|
|
174
|
+
try {
|
|
175
|
+
p.kill(signal);
|
|
176
|
+
} catch {}
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
const resize = (cols, rows) => {
|
|
181
|
+
if (cols === size.cols && rows === size.rows) return;
|
|
182
|
+
size = {
|
|
183
|
+
cols,
|
|
184
|
+
rows
|
|
185
|
+
};
|
|
186
|
+
prompts.resize(cols, rows);
|
|
187
|
+
try {
|
|
188
|
+
pty?.resize(cols, rows);
|
|
189
|
+
} catch {}
|
|
190
|
+
};
|
|
191
|
+
const dog = watchdog({
|
|
192
|
+
launch,
|
|
193
|
+
state,
|
|
194
|
+
hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== void 0,
|
|
195
|
+
log
|
|
196
|
+
});
|
|
197
|
+
const status = () => {
|
|
198
|
+
const waitingOn = prompts.waitingOn();
|
|
199
|
+
const stops = rota.marks();
|
|
200
|
+
return {
|
|
201
|
+
...dog.status(),
|
|
202
|
+
daemonPid: process.pid,
|
|
203
|
+
...folder && { folder },
|
|
204
|
+
...waitingOn && { waitingOn },
|
|
205
|
+
...prompts.channelsRefused() && { channelsRefused: true },
|
|
206
|
+
...account !== void 0 && { account },
|
|
207
|
+
...Object.keys(stops).length > 0 && { accountsStopped: Object.fromEntries(Object.entries(stops).map(([name, { why, until }]) => [name, {
|
|
208
|
+
why,
|
|
209
|
+
until: new Date(until).toISOString()
|
|
210
|
+
}])) }
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
const serve = (connection) => {
|
|
214
|
+
const reply = (value) => connection.end(`${JSON.stringify(value)}\n`);
|
|
215
|
+
const done = (message) => reply({
|
|
216
|
+
ok: message !== NOT_STARTED,
|
|
217
|
+
message
|
|
218
|
+
});
|
|
219
|
+
const lines = createInterface({ input: connection });
|
|
220
|
+
let attached = false;
|
|
221
|
+
connection.on("error", () => {});
|
|
222
|
+
lines.on("line", async (line) => {
|
|
223
|
+
let message;
|
|
224
|
+
try {
|
|
225
|
+
message = JSON.parse(line);
|
|
226
|
+
} catch {
|
|
227
|
+
reply({
|
|
228
|
+
ok: false,
|
|
229
|
+
message: "Not JSON."
|
|
230
|
+
});
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (attached) {
|
|
234
|
+
if (typeof message.input === "string") pty?.write(message.input);
|
|
235
|
+
const asked = message.resize;
|
|
236
|
+
if (asked) resize(clamp(asked.cols, 20, 500, size.cols), clamp(asked.rows, 5, 300, size.rows));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const request = message;
|
|
240
|
+
if (request.command === "status") return void reply({
|
|
241
|
+
ok: true,
|
|
242
|
+
status: status()
|
|
243
|
+
});
|
|
244
|
+
if (request.command === "stop") return void reply({
|
|
245
|
+
ok: true,
|
|
246
|
+
message: await dog.stop()
|
|
247
|
+
});
|
|
248
|
+
if (request.command === "start") return void done(await dog.start());
|
|
249
|
+
if (request.command === "session-start") {
|
|
250
|
+
if (!SESSION_ID.test(String(request.sessionId))) return void reply({
|
|
251
|
+
ok: false,
|
|
252
|
+
message: "sessionId must be a conversation id."
|
|
253
|
+
});
|
|
254
|
+
dog.follow(request.sessionId);
|
|
255
|
+
reply({ ok: true });
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (request.command === "attach") {
|
|
259
|
+
attached = true;
|
|
260
|
+
viewers.add(connection);
|
|
261
|
+
resize(clamp(request.cols, 20, 500, IDLE_SIZE.cols), clamp(request.rows, 5, 300, IDLE_SIZE.rows));
|
|
262
|
+
connection.write(`${JSON.stringify({ output: term.read() })}\n`);
|
|
263
|
+
connection.on("close", () => {
|
|
264
|
+
viewers.delete(connection);
|
|
265
|
+
if (viewers.size === 0) resize(IDLE_SIZE.cols, IDLE_SIZE.rows);
|
|
266
|
+
});
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
reply({
|
|
270
|
+
ok: false,
|
|
271
|
+
message: `Unknown command ${String(request.command)}.`
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
const server = createServer(serve);
|
|
276
|
+
await new Promise((resolve, reject) => {
|
|
277
|
+
server.once("error", reject);
|
|
278
|
+
server.listen(paths.socket, resolve);
|
|
279
|
+
});
|
|
280
|
+
log(`harnessd ${process.pid} started`);
|
|
281
|
+
let stopping = false;
|
|
282
|
+
const shutdown = async (signal) => {
|
|
283
|
+
if (stopping) return;
|
|
284
|
+
stopping = true;
|
|
285
|
+
log(`harnessd got ${signal}; stopping Claude Code`);
|
|
286
|
+
await dog.shutdown();
|
|
287
|
+
for (const viewer of viewers) viewer.end();
|
|
288
|
+
server.close();
|
|
289
|
+
rmSync(paths.socket, { force: true });
|
|
290
|
+
log(`harnessd ${process.pid} stopped`);
|
|
291
|
+
process.exit(0);
|
|
292
|
+
};
|
|
293
|
+
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
294
|
+
process.on("SIGINT", () => void shutdown("SIGINT"));
|
|
295
|
+
process.on("SIGHUP", () => void shutdown("SIGHUP"));
|
|
296
|
+
await dog.run();
|
|
297
|
+
};
|
|
298
|
+
export { ask, runDaemon };
|
|
299
|
+
|
|
300
|
+
//# sourceMappingURL=daemon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon.js","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createConnection, createServer, type Socket } from \"node:net\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IPty } from \"@lydell/node-pty\";\nimport { accountRun, rotation } from \"./accounts\";\nimport {\n claudeArgs,\n skipsPermissions,\n findTranscript,\n prestart,\n trustFolder,\n which,\n writePlugin,\n} from \"./claude\";\nimport { ownFolder, readConfig, type Harnessd } from \"./config\";\nimport { logTo } from \"./log\";\nimport { promptWatcher } from \"./prompts\";\nimport { IDLE_SIZE, scrollback } from \"./terminal\";\nimport { NOT_STARTED, watchdog, type Watchdog } from \"./watchdog\";\n\nexport namespace Daemon {\n /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */\n export type Request =\n | { readonly command: \"status\" | \"stop\" | \"start\" }\n /** From Claude Code's SessionStart hook: the conversation it is in now. */\n | { readonly command: \"session-start\"; readonly sessionId: string }\n | {\n readonly command: \"attach\";\n readonly cols: number;\n readonly rows: number;\n };\n\n export type Status = Watchdog.Status & {\n readonly daemonPid: number;\n readonly folder?: string;\n /** The account Claude Code runs on, when the config names accounts. */\n readonly account?: string;\n /** The accounts passed over, and until when. */\n readonly accountsStopped?: Readonly<\n Record<string, { readonly why: string; readonly until: string }>\n >;\n /** The prompt Claude Code waits at until a person answers it. */\n readonly waitingOn?: string;\n /** Claude Code said managed settings keep channels out: it drops their events. */\n readonly channelsRefused?: true;\n };\n}\n\n// a Claude Code session's own markers, which the agent's session must not inherit\nconst OWN_ENV =\n /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;\n\nconst VIEWER_BUFFER = 8 * 1024 * 1024;\n\nconst SESSION_ID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst clamp = (value: unknown, min: number, max: number, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(min, Math.min(max, Math.floor(value)))\n : fallback;\n\n/** Sends one request to a running harnessd; undefined when none answers. */\nexport const ask = (socket: string, request: Daemon.Request) =>\n new Promise<Record<string, unknown> | undefined>((resolve) => {\n if (!existsSync(socket)) return resolve(undefined);\n const connection = createConnection(socket);\n connection.once(\"error\", () => resolve(undefined));\n connection.once(\"connect\", () =>\n connection.write(`${JSON.stringify(request)}\\n`),\n );\n const lines = createInterface({ input: connection });\n // readline passes the connection's error on: a socket file nobody listens on (harnessd was killed) is no answer\n lines.once(\"error\", () => resolve(undefined));\n lines.once(\"line\", (line) => {\n connection.end();\n try {\n resolve(JSON.parse(line));\n } catch {\n resolve(undefined);\n }\n });\n lines.once(\"close\", () => resolve(undefined));\n });\n\n/** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */\nexport const runDaemon = async (paths: Harnessd.Paths, bin: string) => {\n ownFolder(paths.home);\n ownFolder(dirname(paths.config));\n const socketDir = dirname(paths.socket);\n if (socketDir !== paths.home) {\n mkdirSync(socketDir, { recursive: true, mode: 0o700 });\n // a socket outside harnessd's folder sits in a shared one, where another user may have made its folder first\n if (statSync(socketDir).uid !== process.getuid!())\n throw new Error(`${socketDir} belongs to another user`);\n }\n const log = logTo(paths.log);\n if (await ask(paths.socket, { command: \"status\" }))\n throw new Error(`Another harnessd already runs in ${paths.home}`);\n rmSync(paths.socket, { force: true });\n\n const term = scrollback();\n const viewers = new Set<Socket>();\n let size = IDLE_SIZE;\n let pty: IPty | undefined;\n let folder: string | undefined;\n const show = (data: string) => {\n term.push(data);\n const line = `${JSON.stringify({ output: data })}\\n`;\n for (const viewer of viewers) {\n // a viewer that stops reading is let go rather than buffered without end\n if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();\n else viewer.write(line);\n }\n };\n\n const prompts = promptWatcher({\n write: (keys) => pty?.write(keys),\n log,\n ...size,\n });\n\n const state = {\n read: (): Watchdog.State => {\n try {\n return JSON.parse(readFileSync(paths.state, \"utf8\")) as Watchdog.State;\n } catch {\n return {};\n }\n },\n write: (value: Watchdog.State) =>\n writeFileSync(paths.state, `${JSON.stringify(value)}\\n`),\n };\n\n // what Claude Code last ran with (before its first start: the config's env): its CLAUDE_CONFIG_DIR says where its transcripts are\n let claudeEnv: NodeJS.ProcessEnv | undefined;\n const transcriptEnv = (): NodeJS.ProcessEnv => {\n if (claudeEnv) return claudeEnv;\n try {\n return { ...process.env, ...readConfig(paths).env };\n } catch {\n return process.env;\n }\n };\n let accounts: Harnessd.Config[\"accounts\"] = {};\n let account: string | undefined;\n const rota = rotation({\n accounts: () =>\n Object.fromEntries(\n Object.entries(accounts).map(([name, { env }]) => [name, env]),\n ),\n });\n const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {\n const config = readConfig(paths);\n accounts = config.accounts;\n account = rota.pick(state.read().account);\n if (account !== undefined) state.write({ ...state.read(), account });\n folder = config.folder;\n mkdirSync(config.folder, { recursive: true });\n const inherited = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key)),\n ) as Record<string, string>;\n const base: Record<string, string> = {\n ...inherited,\n ...config.env,\n ...(account !== undefined && {\n ...config.accounts[account]!.env,\n HARNESSD_ACCOUNT: account,\n }),\n ...paths.env,\n };\n if (account !== undefined) log(`Claude Code runs on account ${account}`);\n const hook = config.prestart\n ? await prestart(config.prestart, config.folder, base, log)\n : { env: {}, args: [] };\n const env = { ...base, ...hook.env };\n claudeEnv = env;\n trustFolder(config.folder, env);\n writePlugin(paths, config, bin);\n // from before the start, so a refusal Claude Code writes at once is read\n const onAccount =\n account !== undefined && Object.keys(config.accounts).length > 1\n ? accountRun({\n account,\n rotation: rota,\n sessionId: () => dog.status().sessionId ?? start.sessionId,\n file: (id) => findTranscript(id, env),\n restart: (reason, pid) => void dog.restart(reason, pid),\n log,\n })\n : undefined;\n let handover: string | undefined;\n let p: IPty;\n let args: string[];\n try {\n const file = which(\"claude\", env.PATH);\n const { spawn } = await import(\"@lydell/node-pty\");\n args = claudeArgs({\n start,\n plugin: paths.plugin,\n config,\n extra: hook.args,\n });\n p = spawn(file, args, {\n name: \"xterm-256color\",\n cols: size.cols,\n rows: size.rows,\n cwd: config.folder,\n env,\n });\n } catch (error) {\n onAccount?.exited();\n throw error;\n }\n onAccount?.started(p.pid);\n pty = p;\n prompts.reset({ skipsPermissions: skipsPermissions(args) });\n show(\n `\\r\\n\\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\\x1b[0m\\r\\n`,\n );\n p.onData((data) => {\n show(data);\n prompts.push(data);\n });\n const exited = new Promise<number>((resolve) =>\n p.onExit(({ exitCode, signal }) => {\n // the last lines too: an account that stopped right before the exit isn't started again\n handover = onAccount?.exited();\n if (pty === p) {\n pty = undefined;\n prompts.reset();\n }\n resolve(signal ? 128 + signal : exitCode);\n }),\n );\n return {\n pid: p.pid,\n exited,\n ended: () => handover,\n kill: (signal) => {\n try {\n p.kill(signal);\n } catch {}\n },\n };\n };\n\n const resize = (cols: number, rows: number) => {\n if (cols === size.cols && rows === size.rows) return;\n size = { cols, rows };\n prompts.resize(cols, rows);\n try {\n pty?.resize(cols, rows);\n } catch {}\n };\n\n const dog = watchdog({\n launch,\n state,\n hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== undefined,\n log,\n });\n\n const status = (): Daemon.Status => {\n const waitingOn = prompts.waitingOn();\n const stops = rota.marks();\n return {\n ...dog.status(),\n daemonPid: process.pid,\n ...(folder && { folder }),\n ...(waitingOn && { waitingOn }),\n ...(prompts.channelsRefused() && { channelsRefused: true as const }),\n ...(account !== undefined && { account }),\n ...(Object.keys(stops).length > 0 && {\n accountsStopped: Object.fromEntries(\n Object.entries(stops).map(([name, { why, until }]) => [\n name,\n { why, until: new Date(until).toISOString() },\n ]),\n ),\n }),\n };\n };\n\n const serve = (connection: Socket) => {\n const reply = (value: unknown) =>\n connection.end(`${JSON.stringify(value)}\\n`);\n const done = (message: string) =>\n reply({ ok: message !== NOT_STARTED, message });\n const lines = createInterface({ input: connection });\n let attached = false;\n connection.on(\"error\", () => {});\n lines.on(\"line\", async (line): Promise<void> => {\n let message: Record<string, unknown>;\n try {\n message = JSON.parse(line);\n } catch {\n return void reply({ ok: false, message: \"Not JSON.\" });\n }\n if (attached) {\n if (typeof message.input === \"string\") pty?.write(message.input);\n const asked = message.resize as\n | { cols?: unknown; rows?: unknown }\n | undefined;\n if (asked)\n resize(\n clamp(asked.cols, 20, 500, size.cols),\n clamp(asked.rows, 5, 300, size.rows),\n );\n return;\n }\n const request = message as Daemon.Request;\n if (request.command === \"status\")\n return void reply({ ok: true, status: status() });\n if (request.command === \"stop\")\n return void reply({ ok: true, message: await dog.stop() });\n if (request.command === \"start\") return void done(await dog.start());\n if (request.command === \"session-start\") {\n if (!SESSION_ID.test(String(request.sessionId)))\n return void reply({\n ok: false,\n message: \"sessionId must be a conversation id.\",\n });\n dog.follow(request.sessionId);\n return void reply({ ok: true });\n }\n if (request.command === \"attach\") {\n attached = true;\n viewers.add(connection);\n resize(\n clamp(request.cols, 20, 500, IDLE_SIZE.cols),\n clamp(request.rows, 5, 300, IDLE_SIZE.rows),\n );\n connection.write(`${JSON.stringify({ output: term.read() })}\\n`);\n connection.on(\"close\", () => {\n viewers.delete(connection);\n if (viewers.size === 0) resize(IDLE_SIZE.cols, IDLE_SIZE.rows);\n });\n return;\n }\n reply({\n ok: false,\n message: `Unknown command ${String((request as { command?: unknown }).command)}.`,\n });\n });\n };\n\n const server = createServer(serve);\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(paths.socket, resolve);\n });\n log(`harnessd ${process.pid} started`);\n\n let stopping = false;\n const shutdown = async (signal: string) => {\n if (stopping) return;\n stopping = true;\n log(`harnessd got ${signal}; stopping Claude Code`);\n await dog.shutdown();\n for (const viewer of viewers) viewer.end();\n server.close();\n rmSync(paths.socket, { force: true });\n log(`harnessd ${process.pid} stopped`);\n process.exit(0);\n };\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGHUP\", () => void shutdown(\"SIGHUP\"));\n await dog.run();\n};\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Q,EAAE,OAAO,KAAK,CAAC;EACpC,IAAI,YAAY,QAAQ,IAAI,SAAS;EACrC,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,iBAAiB,KAAK,SAAS,SAAS,CAAC;CACpD,QAAQ,GAAG,gBAAgB,KAAK,SAAS,QAAQ,CAAC;CAClD,QAAQ,GAAG,gBAAgB,KAAK,SAAS,QAAQ,CAAC;CAClD,MAAM,IAAI,IAAI;AAChB"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Service } from "./service.js";
|
|
2
|
+
/**
|
|
3
|
+
* The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
|
|
4
|
+
* /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
|
|
5
|
+
* harnessd unable to start. None that is this one: `process.execPath`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const stableNode: (execPath?: string, path?: string) => string;
|
|
8
|
+
/** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
|
|
9
|
+
export declare const plistFolder: (home: string) => string;
|
|
10
|
+
/** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
|
|
11
|
+
export declare const plistPath: (label: string, boot?: boolean) => string;
|
|
12
|
+
/** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
|
|
13
|
+
export declare const plistOf: (o: Service.Spec) => string;
|
|
14
|
+
/** Writes the launchd entry and (re)loads it, which starts harnessd. */
|
|
15
|
+
export declare const load: (label: string, plist: string, boot: boolean) => Promise<void>;
|
|
16
|
+
/** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
|
|
17
|
+
export declare const unload: (label: string, boot: boolean) => boolean;
|
|
18
|
+
//# sourceMappingURL=launchd.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"launchd.d.ts","sourceRoot":"","sources":["../src/launchd.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAE,qBAAkB;AAMzC;;;;GAIG;AACH,eAAO,MAAM,UAAU,GACrB,iBAA2B,EAC3B,aAA6B,WAiB9B,CAAC;AAEF,2GAA2G;AAC3G,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,WAC0B,CAAC;AAEnE,oFAAoF;AACpF,eAAO,MAAM,SAAS,GAAI,OAAO,MAAM,EAAE,cAAY,WAGa,CAAC;AAEnE,4GAA4G;AAC5G,eAAO,MAAM,OAAO,GAClB,GAAG,OAAO,CAAC,IAAI,WAqChB,CAAC;AAUF,wEAAwE;AACxE,eAAO,MAAM,IAAI,GAAU,OAAO,MAAM,EAAE,OAAO,MAAM,EAAE,MAAM,OAAO,kBAYrE,CAAC;AAEF,iFAAiF;AACjF,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,EAAE,MAAM,OAAO,YAYlD,CAAC"}
|