@harness-sdk/harnessd 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +15 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/channel.d.ts +56 -0
  8. package/dist/channel.d.ts.map +1 -0
  9. package/dist/channel.js +356 -0
  10. package/dist/channel.js.map +1 -0
  11. package/dist/claude.d.ts +42 -0
  12. package/dist/claude.d.ts.map +1 -0
  13. package/dist/claude.js +166 -0
  14. package/dist/claude.js.map +1 -0
  15. package/dist/cli.d.ts +8 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +258 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config.d.ts +43 -0
  20. package/dist/config.d.ts.map +1 -0
  21. package/dist/config.js +121 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/daemon.d.ts +24 -0
  24. package/dist/daemon.d.ts.map +1 -0
  25. package/dist/daemon.js +239 -0
  26. package/dist/daemon.js.map +1 -0
  27. package/dist/launchd.d.ts +22 -0
  28. package/dist/launchd.d.ts.map +1 -0
  29. package/dist/launchd.js +88 -0
  30. package/dist/launchd.js.map +1 -0
  31. package/dist/log.d.ts +3 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +17 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/terminal.d.ts +11 -0
  36. package/dist/terminal.d.ts.map +1 -0
  37. package/dist/terminal.js +36 -0
  38. package/dist/terminal.js.map +1 -0
  39. package/dist/watchdog.d.ts +73 -0
  40. package/dist/watchdog.d.ts.map +1 -0
  41. package/dist/watchdog.js +230 -0
  42. package/dist/watchdog.js.map +1 -0
  43. package/package.json +53 -6
  44. package/src/bin.ts +18 -0
  45. package/src/channel.ts +461 -0
  46. package/src/claude.ts +274 -0
  47. package/src/cli.ts +372 -0
  48. package/src/config.ts +203 -0
  49. package/src/daemon.ts +312 -0
  50. package/src/launchd.ts +126 -0
  51. package/src/log.ts +17 -0
  52. package/src/terminal.ts +33 -0
  53. package/src/watchdog.ts +310 -0
@@ -0,0 +1,310 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export namespace Watchdog {
4
+ /** What harnessd keeps across its own restarts. */
5
+ export type State = {
6
+ /** The conversation the next start resumes. */
7
+ readonly sessionId?: string;
8
+ /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */
9
+ readonly stopped?: boolean;
10
+ };
11
+
12
+ /** One start of Claude Code: a new conversation with this id, or a resume of it. */
13
+ export type Start = {
14
+ readonly sessionId: string;
15
+ readonly resume: boolean;
16
+ /** The first message: the one `harnessd new` gave, or why a resumed conversation restarted. */
17
+ readonly prompt?: string;
18
+ };
19
+
20
+ export type Run = {
21
+ readonly pid?: number;
22
+ /** Resolves with the exit code (128 + signal for a signal). */
23
+ readonly exited: Promise<number>;
24
+ readonly kill: (signal: NodeJS.Signals) => void;
25
+ };
26
+
27
+ export type Timing = {
28
+ readonly minBackoffMs: number;
29
+ readonly maxBackoffMs: number;
30
+ /** A run this long resets the backoff. */
31
+ readonly healthyMs: number;
32
+ /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */
33
+ readonly resumeFailedMs: number;
34
+ /** Alive this long: running. */
35
+ readonly runningAfterMs: number;
36
+ /** How long a stop waits after SIGTERM before SIGKILL. */
37
+ readonly killAfterMs: number;
38
+ };
39
+
40
+ export type Options = {
41
+ /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */
42
+ readonly launch: (start: Start) => Promise<Run>;
43
+ readonly state: { read(): State; write(state: State): void };
44
+ /** Whether Claude Code still has this conversation's transcript. */
45
+ readonly hasTranscript: (sessionId: string) => boolean;
46
+ readonly log: (line: string) => void;
47
+ readonly timing?: Partial<Timing>;
48
+ readonly now?: () => number;
49
+ readonly newId?: () => string;
50
+ };
51
+
52
+ export type Status = {
53
+ readonly state: "starting" | "running" | "waiting" | "stopped";
54
+ readonly pid?: number | undefined;
55
+ readonly sessionId?: string | undefined;
56
+ readonly startedAt?: string | undefined;
57
+ readonly restarts: number;
58
+ readonly lastExit?:
59
+ | { readonly code: number; readonly at: string }
60
+ | undefined;
61
+ readonly nextStartAt?: string | undefined;
62
+ };
63
+
64
+ export type Watchdog = {
65
+ /** Runs until `shutdown`. */
66
+ readonly run: () => Promise<void>;
67
+ readonly status: () => Status;
68
+ readonly stop: () => Promise<string>;
69
+ readonly start: () => Promise<string>;
70
+ /** Starts a new conversation, with `message` as its first message. */
71
+ readonly fresh: (message?: string) => Promise<string>;
72
+ /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */
73
+ readonly shutdown: () => Promise<void>;
74
+ };
75
+ }
76
+
77
+ const DEFAULT_TIMING: Watchdog.Timing = {
78
+ minBackoffMs: 5_000,
79
+ maxBackoffMs: 5 * 60_000,
80
+ healthyMs: 10 * 60_000,
81
+ resumeFailedMs: 30_000,
82
+ runningAfterMs: 3_000,
83
+ killAfterMs: 10_000,
84
+ };
85
+
86
+ const SPAWN_WAIT_MS = 30_000;
87
+
88
+ export const watchdog = (options: Watchdog.Options): Watchdog.Watchdog => {
89
+ const timing = { ...DEFAULT_TIMING, ...options.timing };
90
+ const now = options.now ?? Date.now;
91
+ const newId = options.newId ?? randomUUID;
92
+ const iso = (ms: number) => new Date(ms).toISOString();
93
+
94
+ let status: Watchdog.Status = { state: "starting", restarts: 0 };
95
+ let current: Watchdog.Run | undefined;
96
+ // a start in progress (its prestart can take a minute): commands wait for it, then act on what it started
97
+ let launching: Promise<unknown> = Promise.resolve();
98
+ let shuttingDown = false;
99
+ let restartNow = false;
100
+ let fresh = false;
101
+ let firstMessage: string | undefined;
102
+ let reason = "harnessd started (a login, a reboot or an update)";
103
+ let wakeUp = () => {};
104
+ let finished: Promise<void> | undefined;
105
+ const spawnWaiters = new Set<() => void>();
106
+ let queue: Promise<unknown> = Promise.resolve();
107
+
108
+ const set = (patch: Partial<Watchdog.Status>) => {
109
+ status = { ...status, ...patch };
110
+ };
111
+ const sleep = (ms: number) =>
112
+ new Promise<void>((resolve) => {
113
+ const timer = setTimeout(done, ms);
114
+ function done() {
115
+ clearTimeout(timer);
116
+ resolve();
117
+ }
118
+ wakeUp = done;
119
+ });
120
+ const nextSpawn = () =>
121
+ new Promise<boolean>((resolve) => {
122
+ const done = () => {
123
+ clearTimeout(timer);
124
+ resolve(true);
125
+ };
126
+ const timer = setTimeout(() => {
127
+ spawnWaiters.delete(done);
128
+ resolve(false);
129
+ }, timing.killAfterMs + SPAWN_WAIT_MS);
130
+ spawnWaiters.add(done);
131
+ });
132
+ const kill = async (run: Watchdog.Run) => {
133
+ run.kill("SIGTERM");
134
+ let timer: ReturnType<typeof setTimeout> | undefined;
135
+ const exited = await Promise.race([
136
+ run.exited.then(() => true),
137
+ new Promise<false>(
138
+ (resolve) =>
139
+ (timer = setTimeout(() => resolve(false), timing.killAfterMs)),
140
+ ),
141
+ ]);
142
+ clearTimeout(timer);
143
+ if (exited) return;
144
+ options.log("Claude Code didn't exit after SIGTERM; sending SIGKILL");
145
+ run.kill("SIGKILL");
146
+ await run.exited;
147
+ };
148
+
149
+ const next = (): Watchdog.Start => {
150
+ const { sessionId } = options.state.read();
151
+ if (!fresh && sessionId && options.hasTranscript(sessionId))
152
+ return {
153
+ sessionId,
154
+ resume: true,
155
+ prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`,
156
+ };
157
+ // a new conversation asked for stays asked for, with its first message, until a start of it succeeds
158
+ return {
159
+ sessionId: newId(),
160
+ resume: false,
161
+ ...(firstMessage !== undefined && { prompt: firstMessage }),
162
+ };
163
+ };
164
+
165
+ const loop = async () => {
166
+ let backoff = timing.minBackoffMs;
167
+ let runs = 0;
168
+ while (!shuttingDown) {
169
+ if (options.state.read().stopped) {
170
+ set({ state: "stopped", nextStartAt: undefined });
171
+ await sleep(2 ** 31 - 1);
172
+ continue;
173
+ }
174
+ const start = next();
175
+ options.state.write({
176
+ ...options.state.read(),
177
+ sessionId: start.sessionId,
178
+ });
179
+ if (runs++ > 0) set({ restarts: status.restarts + 1 });
180
+ const startedAt = now();
181
+ set({
182
+ state: "starting",
183
+ sessionId: start.sessionId,
184
+ startedAt: iso(startedAt),
185
+ nextStartAt: undefined,
186
+ });
187
+ options.log(
188
+ `starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`,
189
+ );
190
+ let run: Watchdog.Run | undefined;
191
+ try {
192
+ const launch = options
193
+ .launch(start)
194
+ .then((started) => (current = started));
195
+ launching = launch.catch(() => {});
196
+ run = await launch;
197
+ } catch (error) {
198
+ options.log(
199
+ `couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`,
200
+ );
201
+ reason = "the start before this one failed";
202
+ }
203
+ if (run) {
204
+ if (!start.resume) {
205
+ fresh = false;
206
+ firstMessage = undefined;
207
+ }
208
+ const spawnedAt = now();
209
+ set({ pid: run.pid });
210
+ for (const waiter of spawnWaiters) waiter();
211
+ spawnWaiters.clear();
212
+ const running = setTimeout(
213
+ () => current === run && set({ state: "running" }),
214
+ timing.runningAfterMs,
215
+ );
216
+ const code = await run.exited;
217
+ clearTimeout(running);
218
+ current = undefined;
219
+ const ran = now() - spawnedAt;
220
+ set({ pid: undefined, lastExit: { code, at: iso(now()) } });
221
+ options.log(
222
+ `Claude Code exited with code ${code} after ${Math.round(ran / 1000)}s`,
223
+ );
224
+ if (shuttingDown) break;
225
+ if (restartNow) {
226
+ restartNow = false;
227
+ backoff = timing.minBackoffMs;
228
+ continue;
229
+ }
230
+ if (options.state.read().stopped) continue;
231
+ if (start.resume && ran < timing.resumeFailedMs) {
232
+ fresh = true;
233
+ reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;
234
+ options.log(`${reason}; the next start is a new conversation`);
235
+ } else
236
+ reason = `it exited with code ${code} after ${Math.round(ran / 1000)}s`;
237
+ if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;
238
+ }
239
+ if (shuttingDown) break;
240
+ set({ state: "waiting", nextStartAt: iso(now() + backoff) });
241
+ options.log(`starting again in ${Math.round(backoff / 1000)}s`);
242
+ await sleep(backoff);
243
+ backoff = Math.min(backoff * 2, timing.maxBackoffMs);
244
+ }
245
+ set({ state: "stopped", nextStartAt: undefined });
246
+ };
247
+
248
+ const serial = (command: () => Promise<string>) => {
249
+ const result = queue.catch(() => {}).then(command);
250
+ queue = result;
251
+ return result;
252
+ };
253
+
254
+ return {
255
+ run: () => (finished ??= loop()),
256
+ status: () => status,
257
+ stop: () =>
258
+ serial(async () => {
259
+ await launching;
260
+ const stopped = options.state.read().stopped;
261
+ options.state.write({ ...options.state.read(), stopped: true });
262
+ const run = current;
263
+ if (run) await kill(run);
264
+ wakeUp();
265
+ options.log("stopped with harnessd stop");
266
+ return run
267
+ ? "Stopped Claude Code."
268
+ : stopped
269
+ ? "Claude Code was already stopped."
270
+ : "Stopped (Claude Code was waiting to start).";
271
+ }),
272
+ start: () =>
273
+ serial(async () => {
274
+ await launching;
275
+ if (current) return "Claude Code is already running.";
276
+ options.state.write({ ...options.state.read(), stopped: false });
277
+ reason = "started with harnessd start";
278
+ const spawned = nextSpawn();
279
+ wakeUp();
280
+ return (await spawned)
281
+ ? "Started Claude Code."
282
+ : "Claude Code didn't start in time; see harnessd logs.";
283
+ }),
284
+ fresh: (message) =>
285
+ serial(async () => {
286
+ await launching;
287
+ options.state.write({ ...options.state.read(), stopped: false });
288
+ fresh = true;
289
+ firstMessage = message;
290
+ reason = "a new conversation was asked for";
291
+ const spawned = nextSpawn();
292
+ const run = current;
293
+ if (run) {
294
+ restartNow = true;
295
+ await kill(run);
296
+ } else wakeUp();
297
+ return (await spawned)
298
+ ? `Started a new conversation (${status.sessionId}).`
299
+ : "Claude Code didn't start in time; see harnessd logs.";
300
+ }),
301
+ shutdown: async () => {
302
+ shuttingDown = true;
303
+ wakeUp();
304
+ await launching;
305
+ const run = current;
306
+ if (run) await kill(run);
307
+ await finished;
308
+ },
309
+ };
310
+ };