@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nexport namespace Watchdog {\n /** What harnessd keeps across its own restarts. */\n export type State = {\n /** The conversation Claude Code is in, and the next start resumes. */\n readonly sessionId?: string;\n /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */\n readonly stopped?: boolean;\n /** The account Claude Code last ran on, of the config's accounts. */\n readonly account?: string;\n };\n\n /** One start of Claude Code: a new conversation with this id, or a resume of it. */\n export type Start = {\n readonly sessionId: string;\n readonly resume: boolean;\n /** The first message of a resumed conversation: why it restarted. */\n readonly prompt?: string;\n };\n\n export type Run = {\n readonly pid?: number;\n /** Resolves with the exit code (128 + signal for a signal). */\n readonly exited: Promise<number>;\n readonly kill: (signal: NodeJS.Signals) => void;\n /** After the exit: why it ended, when the launcher knows and the next start can go on in the same conversation at once. */\n readonly ended?: () => string | undefined;\n };\n\n export type Timing = {\n readonly minBackoffMs: number;\n readonly maxBackoffMs: number;\n /** A run this long resets the backoff. */\n readonly healthyMs: number;\n /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */\n readonly resumeFailedMs: number;\n /** Alive this long: running. */\n readonly runningAfterMs: number;\n /** How long a stop waits after SIGTERM before SIGKILL. */\n readonly killAfterMs: number;\n /** How long start and a restart wait for Claude Code to start: longer than a prestart command may take (60 s). */\n readonly spawnWaitMs: number;\n };\n\n export type Options = {\n /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */\n readonly launch: (start: Start) => Promise<Run>;\n readonly state: { read(): State; write(state: State): void };\n /** Whether Claude Code still has this conversation's transcript. */\n readonly hasTranscript: (sessionId: string) => boolean;\n readonly log: (line: string) => void;\n readonly timing?: Partial<Timing>;\n readonly now?: () => number;\n readonly newId?: () => string;\n };\n\n export type Status = {\n readonly state: \"starting\" | \"running\" | \"waiting\" | \"stopped\";\n readonly pid?: number | undefined;\n readonly sessionId?: string | undefined;\n readonly startedAt?: string | undefined;\n readonly restarts: number;\n readonly lastExit?:\n | { readonly code: number; readonly at: string }\n | undefined;\n readonly nextStartAt?: string | undefined;\n };\n\n export type Watchdog = {\n /** Runs until `shutdown`. */\n readonly run: () => Promise<void>;\n readonly status: () => Status;\n readonly stop: () => Promise<string>;\n readonly start: () => Promise<string>;\n /** Claude Code moved to this conversation (a /clear, a /resume): later starts resume it. */\n readonly follow: (sessionId: string) => void;\n /** Stops the Claude Code that runs and starts it again at once, in the same conversation, which is told `reason`. With `pid`, only while that start still runs. */\n readonly restart: (reason: string, pid?: number) => Promise<string>;\n /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */\n readonly shutdown: () => Promise<void>;\n };\n}\n\nconst DEFAULT_TIMING: Watchdog.Timing = {\n minBackoffMs: 5_000,\n maxBackoffMs: 5 * 60_000,\n healthyMs: 10 * 60_000,\n resumeFailedMs: 30_000,\n runningAfterMs: 3_000,\n killAfterMs: 10_000,\n spawnWaitMs: 75_000,\n};\n\n/** What start and a restart answer when Claude Code didn't start. */\nexport const NOT_STARTED =\n \"Claude Code didn't start in time; harnessd status shows the log.\";\n\nexport const watchdog = (options: Watchdog.Options): Watchdog.Watchdog => {\n const timing = { ...DEFAULT_TIMING, ...options.timing };\n const now = options.now ?? Date.now;\n const newId = options.newId ?? randomUUID;\n const iso = (ms: number) => new Date(ms).toISOString();\n\n let status: Watchdog.Status = { state: \"starting\", restarts: 0 };\n let current: Watchdog.Run | undefined;\n // a start in progress (its prestart can take a minute): commands wait for it, then act on what it started\n let launching: Promise<unknown> = Promise.resolve();\n let shuttingDown = false;\n let restartNow = false;\n let fresh = false;\n let reason = \"harnessd started (a login, a reboot or an update)\";\n let wakeUp = () => {};\n let finished: Promise<void> | undefined;\n const spawnWaiters = new Set<() => void>();\n let queue: Promise<unknown> = Promise.resolve();\n\n const set = (patch: Partial<Watchdog.Status>) => {\n status = { ...status, ...patch };\n };\n const sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n resolve();\n }\n wakeUp = done;\n });\n const nextSpawn = () =>\n new Promise<boolean>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n resolve(true);\n };\n const timer = setTimeout(() => {\n spawnWaiters.delete(done);\n resolve(false);\n }, timing.killAfterMs + timing.spawnWaitMs);\n spawnWaiters.add(done);\n });\n const kill = async (run: Watchdog.Run) => {\n run.kill(\"SIGTERM\");\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exited = await Promise.race([\n run.exited.then(() => true),\n new Promise<false>(\n (resolve) =>\n (timer = setTimeout(() => resolve(false), timing.killAfterMs)),\n ),\n ]);\n clearTimeout(timer);\n if (exited) return;\n options.log(\"Claude Code didn't exit after SIGTERM; sending SIGKILL\");\n run.kill(\"SIGKILL\");\n await run.exited;\n };\n\n const next = (): Watchdog.Start => {\n const { sessionId } = options.state.read();\n if (!fresh && sessionId && options.hasTranscript(sessionId))\n return {\n sessionId,\n resume: true,\n prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`,\n };\n return { sessionId: newId(), resume: false };\n };\n\n const loop = async () => {\n let backoff = timing.minBackoffMs;\n let runs = 0;\n while (!shuttingDown) {\n if (options.state.read().stopped) {\n set({ state: \"stopped\", nextStartAt: undefined });\n await sleep(2 ** 31 - 1);\n continue;\n }\n const start = next();\n options.state.write({\n ...options.state.read(),\n sessionId: start.sessionId,\n });\n if (runs++ > 0) set({ restarts: status.restarts + 1 });\n const startedAt = now();\n set({\n state: \"starting\",\n sessionId: start.sessionId,\n startedAt: iso(startedAt),\n nextStartAt: undefined,\n });\n options.log(\n `starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`,\n );\n let run: Watchdog.Run | undefined;\n try {\n const launch = options\n .launch(start)\n .then((started) => (current = started));\n launching = launch.catch(() => {});\n run = await launch;\n } catch (error) {\n options.log(\n `couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`,\n );\n reason = \"the start before this one failed\";\n }\n if (run) {\n if (!start.resume) fresh = false;\n const spawnedAt = now();\n set({ pid: run.pid });\n for (const waiter of spawnWaiters) waiter();\n spawnWaiters.clear();\n const running = setTimeout(\n () => current === run && set({ state: \"running\" }),\n timing.runningAfterMs,\n );\n const code = await run.exited;\n clearTimeout(running);\n current = undefined;\n const ran = now() - spawnedAt;\n set({ pid: undefined, lastExit: { code, at: iso(now()) } });\n options.log(\n `Claude Code exited with code ${code} after ${Math.round(ran / 1000)}s`,\n );\n if (shuttingDown) break;\n if (restartNow) {\n restartNow = false;\n backoff = timing.minBackoffMs;\n continue;\n }\n if (options.state.read().stopped) continue;\n const ended = run.ended?.();\n if (ended !== undefined) {\n reason = ended;\n backoff = timing.minBackoffMs;\n continue;\n }\n if (start.resume && ran < timing.resumeFailedMs) {\n fresh = true;\n reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;\n options.log(`${reason}; the next start is a new conversation`);\n } else\n reason = `it exited with code ${code} after ${Math.round(ran / 1000)}s`;\n if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;\n }\n if (shuttingDown) break;\n set({ state: \"waiting\", nextStartAt: iso(now() + backoff) });\n options.log(`starting again in ${Math.round(backoff / 1000)}s`);\n await sleep(backoff);\n backoff = Math.min(backoff * 2, timing.maxBackoffMs);\n }\n set({ state: \"stopped\", nextStartAt: undefined });\n };\n\n const serial = (command: () => Promise<string>) => {\n const result = queue.catch(() => {}).then(command);\n queue = result;\n return result;\n };\n\n return {\n run: () => (finished ??= loop()),\n status: () => status,\n stop: () =>\n serial(async () => {\n await launching;\n const stopped = options.state.read().stopped;\n options.state.write({ ...options.state.read(), stopped: true });\n const run = current;\n if (run) await kill(run);\n wakeUp();\n options.log(\"stopped with harnessd stop\");\n return run\n ? \"Stopped Claude Code.\"\n : stopped\n ? \"Claude Code was already stopped.\"\n : \"Stopped (Claude Code was waiting to start).\";\n }),\n start: () =>\n serial(async () => {\n await launching;\n if (current) return \"Claude Code is already running.\";\n options.state.write({ ...options.state.read(), stopped: false });\n reason = \"started with harnessd start\";\n const spawned = nextSpawn();\n wakeUp();\n return (await spawned) ? \"Started Claude Code.\" : NOT_STARTED;\n }),\n follow: (sessionId) => {\n if (sessionId === options.state.read().sessionId) return;\n options.state.write({ ...options.state.read(), sessionId });\n set({ sessionId });\n options.log(`Claude Code moved to conversation ${sessionId}`);\n },\n restart: (why, pid) =>\n serial(async () => {\n await launching;\n const run = current;\n if (!run) return \"Claude Code isn't running.\";\n if (pid !== undefined && run.pid !== pid)\n return \"That start of Claude Code is over.\";\n reason = why;\n const spawned = nextSpawn();\n restartNow = true;\n await kill(run);\n return (await spawned) ? \"Restarted Claude Code.\" : NOT_STARTED;\n }),\n shutdown: async () => {\n shuttingDown = true;\n wakeUp();\n await launching;\n const run = current;\n if (run) await kill(run);\n await finished;\n },\n };\n};\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M,UAAU,UAAU;GAC1B,aAAa;GACb,MAAM,KAAK,GAAG;GACd,OAAQ,MAAM,UAAW,2BAA2B;EACtD,CAAC;EACH,UAAU,YAAY;GACpB,eAAe;GACf,OAAO;GACP,MAAM;GACN,MAAM,MAAM;GACZ,IAAI,KAAK,MAAM,KAAK,GAAG;GACvB,MAAM;EACR;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,9 +1,58 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
"
|
|
2
|
+
"name": "@harness-sdk/harnessd",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Keeps Claude Code running on your Mac or Linux machine, day and night, connected to the events of your agentic apps",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"claude-code",
|
|
7
|
+
"agent",
|
|
8
|
+
"daemon",
|
|
9
|
+
"launchd",
|
|
10
|
+
"systemd",
|
|
11
|
+
"mcp",
|
|
12
|
+
"channels"
|
|
13
|
+
],
|
|
14
|
+
"author": "AgentbaseAI Inc.",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"bin": {
|
|
18
|
+
"harnessd": "./dist/bin.js"
|
|
7
19
|
},
|
|
8
|
-
"
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20.19.0"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"src",
|
|
26
|
+
"!src/**/*.test.ts",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "node scripts/build-deps.mjs && aui-build",
|
|
33
|
+
"typecheck": "tsc --noEmit",
|
|
34
|
+
"test": "vitest run"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@xterm/headless": "6.0.0",
|
|
38
|
+
"@lydell/node-pty": "1.1.0",
|
|
39
|
+
"toolport": "^0.2.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@assistant-ui/tap": "^0.9.24",
|
|
43
|
+
"@assistant-ui/x-buildutils": "^0.0.31",
|
|
44
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
45
|
+
"@types/node": "^26.6.5",
|
|
46
|
+
"statewire": "^0.33.0",
|
|
47
|
+
"typescript": "^7.0.2",
|
|
48
|
+
"vitest": "^5.0.5"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "git+https://github.com/assistant-ui/harness-sdk.git",
|
|
56
|
+
"directory": "packages/harnessd/harnessd"
|
|
57
|
+
}
|
|
9
58
|
}
|
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
export namespace Accounts {
|
|
4
|
+
/** Why Claude Code can't go on with the account it runs on. */
|
|
5
|
+
export type Stop = {
|
|
6
|
+
readonly why: "its usage limit" | "a failed sign-in";
|
|
7
|
+
/** When the account is worth another try (epoch ms). */
|
|
8
|
+
readonly until: number;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** An account harnessd passes over, for now. */
|
|
12
|
+
export type Mark = Stop & {
|
|
13
|
+
/** The account's environment when it stopped: a changed one (a new token) is tried again. */
|
|
14
|
+
readonly env: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type Options = {
|
|
18
|
+
/** The config's accounts, in its order. */
|
|
19
|
+
readonly accounts: () => Readonly<
|
|
20
|
+
Record<string, Readonly<Record<string, string>>>
|
|
21
|
+
>;
|
|
22
|
+
readonly now?: () => number;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type Rotation = {
|
|
26
|
+
/** The account the next start runs on: `current` while it can go on, else the first that can. All stopped: `current`. */
|
|
27
|
+
readonly pick: (current: string | undefined) => string | undefined;
|
|
28
|
+
readonly mark: (name: string, stop: Stop) => void;
|
|
29
|
+
/** The accounts passed over now. */
|
|
30
|
+
readonly marks: () => Readonly<Record<string, Stop>>;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const LIMIT_MS = 5 * 60 * 60_000;
|
|
35
|
+
const SIGN_IN_MS = 24 * 60 * 60_000;
|
|
36
|
+
|
|
37
|
+
/** Whether a line of Claude Code's transcript says the account can't go on: a usage limit, or a sign-in the API refused. */
|
|
38
|
+
export const accountStop = (
|
|
39
|
+
entry: unknown,
|
|
40
|
+
now = Date.now(),
|
|
41
|
+
): Accounts.Stop | undefined => {
|
|
42
|
+
if (typeof entry !== "object" || entry === null) return undefined;
|
|
43
|
+
const e = entry as {
|
|
44
|
+
type?: unknown;
|
|
45
|
+
isApiErrorMessage?: unknown;
|
|
46
|
+
error?: unknown;
|
|
47
|
+
apiErrorStatus?: unknown;
|
|
48
|
+
apiErrorIsTransient?: unknown;
|
|
49
|
+
quotaLimits?: { resetsAt?: unknown };
|
|
50
|
+
};
|
|
51
|
+
if (e.type !== "assistant" || e.isApiErrorMessage !== true) return undefined;
|
|
52
|
+
if (e.error === "authentication_failed")
|
|
53
|
+
return { why: "a failed sign-in", until: now + SIGN_IN_MS };
|
|
54
|
+
if (
|
|
55
|
+
e.error !== "rate_limit" ||
|
|
56
|
+
e.apiErrorStatus !== 429 ||
|
|
57
|
+
e.apiErrorIsTransient === true
|
|
58
|
+
)
|
|
59
|
+
return undefined;
|
|
60
|
+
const resetsAt = e.quotaLimits?.resetsAt;
|
|
61
|
+
return {
|
|
62
|
+
why: "its usage limit",
|
|
63
|
+
until:
|
|
64
|
+
typeof resetsAt === "number" && resetsAt * 1000 > now
|
|
65
|
+
? resetsAt * 1000
|
|
66
|
+
: now + LIMIT_MS,
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Which of the config's accounts Claude Code runs on, and which it passes over until they can go on again. */
|
|
71
|
+
export const rotation = (options: Accounts.Options): Accounts.Rotation => {
|
|
72
|
+
const now = options.now ?? Date.now;
|
|
73
|
+
const marked = new Map<string, Accounts.Mark>();
|
|
74
|
+
const stopped = (name: string, env: Readonly<Record<string, string>>) => {
|
|
75
|
+
const mark = marked.get(name);
|
|
76
|
+
if (!mark) return false;
|
|
77
|
+
if (mark.until > now() && mark.env === JSON.stringify(env)) return true;
|
|
78
|
+
marked.delete(name);
|
|
79
|
+
return false;
|
|
80
|
+
};
|
|
81
|
+
const open = () =>
|
|
82
|
+
Object.entries(options.accounts())
|
|
83
|
+
.filter(([name, env]) => !stopped(name, env))
|
|
84
|
+
.map(([name]) => name);
|
|
85
|
+
return {
|
|
86
|
+
pick: (current) => {
|
|
87
|
+
const accounts = options.accounts();
|
|
88
|
+
const names = Object.keys(accounts);
|
|
89
|
+
const free = open();
|
|
90
|
+
if (current !== undefined && free.includes(current)) return current;
|
|
91
|
+
return (
|
|
92
|
+
free[0] ??
|
|
93
|
+
(current !== undefined && current in accounts ? current : names[0])
|
|
94
|
+
);
|
|
95
|
+
},
|
|
96
|
+
mark: (name, stop) => {
|
|
97
|
+
const env = options.accounts()[name];
|
|
98
|
+
if (env) marked.set(name, { ...stop, env: JSON.stringify(env) });
|
|
99
|
+
},
|
|
100
|
+
marks: () => {
|
|
101
|
+
const accounts = options.accounts();
|
|
102
|
+
for (const name of marked.keys())
|
|
103
|
+
if (!(name in accounts)) marked.delete(name);
|
|
104
|
+
const free = new Set(open());
|
|
105
|
+
return Object.fromEntries(
|
|
106
|
+
[...marked]
|
|
107
|
+
.filter(([name]) => !free.has(name))
|
|
108
|
+
.map(([name, { why, until }]) => [name, { why, until }]),
|
|
109
|
+
);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Calls `onEntry` with each line the conversation's transcript gains from now on; `file` says where it is once Claude
|
|
116
|
+
* Code has written it. When Claude Code moves to another conversation, its transcript is followed from then on.
|
|
117
|
+
*/
|
|
118
|
+
export const followTranscript = (o: {
|
|
119
|
+
sessionId: () => string;
|
|
120
|
+
file: (sessionId: string) => string | undefined;
|
|
121
|
+
onEntry: (entry: unknown) => void;
|
|
122
|
+
/** After each look at the transcript, whether it gained lines or not. */
|
|
123
|
+
onRead?: () => void;
|
|
124
|
+
everyMs?: number;
|
|
125
|
+
}) => {
|
|
126
|
+
let sessionId: string | undefined;
|
|
127
|
+
let path: string | undefined;
|
|
128
|
+
let offset: number | undefined;
|
|
129
|
+
let rest = "";
|
|
130
|
+
const read = () => {
|
|
131
|
+
if (o.sessionId() !== sessionId) {
|
|
132
|
+
sessionId = o.sessionId();
|
|
133
|
+
path = undefined;
|
|
134
|
+
offset = undefined;
|
|
135
|
+
rest = "";
|
|
136
|
+
}
|
|
137
|
+
path ??= o.file(sessionId);
|
|
138
|
+
if (path === undefined) {
|
|
139
|
+
// a transcript that appears after the start, or after a move to another conversation, is read from its first line
|
|
140
|
+
offset = 0;
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
let fd: number;
|
|
144
|
+
try {
|
|
145
|
+
fd = openSync(path, "r");
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const { size } = fstatSync(fd);
|
|
151
|
+
offset ??= size;
|
|
152
|
+
if (size <= offset) return;
|
|
153
|
+
const chunk = Buffer.alloc(size - offset);
|
|
154
|
+
readSync(fd, chunk, 0, chunk.length, offset);
|
|
155
|
+
offset = size;
|
|
156
|
+
const lines = (rest + chunk.toString("utf8")).split("\n");
|
|
157
|
+
rest = lines.pop() ?? "";
|
|
158
|
+
for (const line of lines) {
|
|
159
|
+
if (!line.trim()) continue;
|
|
160
|
+
let entry: unknown;
|
|
161
|
+
try {
|
|
162
|
+
entry = JSON.parse(line);
|
|
163
|
+
} catch {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
o.onEntry(entry);
|
|
167
|
+
}
|
|
168
|
+
} finally {
|
|
169
|
+
closeSync(fd);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const look = () => {
|
|
173
|
+
read();
|
|
174
|
+
o.onRead?.();
|
|
175
|
+
};
|
|
176
|
+
look();
|
|
177
|
+
const timer = setInterval(look, o.everyMs ?? 10_000);
|
|
178
|
+
return {
|
|
179
|
+
/** Reads what the transcript gained since the last look, then stops looking. */
|
|
180
|
+
finish: () => {
|
|
181
|
+
clearInterval(timer);
|
|
182
|
+
read();
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* One start of Claude Code on `account`, watched from before the start to after the exit: when the account stops and
|
|
189
|
+
* another can go on, Claude Code hands over to it in the same conversation.
|
|
190
|
+
*/
|
|
191
|
+
export const accountRun = (o: {
|
|
192
|
+
account: string;
|
|
193
|
+
rotation: Accounts.Rotation;
|
|
194
|
+
/** The conversation Claude Code is in. */
|
|
195
|
+
sessionId: () => string;
|
|
196
|
+
/** Where a conversation's transcript is, once Claude Code has written it. */
|
|
197
|
+
file: (sessionId: string) => string | undefined;
|
|
198
|
+
/** Restarts the start with this pid, telling the conversation why. */
|
|
199
|
+
restart: (reason: string, pid: number) => void;
|
|
200
|
+
log: (line: string) => void;
|
|
201
|
+
everyMs?: number;
|
|
202
|
+
}) => {
|
|
203
|
+
let pid: number | undefined;
|
|
204
|
+
let handed = false;
|
|
205
|
+
const handover = () => {
|
|
206
|
+
const why = o.rotation.marks()[o.account]?.why;
|
|
207
|
+
const next = o.rotation.pick(o.account);
|
|
208
|
+
if (handed || !why || next === undefined || next === o.account)
|
|
209
|
+
return undefined;
|
|
210
|
+
handed = true;
|
|
211
|
+
o.log(`switching from account ${o.account} to ${next}`);
|
|
212
|
+
return `account ${o.account} stopped at ${why}, so Claude Code now runs on account ${next}`;
|
|
213
|
+
};
|
|
214
|
+
const follow = followTranscript({
|
|
215
|
+
sessionId: o.sessionId,
|
|
216
|
+
file: o.file,
|
|
217
|
+
onEntry: (entry) => {
|
|
218
|
+
const stop = accountStop(entry);
|
|
219
|
+
if (!stop) return;
|
|
220
|
+
if (!(o.account in o.rotation.marks()))
|
|
221
|
+
o.log(`account ${o.account} stopped at ${stop.why}`);
|
|
222
|
+
o.rotation.mark(o.account, stop);
|
|
223
|
+
},
|
|
224
|
+
// after each look: a stopped account hands over as soon as another can go on, now or once that one's limit resets
|
|
225
|
+
onRead: () => {
|
|
226
|
+
if (pid === undefined) return;
|
|
227
|
+
const reason = handover();
|
|
228
|
+
if (reason !== undefined) o.restart(reason, pid);
|
|
229
|
+
},
|
|
230
|
+
...(o.everyMs !== undefined && { everyMs: o.everyMs }),
|
|
231
|
+
});
|
|
232
|
+
return {
|
|
233
|
+
/** Claude Code runs. */
|
|
234
|
+
started: (startedPid: number) => void (pid = startedPid),
|
|
235
|
+
/** Claude Code exited, or never started: reads the transcript's last lines. A reason: the next start goes on with another account, and is told this. */
|
|
236
|
+
exited: () => {
|
|
237
|
+
pid = undefined;
|
|
238
|
+
follow.finish();
|
|
239
|
+
return handover();
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
};
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { runHarnessd } from "./cli";
|
|
4
|
+
|
|
5
|
+
// stdout belongs to the command (for `harnessd channel`, to Claude Code)
|
|
6
|
+
console.log = console.error.bind(console);
|
|
7
|
+
console.info = console.error.bind(console);
|
|
8
|
+
console.debug = console.error.bind(console);
|
|
9
|
+
|
|
10
|
+
// a reader that closes early (harnessd status | head) ends the command quietly
|
|
11
|
+
process.stdout.on("error", (error: NodeJS.ErrnoException) => {
|
|
12
|
+
if (error.code !== "EPIPE") throw error;
|
|
13
|
+
process.exit(0);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
process.exitCode = await runHarnessd(
|
|
18
|
+
process.argv.slice(2),
|
|
19
|
+
realpathSync(process.argv[1]!),
|
|
20
|
+
);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
23
|
+
process.exitCode = 1;
|
|
24
|
+
}
|