@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.
- package/README.md +31 -18
- 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.js +4 -0
- package/dist/bin.js.map +1 -1
- package/dist/channel.d.ts +15 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +113 -158
- package/dist/channel.js.map +1 -1
- package/dist/claude.d.ts +17 -13
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +69 -59
- package/dist/claude.js.map +1 -1
- package/dist/cli.d.ts +5 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +317 -131
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +46 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +142 -51
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +29 -4
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +174 -51
- package/dist/daemon.js.map +1 -1
- package/dist/launchd.d.ts +12 -16
- package/dist/launchd.d.ts.map +1 -1
- package/dist/launchd.js +28 -25
- package/dist/launchd.js.map +1 -1
- 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/watchdog.d.ts +14 -4
- package/dist/watchdog.d.ts.map +1 -1
- package/dist/watchdog.js +30 -24
- package/dist/watchdog.js.map +1 -1
- package/package.json +8 -12
- package/src/accounts.ts +242 -0
- package/src/bin.ts +6 -0
- package/src/channel.ts +151 -172
- package/src/claude.ts +90 -88
- package/src/cli.ts +494 -183
- package/src/config.ts +239 -63
- package/src/daemon.ts +215 -65
- package/src/launchd.ts +40 -35
- 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/watchdog.ts +41 -33
package/dist/cli.js
CHANGED
|
@@ -1,95 +1,220 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { readStatus, serveChannel, statusFile } from "./channel.js";
|
|
1
|
+
import { defaultConfig, ownFolder, pathsOf, readConfig } from "./config.js";
|
|
2
|
+
import { readStatus, serveChannel, serverCli, subscriptionLabel } from "./channel.js";
|
|
4
3
|
import { logTo } from "./log.js";
|
|
4
|
+
import { CHANNELS_REFUSED } from "./prompts.js";
|
|
5
5
|
import { ask, runDaemon } from "./daemon.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { stableNode } from "./launchd.js";
|
|
7
|
+
import { asUser, installService, lookUpUser, removeService, serviceIn, servicePath, serviceText, supportedPlatform } from "./service.js";
|
|
8
|
+
import { ensureClaude, ensureSignedIn, ttyTerminal } from "./setup.js";
|
|
9
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
9
12
|
import { createConnection } from "node:net";
|
|
13
|
+
import { userInfo } from "node:os";
|
|
14
|
+
import { delimiter, dirname } from "node:path";
|
|
10
15
|
import { createInterface } from "node:readline";
|
|
16
|
+
import { processCliIo, runCli } from "toolport/cli";
|
|
11
17
|
// src/cli.ts
|
|
12
|
-
const USAGE = `harnessd keeps Claude Code running on this
|
|
18
|
+
const USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.
|
|
13
19
|
|
|
14
20
|
usage: harnessd <command>
|
|
15
21
|
|
|
16
|
-
install
|
|
17
|
-
uninstall
|
|
18
|
-
status [--json]
|
|
19
|
-
start
|
|
20
|
-
stop
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
service install Start harnessd now and at every login; with sudo, at every boot
|
|
23
|
+
service uninstall Stop harnessd and remove its service
|
|
24
|
+
status [--json] What runs, which conversation, the channel's events, and the log's last lines
|
|
25
|
+
start Start Claude Code after a stop
|
|
26
|
+
stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start
|
|
27
|
+
attach Open Claude Code's terminal; Ctrl-\\ detaches
|
|
28
|
+
tools <server> ... Run a server's tools, as the agent's <server> command does
|
|
29
|
+
--version Print harnessd's version
|
|
24
30
|
|
|
25
|
-
|
|
31
|
+
service install takes:
|
|
32
|
+
--user <name> With sudo: the user the boot service runs as; service uninstall takes it too
|
|
33
|
+
--dry-run Print the service's file and change nothing
|
|
34
|
+
--install-claude When Claude Code is missing, install it with Anthropic's installer without asking
|
|
35
|
+
--skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in
|
|
36
|
+
|
|
37
|
+
Settings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.
|
|
38
|
+
XDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;
|
|
39
|
+
const VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
26
40
|
const DETACH = "";
|
|
27
|
-
const
|
|
41
|
+
const stdin = async () => {
|
|
42
|
+
let text = "";
|
|
43
|
+
for await (const chunk of process.stdin) text += String(chunk);
|
|
44
|
+
return text;
|
|
45
|
+
};
|
|
46
|
+
const notRunning = (paths) => `harnessd isn't running in ${paths.home}: harnessd service install starts it.`;
|
|
47
|
+
const usageError = (message) => Object.assign(new Error(message), { usage: true });
|
|
48
|
+
/** Refuses any argument a command doesn't take, so a typo never runs the command. */
|
|
49
|
+
const takes = (command, rest, allowed = []) => {
|
|
50
|
+
const extra = rest.find((arg) => !allowed.includes(arg));
|
|
51
|
+
if (extra !== void 0) throw usageError(`harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(", ")}` : "no arguments"}, not ${extra}.`);
|
|
52
|
+
};
|
|
53
|
+
const tail = (file, lines) => {
|
|
54
|
+
try {
|
|
55
|
+
const text = readFileSync(file, "utf8").trimEnd();
|
|
56
|
+
return text ? text.split("\n").slice(-lines) : [];
|
|
57
|
+
} catch {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const daemonStatus = async (paths) => (await ask(paths.socket, { command: "status" }))?.status;
|
|
62
|
+
const START_WAIT_MS = 9e4;
|
|
63
|
+
/** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */
|
|
64
|
+
const settled = async (paths, not, waitMs = START_WAIT_MS) => {
|
|
65
|
+
const until = Date.now() + waitMs;
|
|
66
|
+
for (;;) {
|
|
67
|
+
const status = await daemonStatus(paths);
|
|
68
|
+
const ours = status && status.daemonPid !== not ? status : void 0;
|
|
69
|
+
if (ours && ours.state !== "starting" || Date.now() >= until) return ours;
|
|
70
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
/** After a failed start: the log lines that show why; resolves to the exit code. */
|
|
74
|
+
const showLog = (log, io) => {
|
|
75
|
+
for (const line of tail(log, 10)) io.err(` ${line}`);
|
|
76
|
+
io.err(`log ${log}`);
|
|
77
|
+
return 1;
|
|
78
|
+
};
|
|
79
|
+
/** Says why a start failed, with the log's last lines; resolves to the exit code. */
|
|
80
|
+
const startFailed = (paths, status, io) => {
|
|
81
|
+
io.err(!status ? "harnessd didn't start." : status.state === "waiting" ? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : ""}; harnessd keeps trying.` : "Claude Code is still starting; harnessd status shows how it goes.");
|
|
82
|
+
return showLog(status ? paths.log : paths.serviceLog, io);
|
|
83
|
+
};
|
|
28
84
|
const command = async (paths, request, io) => {
|
|
29
85
|
const answer = await ask(paths.socket, request);
|
|
30
86
|
if (!answer) {
|
|
31
87
|
io.err(notRunning(paths));
|
|
32
88
|
return 1;
|
|
33
89
|
}
|
|
34
|
-
|
|
35
|
-
|
|
90
|
+
if (!answer.ok) {
|
|
91
|
+
io.err(String(answer.message));
|
|
92
|
+
return request.command === "stop" ? 1 : showLog(paths.log, io);
|
|
93
|
+
}
|
|
94
|
+
if (request.command !== "stop") {
|
|
95
|
+
const status = await settled(paths);
|
|
96
|
+
if (status?.state !== "running") return startFailed(paths, status, io);
|
|
97
|
+
}
|
|
98
|
+
io.out(String(answer.message));
|
|
99
|
+
return 0;
|
|
36
100
|
};
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
101
|
+
/** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */
|
|
102
|
+
const serviceTarget = (action, flags) => {
|
|
103
|
+
const root = process.getuid?.() === 0;
|
|
104
|
+
if (flags.user !== void 0 && !root && !flags.dryRun) throw new Error(`A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`);
|
|
105
|
+
const name = flags.user ?? (root ? process.env.SUDO_USER : void 0);
|
|
106
|
+
if (root && name === void 0) throw new Error("Name the user harnessd runs as: --user <name>");
|
|
107
|
+
const user = name === void 0 ? void 0 : lookUpUser(name);
|
|
108
|
+
const caller = process.env.SUDO_USER ?? userInfo().username;
|
|
109
|
+
const moved = [
|
|
110
|
+
"HARNESSD_HOME",
|
|
111
|
+
"XDG_CONFIG_HOME",
|
|
112
|
+
"XDG_STATE_HOME"
|
|
113
|
+
].find((key) => process.env[key]);
|
|
114
|
+
if (user && user.name !== caller && moved) throw new Error(`${moved} is set in your shell, and --user ${user.name} installs in ${user.name}'s own folders: unset it, or let ${user.name} run the install.`);
|
|
115
|
+
if (user) Object.assign(process.env, {
|
|
116
|
+
HOME: user.home,
|
|
117
|
+
USER: user.name,
|
|
118
|
+
LOGNAME: user.name
|
|
41
119
|
});
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
120
|
+
const paths = pathsOf();
|
|
121
|
+
if (user && !paths.socket.startsWith(paths.home)) throw new Error(`${paths.home} is too long a path for harnessd's socket, and a boot service keeps its socket there: set a shorter XDG_STATE_HOME or HARNESSD_HOME.`);
|
|
122
|
+
const bootLabel = (name) => paths.label === "dev.harnessd" ? `dev.harnessd.${name}` : paths.label;
|
|
123
|
+
return {
|
|
124
|
+
user,
|
|
125
|
+
paths,
|
|
126
|
+
label: user ? bootLabel(user.name) : paths.label,
|
|
127
|
+
/** The other kind's file, when one is installed for this state folder: it holds one harnessd. */
|
|
128
|
+
other: () => serviceIn(paths.home, user === void 0)
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
const uninstall = (flags, io) => {
|
|
132
|
+
const { user, paths, label, other } = serviceTarget("uninstall", flags);
|
|
133
|
+
if (removeService(label, user !== void 0)) {
|
|
134
|
+
io.out(`Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`);
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
const file = other();
|
|
138
|
+
io[file ? "err" : "out"](file ? `harnessd is installed as a ${user ? "login item" : "boot service"} (${file}): run ${user ? "" : "sudo "}harnessd service uninstall.` : "harnessd wasn't installed.");
|
|
139
|
+
return file ? 1 : 0;
|
|
45
140
|
};
|
|
46
|
-
const install = async (
|
|
47
|
-
|
|
48
|
-
if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so
|
|
49
|
-
const
|
|
141
|
+
const install = async (flags, bin, io) => {
|
|
142
|
+
supportedPlatform();
|
|
143
|
+
if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd");
|
|
144
|
+
const { user, paths, label, other } = serviceTarget("install", flags);
|
|
145
|
+
const own = (process.env.PATH ?? "/usr/bin:/bin").split(delimiter);
|
|
146
|
+
const terminal = flags.dryRun ? void 0 : io.terminal;
|
|
147
|
+
const claude = await ensureClaude({
|
|
148
|
+
terminal,
|
|
149
|
+
user,
|
|
150
|
+
install: flags.installClaude && !flags.dryRun
|
|
151
|
+
});
|
|
50
152
|
const version = spawnSync(claude, ["--version"], {
|
|
51
153
|
encoding: "utf8",
|
|
52
|
-
timeout: 3e4
|
|
154
|
+
timeout: 3e4,
|
|
155
|
+
...user && process.getuid?.() === 0 && {
|
|
156
|
+
uid: user.uid,
|
|
157
|
+
gid: user.gid
|
|
158
|
+
}
|
|
53
159
|
});
|
|
54
160
|
if (version.status !== 0) throw new Error(`${claude} --version failed: ${(version.stderr || version.stdout || "").trim()}`);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const blockers = Object.keys(config.channels).length > 0 ? channelBlockers() : [];
|
|
60
|
-
if (blockers.length > 0) {
|
|
61
|
-
io.out(`Claude Code lets a channel in only when this Mac's managed settings list it:\n ${blockers.join("\n ")}`);
|
|
62
|
-
if (process.stdin.isTTY && await confirm(`Let harnessd's channels in? This writes /Library/Application Support/ClaudeCode/managed-settings.json with sudo.`)) {
|
|
63
|
-
if (spawnSync("sudo", [
|
|
64
|
-
"sh",
|
|
65
|
-
"-c",
|
|
66
|
-
`mkdir -p "$(dirname "$1")" && cat > "$1"`,
|
|
67
|
-
"sh",
|
|
68
|
-
"/Library/Application Support/ClaudeCode/managed-settings.json"
|
|
69
|
-
], {
|
|
70
|
-
input: `${JSON.stringify(allowChannel(), null, 2)}\n`,
|
|
71
|
-
stdio: [
|
|
72
|
-
"pipe",
|
|
73
|
-
"inherit",
|
|
74
|
-
"inherit"
|
|
75
|
-
]
|
|
76
|
-
}).status !== 0) throw new Error(`Couldn't write ${MANAGED_SETTINGS}.`);
|
|
77
|
-
} else io.out("Until they're let in, Claude Code drops the channels' events; harnessd status says so.");
|
|
78
|
-
}
|
|
79
|
-
const env = { PATH: process.env.PATH ?? "/usr/bin:/bin" };
|
|
80
|
-
if (process.env.HARNESSD_HOME) env.HARNESSD_HOME = paths.home;
|
|
81
|
-
load(paths.label, plistOf({
|
|
82
|
-
label: paths.label,
|
|
83
|
-
node: stableNode(),
|
|
161
|
+
const node = stableNode();
|
|
162
|
+
const spec = {
|
|
163
|
+
label,
|
|
164
|
+
node,
|
|
84
165
|
bin,
|
|
85
|
-
env
|
|
86
|
-
|
|
87
|
-
|
|
166
|
+
env: {
|
|
167
|
+
PATH: [.../* @__PURE__ */ new Set([
|
|
168
|
+
...own,
|
|
169
|
+
dirname(claude),
|
|
170
|
+
dirname(node)
|
|
171
|
+
])].filter((dir) => dir.startsWith("/")).join(delimiter),
|
|
172
|
+
...user && {
|
|
173
|
+
HOME: user.home,
|
|
174
|
+
USER: user.name,
|
|
175
|
+
LOGNAME: user.name
|
|
176
|
+
},
|
|
177
|
+
...paths.env
|
|
178
|
+
},
|
|
179
|
+
paths,
|
|
180
|
+
...user && { user: user.name }
|
|
181
|
+
};
|
|
182
|
+
const file = servicePath(label, user !== void 0);
|
|
183
|
+
if (flags.dryRun) {
|
|
184
|
+
io.out(`Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : ""}:\n\n${serviceText(spec)}`);
|
|
185
|
+
return 0;
|
|
186
|
+
}
|
|
187
|
+
const taken = other();
|
|
188
|
+
if (taken) throw new Error(`harnessd is already installed as a ${user ? "login item" : "boot service"} (${taken}): run ${user ? "" : "sudo "}harnessd service uninstall first.`);
|
|
189
|
+
const config = asUser(user, () => {
|
|
190
|
+
ownFolder(paths.home);
|
|
191
|
+
ownFolder(dirname(paths.config));
|
|
192
|
+
if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(defaultConfig(), null, 2)}\n`);
|
|
193
|
+
chmodSync(paths.config, 384);
|
|
194
|
+
appendFileSync(paths.serviceLog, "");
|
|
195
|
+
const config = readConfig(paths);
|
|
196
|
+
mkdirSync(config.folder, { recursive: true });
|
|
197
|
+
return config;
|
|
198
|
+
});
|
|
199
|
+
const signIn = await ensureSignedIn({
|
|
200
|
+
claude,
|
|
201
|
+
paths,
|
|
202
|
+
env: spec.env,
|
|
203
|
+
user,
|
|
204
|
+
terminal,
|
|
205
|
+
skip: flags.skipSignIn
|
|
206
|
+
});
|
|
207
|
+
const before = (await daemonStatus(paths))?.daemonPid;
|
|
208
|
+
await installService(spec);
|
|
209
|
+
const status = await settled(paths, before);
|
|
210
|
+
if (status?.state !== "running" && status?.state !== "stopped") return startFailed(paths, status, io);
|
|
211
|
+
const when = user ? `at every boot, as ${user.name}` : "at every login";
|
|
88
212
|
io.out([
|
|
89
|
-
`harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and
|
|
90
|
-
" harnessd attach its terminal
|
|
213
|
+
status.state === "stopped" ? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.` : `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,
|
|
214
|
+
" harnessd attach its terminal; Ctrl-\\ detaches",
|
|
91
215
|
" harnessd status what runs and whether events arrive",
|
|
92
|
-
|
|
216
|
+
...signIn ? [signIn] : [],
|
|
217
|
+
...user ? [] : [process.platform === "darwin" ? "It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut." : "It starts when you sign in and stops when you sign out.", `For a start at boot, with nobody logged in: harnessd service uninstall, then ${process.platform === "darwin" ? "sudo harnessd" : "sudo env \"PATH=$PATH\" harnessd"} service install`]
|
|
93
218
|
].join("\n"));
|
|
94
219
|
return 0;
|
|
95
220
|
};
|
|
@@ -97,21 +222,27 @@ const ago = (iso) => {
|
|
|
97
222
|
const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1e3));
|
|
98
223
|
return s < 120 ? `${s}s` : s < 7200 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;
|
|
99
224
|
};
|
|
100
|
-
/**
|
|
101
|
-
const channelReport = (paths, config, running
|
|
102
|
-
const
|
|
225
|
+
/** The channel as of the Claude Code that runs now (what an earlier run heard says nothing about this one); none without subscriptions. */
|
|
226
|
+
const channelReport = (paths, config, running) => {
|
|
227
|
+
const subscribe = config?.channel.subscribe ?? [];
|
|
228
|
+
if (subscribe.length === 0) return void 0;
|
|
229
|
+
const status = readStatus(paths.channel);
|
|
103
230
|
const since = running?.state === "running" || running?.state === "starting" ? running.startedAt : void 0;
|
|
104
231
|
const now = (at) => since !== void 0 && at !== void 0 && at >= since;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
...status
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
232
|
+
return {
|
|
233
|
+
events: since === void 0 ? "off (Claude Code isn't running)" : running?.channelsRefused ? "refused" : now(status.heardAt) ? "arriving" : now(status.pushedAt) ? "sent, not in the conversation yet" : "none yet",
|
|
234
|
+
subscribe: subscribe.map(subscriptionLabel),
|
|
235
|
+
...status.pushedAt && { pushedAt: status.pushedAt },
|
|
236
|
+
...status.heardAt && { heardAt: status.heardAt }
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
/** Each server: its URL, and the events the channel takes from it. */
|
|
240
|
+
const serverReport = (config) => Object.fromEntries(Object.entries(config?.servers ?? {}).map(([name, server]) => [name, {
|
|
241
|
+
url: server.url,
|
|
242
|
+
events: config.channel.subscribe.filter((subscription) => subscription.server === name).map((subscription) => subscription.event)
|
|
243
|
+
}]));
|
|
113
244
|
const status = async (paths, json, io) => {
|
|
114
|
-
const
|
|
245
|
+
const s = await daemonStatus(paths);
|
|
115
246
|
let config;
|
|
116
247
|
let configError;
|
|
117
248
|
try {
|
|
@@ -119,31 +250,47 @@ const status = async (paths, json, io) => {
|
|
|
119
250
|
} catch (error) {
|
|
120
251
|
configError = error instanceof Error ? error.message : String(error);
|
|
121
252
|
}
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
const
|
|
253
|
+
const channel = channelReport(paths, config, s);
|
|
254
|
+
const servers = serverReport(config);
|
|
255
|
+
const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;
|
|
256
|
+
const logTail = tail(log, 10);
|
|
257
|
+
const code = s && !configError ? 0 : 1;
|
|
125
258
|
if (json) {
|
|
126
259
|
io.out(JSON.stringify({
|
|
127
260
|
running: !!s,
|
|
128
261
|
home: paths.home,
|
|
262
|
+
config: paths.config,
|
|
129
263
|
...s && { status: s },
|
|
130
264
|
...configError && { configError },
|
|
131
|
-
|
|
265
|
+
servers,
|
|
266
|
+
...channel && { channel },
|
|
267
|
+
log,
|
|
268
|
+
logTail
|
|
132
269
|
}));
|
|
133
|
-
return
|
|
270
|
+
return code;
|
|
134
271
|
}
|
|
135
272
|
if (!s) io.out(notRunning(paths));
|
|
136
273
|
else {
|
|
137
274
|
const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
|
|
138
|
-
const what = s.state === "running" ? `Claude Code running${since} (pid ${s.pid})` : s.state === "waiting" ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1e3))}s` : ""}` : s.state === "stopped" ? "Claude Code stopped (harnessd start starts it)" : "Claude Code starting";
|
|
275
|
+
const what = s.state === "running" ? `Claude Code${s.claudeVersion ? ` ${s.claudeVersion}` : ""} running${since} (pid ${s.pid})` : s.state === "waiting" ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1e3))}s` : ""}` : s.state === "stopped" ? "Claude Code stopped (harnessd start starts it)" : "Claude Code starting";
|
|
139
276
|
io.out(`harnessd ${s.daemonPid}: ${what}`);
|
|
277
|
+
if (s.update) io.out(s.update.at ? `updated from Claude Code ${s.update.from} to ${s.update.to} ${ago(s.update.at)} ago` : `Claude Code ${s.update.to} is installed; harnessd restarts into it once the agent is idle`);
|
|
278
|
+
if (s.account) io.out(`account ${s.account}`);
|
|
279
|
+
for (const [name, stop] of Object.entries(s.accountsStopped ?? {})) io.out(`account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`);
|
|
280
|
+
if (s.waitingOn) io.out(`Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`);
|
|
140
281
|
if (s.sessionId) io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : ""}`);
|
|
141
282
|
if (s.restarts > 0 || s.lastExit) io.out(`restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : ""}`);
|
|
142
283
|
}
|
|
143
284
|
if (configError) io.out(configError);
|
|
144
|
-
for (const [name,
|
|
145
|
-
if (
|
|
146
|
-
|
|
285
|
+
for (const [name, server] of Object.entries(servers)) io.out(`server ${name}: the ${name} command, ${server.events.length > 0 ? `events ${server.events.join(", ")}` : "no events subscribed"} (${server.url})`);
|
|
286
|
+
if (channel) {
|
|
287
|
+
io.out(`channel: events ${channel.events}`);
|
|
288
|
+
for (const label of channel.subscribe) io.out(` ${label}`);
|
|
289
|
+
}
|
|
290
|
+
if (s?.channelsRefused && channel) io.out(CHANNELS_REFUSED);
|
|
291
|
+
io.out(`log ${log}`);
|
|
292
|
+
for (const line of logTail) io.out(` ${line}`);
|
|
293
|
+
return code;
|
|
147
294
|
};
|
|
148
295
|
const attach = (paths, io) => new Promise((resolve) => {
|
|
149
296
|
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
@@ -184,7 +331,7 @@ const attach = (paths, io) => new Promise((resolve) => {
|
|
|
184
331
|
process.stdin.resume();
|
|
185
332
|
process.stdin.on("data", onInput);
|
|
186
333
|
process.stdout.on("resize", onResize);
|
|
187
|
-
createInterface({ input: connection }).on("line", (line) => {
|
|
334
|
+
createInterface({ input: connection }).on("error", () => {}).on("line", (line) => {
|
|
188
335
|
try {
|
|
189
336
|
const message = JSON.parse(line);
|
|
190
337
|
if (typeof message.output === "string") process.stdout.write(message.output);
|
|
@@ -196,61 +343,100 @@ const attach = (paths, io) => new Promise((resolve) => {
|
|
|
196
343
|
/** Runs one harnessd command; resolves to the exit code. */
|
|
197
344
|
const runHarnessd = async (argv, bin, io = {
|
|
198
345
|
out: (line) => void process.stdout.write(`${line}\n`),
|
|
199
|
-
err: (line) => void process.stderr.write(`${line}\n`)
|
|
346
|
+
err: (line) => void process.stderr.write(`${line}\n`),
|
|
347
|
+
terminal: ttyTerminal()
|
|
200
348
|
}) => {
|
|
201
|
-
const paths = pathsOf();
|
|
202
349
|
const [first, ...rest] = argv;
|
|
350
|
+
if (first === void 0 || first === "help" || argv.slice(0, first === "tools" ? 2 : void 0).some((arg) => arg === "--help" || arg === "-h")) {
|
|
351
|
+
io.out(USAGE);
|
|
352
|
+
return 0;
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
return await run(first, rest, bin, io);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (!error.usage) throw error;
|
|
358
|
+
io.err(`${error.message} harnessd --help lists the commands.`);
|
|
359
|
+
return 2;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const service = (rest, bin, io) => {
|
|
363
|
+
const [action, ...more] = rest;
|
|
364
|
+
if (action !== "install" && action !== "uninstall") throw usageError("harnessd service takes install or uninstall.");
|
|
365
|
+
const flags = {};
|
|
366
|
+
for (let i = 0; i < more.length; i++) {
|
|
367
|
+
const arg = more[i];
|
|
368
|
+
if (action === "install" && arg === "--dry-run") flags.dryRun = true;
|
|
369
|
+
else if (action === "install" && arg === "--install-claude") flags.installClaude = true;
|
|
370
|
+
else if (action === "install" && arg === "--skip-sign-in") flags.skipSignIn = true;
|
|
371
|
+
else if (arg === "--user" && more[i + 1] !== void 0) flags.user = more[++i];
|
|
372
|
+
else throw usageError(`harnessd service ${action} takes ${action === "install" ? "--user <name>, --dry-run, --install-claude and --skip-sign-in" : "--user <name>"}, not ${arg}.`);
|
|
373
|
+
}
|
|
374
|
+
return action === "install" ? install(flags, bin, io) : uninstall(flags, io);
|
|
375
|
+
};
|
|
376
|
+
const run = async (first, rest, bin, io) => {
|
|
377
|
+
if (first === "--version") {
|
|
378
|
+
takes(first, rest);
|
|
379
|
+
io.out(VERSION);
|
|
380
|
+
return 0;
|
|
381
|
+
}
|
|
382
|
+
if (first === "service") return service(rest, bin, io);
|
|
383
|
+
const paths = pathsOf();
|
|
203
384
|
switch (first) {
|
|
204
|
-
case "
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
io.out(had ? `Removed harnessd from login. Its settings and conversation stay in ${paths.home}.` : "harnessd wasn't installed.");
|
|
208
|
-
return 0;
|
|
209
|
-
}
|
|
210
|
-
case "status": return status(paths, rest.includes("--json"), io);
|
|
385
|
+
case "status":
|
|
386
|
+
takes(first, rest, ["--json"]);
|
|
387
|
+
return status(paths, rest.includes("--json"), io);
|
|
211
388
|
case "start":
|
|
212
|
-
case "stop":
|
|
213
|
-
|
|
214
|
-
command:
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
case "logs": return new Promise((resolve) => {
|
|
219
|
-
if (!existsSync(paths.log)) {
|
|
220
|
-
io.err(`No log yet at ${paths.log}.`);
|
|
221
|
-
return resolve(1);
|
|
222
|
-
}
|
|
223
|
-
spawn("tail", [
|
|
224
|
-
"-n",
|
|
225
|
-
"100",
|
|
226
|
-
"-F",
|
|
227
|
-
paths.log
|
|
228
|
-
], { stdio: "inherit" }).on("exit", (code) => resolve(code ?? 0));
|
|
229
|
-
});
|
|
389
|
+
case "stop":
|
|
390
|
+
takes(first, rest);
|
|
391
|
+
return command(paths, { command: first }, io);
|
|
392
|
+
case "attach":
|
|
393
|
+
takes(first, rest);
|
|
394
|
+
return attach(paths, io);
|
|
230
395
|
case "run":
|
|
396
|
+
takes(first, rest);
|
|
231
397
|
await runDaemon(paths, bin);
|
|
232
398
|
return 0;
|
|
233
|
-
case "
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
if (
|
|
399
|
+
case "session-start": {
|
|
400
|
+
takes(first, rest);
|
|
401
|
+
const input = JSON.parse(await (io.stdin ?? stdin)());
|
|
402
|
+
if (input.agent_id !== void 0) return 0;
|
|
403
|
+
if (typeof input.session_id !== "string") throw new Error("Claude Code's SessionStart input has no session_id.");
|
|
404
|
+
const answer = await ask(paths.socket, {
|
|
405
|
+
command: "session-start",
|
|
406
|
+
sessionId: input.session_id
|
|
407
|
+
});
|
|
408
|
+
if (answer?.ok) return 0;
|
|
409
|
+
io.err(answer ? String(answer.message) : notRunning(paths));
|
|
410
|
+
return 1;
|
|
411
|
+
}
|
|
412
|
+
case "idle": {
|
|
413
|
+
takes(first, rest);
|
|
414
|
+
const answer = await ask(paths.socket, { command: "idle" });
|
|
415
|
+
if (answer?.ok) return 0;
|
|
416
|
+
io.err(answer ? String(answer.message) : notRunning(paths));
|
|
417
|
+
return 1;
|
|
418
|
+
}
|
|
419
|
+
case "channel":
|
|
420
|
+
takes(first, rest);
|
|
237
421
|
await serveChannel({
|
|
238
|
-
|
|
239
|
-
channel,
|
|
422
|
+
config: readConfig(paths),
|
|
240
423
|
paths,
|
|
241
|
-
log: logTo(paths.log,
|
|
424
|
+
log: logTo(paths.log, "channel: ")
|
|
242
425
|
});
|
|
243
426
|
return 0;
|
|
427
|
+
case "tools": {
|
|
428
|
+
const [name, ...args] = rest;
|
|
429
|
+
if (name === void 0) throw usageError("harnessd tools takes a server's name.");
|
|
430
|
+
const { servers } = readConfig(paths);
|
|
431
|
+
const server = Object.hasOwn(servers, name) ? servers[name] : void 0;
|
|
432
|
+
if (!server) throw new Error(`No server "${name}" in ${paths.config}`);
|
|
433
|
+
return runCli(serverCli(paths, name, server, process.env), {
|
|
434
|
+
...await processCliIo(args),
|
|
435
|
+
stdout: io.out,
|
|
436
|
+
stderr: io.err
|
|
437
|
+
});
|
|
244
438
|
}
|
|
245
|
-
|
|
246
|
-
case "help":
|
|
247
|
-
case "--help":
|
|
248
|
-
case "-h":
|
|
249
|
-
io.out(USAGE);
|
|
250
|
-
return first === void 0 ? 1 : 0;
|
|
251
|
-
default:
|
|
252
|
-
io.err(`Unknown command ${first}.\n\n${USAGE}`);
|
|
253
|
-
return 2;
|
|
439
|
+
default: throw usageError(`Unknown command ${first}.`);
|
|
254
440
|
}
|
|
255
441
|
};
|
|
256
442
|
export { runHarnessd };
|