@harness-sdk/harnessd 0.0.2 → 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/src/daemon.ts CHANGED
@@ -7,12 +7,13 @@ import {
7
7
  writeFileSync,
8
8
  } from "node:fs";
9
9
  import { createConnection, createServer, type Socket } from "node:net";
10
- import { dirname } from "node:path";
10
+ import { delimiter, dirname } from "node:path";
11
11
  import { createInterface } from "node:readline";
12
12
  import type { IPty } from "@lydell/node-pty";
13
13
  import { accountRun, rotation } from "./accounts";
14
14
  import {
15
15
  claudeArgs,
16
+ claudeVersion,
16
17
  skipsPermissions,
17
18
  findTranscript,
18
19
  prestart,
@@ -32,6 +33,8 @@ export namespace Daemon {
32
33
  | { readonly command: "status" | "stop" | "start" }
33
34
  /** From Claude Code's SessionStart hook: the conversation it is in now. */
34
35
  | { readonly command: "session-start"; readonly sessionId: string }
36
+ /** From Claude Code's Notification hook: it waits for input, with nothing running. */
37
+ | { readonly command: "idle" }
35
38
  | {
36
39
  readonly command: "attach";
37
40
  readonly cols: number;
@@ -51,6 +54,14 @@ export namespace Daemon {
51
54
  readonly waitingOn?: string;
52
55
  /** Claude Code said managed settings keep channels out: it drops their events. */
53
56
  readonly channelsRefused?: true;
57
+ /** The version of the Claude Code that runs, or ran last. */
58
+ readonly claudeVersion?: string;
59
+ /** A newer Claude Code than the one that runs (no `at`: it starts once the agent is idle), or the last restart into one. */
60
+ readonly update?: {
61
+ readonly from: string;
62
+ readonly to: string;
63
+ readonly at?: string;
64
+ };
54
65
  };
55
66
  }
56
67
 
@@ -60,6 +71,8 @@ const OWN_ENV =
60
71
 
61
72
  const VIEWER_BUFFER = 8 * 1024 * 1024;
62
73
 
74
+ const UPDATE_CHECK_MS = 60 * 60_000;
75
+
63
76
  const SESSION_ID =
64
77
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
65
78
 
@@ -150,6 +163,18 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
150
163
  return process.env;
151
164
  }
152
165
  };
166
+ // the Claude Code that runs: how to ask the installed one its version, and which version this one is
167
+ let claude:
168
+ | {
169
+ pid: number;
170
+ file: string;
171
+ env: NodeJS.ProcessEnv;
172
+ version: string | undefined;
173
+ }
174
+ | undefined;
175
+ // when Claude Code last said it waits for input with nothing running
176
+ let idleAt: number | undefined;
177
+ let update: Daemon.Status["update"];
153
178
  let accounts: Harnessd.Config["accounts"] = {};
154
179
  let account: string | undefined;
155
180
  const rota = rotation({
@@ -200,8 +225,16 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
200
225
  let handover: string | undefined;
201
226
  let p: IPty;
202
227
  let args: string[];
228
+ let file: string;
229
+ let version: string | undefined;
230
+ // the servers' commands, ahead of any other command of the same name; after claude is found
231
+ const spawnEnv = {
232
+ ...env,
233
+ PATH: [paths.bin, ...(env.PATH ? [env.PATH] : [])].join(delimiter),
234
+ };
203
235
  try {
204
- const file = which("claude", env.PATH);
236
+ file = which("claude", env.PATH);
237
+ version = await claudeVersion(file, spawnEnv);
205
238
  const { spawn } = await import("@lydell/node-pty");
206
239
  args = claudeArgs({
207
240
  start,
@@ -214,7 +247,7 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
214
247
  cols: size.cols,
215
248
  rows: size.rows,
216
249
  cwd: config.folder,
217
- env,
250
+ env: spawnEnv,
218
251
  });
219
252
  } catch (error) {
220
253
  onAccount?.exited();
@@ -222,6 +255,10 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
222
255
  }
223
256
  onAccount?.started(p.pid);
224
257
  pty = p;
258
+ claude = { pid: p.pid, file, env: spawnEnv, version };
259
+ idleAt = undefined;
260
+ if (update && !update.at && version === update.to)
261
+ update = { ...update, at: new Date().toISOString() };
225
262
  prompts.reset({ skipsPermissions: skipsPermissions(args) });
226
263
  show(
227
264
  `\r\n\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\x1b[0m\r\n`,
@@ -269,6 +306,44 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
269
306
  log,
270
307
  });
271
308
 
309
+ const idle = () => {
310
+ if (idleAt === undefined || prompts.waitingOn()) return false;
311
+ // a line written since: a turn ran after Claude Code said it was idle
312
+ const sessionId = dog.status().sessionId;
313
+ const file = sessionId && findTranscript(sessionId, transcriptEnv());
314
+ try {
315
+ return !file || statSync(file).mtimeMs <= idleAt;
316
+ } catch {
317
+ return true;
318
+ }
319
+ };
320
+
321
+ // Claude Code's own updater installs a new version, which the one that runs only uses from its next start
322
+ const checkUpdate = async () => {
323
+ const run = claude;
324
+ if (run?.version === undefined) return;
325
+ const installed = await claudeVersion(run.file, run.env);
326
+ if (run !== claude) return;
327
+ if (installed === undefined || installed === run.version) {
328
+ if (update && !update.at) update = undefined;
329
+ return;
330
+ }
331
+ const found = update?.to !== installed || update.at !== undefined;
332
+ if (found) update = { from: run.version, to: installed };
333
+ if (!idle()) {
334
+ if (found)
335
+ log(
336
+ `Claude Code ${installed} is installed; harnessd restarts into it once the agent is idle`,
337
+ );
338
+ return;
339
+ }
340
+ log(`restarting Claude Code ${run.version} into ${installed}`);
341
+ await dog.restart(
342
+ `it was updated from ${run.version} to ${installed}`,
343
+ run.pid,
344
+ );
345
+ };
346
+
272
347
  const status = (): Daemon.Status => {
273
348
  const waitingOn = prompts.waitingOn();
274
349
  const stops = rota.marks();
@@ -278,6 +353,8 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
278
353
  ...(folder && { folder }),
279
354
  ...(waitingOn && { waitingOn }),
280
355
  ...(prompts.channelsRefused() && { channelsRefused: true as const }),
356
+ ...(claude?.version !== undefined && { claudeVersion: claude.version }),
357
+ ...(update && { update }),
281
358
  ...(account !== undefined && { account }),
282
359
  ...(Object.keys(stops).length > 0 && {
283
360
  accountsStopped: Object.fromEntries(
@@ -332,6 +409,11 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
332
409
  dog.follow(request.sessionId);
333
410
  return void reply({ ok: true });
334
411
  }
412
+ if (request.command === "idle") {
413
+ idleAt = Date.now();
414
+ reply({ ok: true });
415
+ return void checkUpdate();
416
+ }
335
417
  if (request.command === "attach") {
336
418
  attached = true;
337
419
  viewers.add(connection);
@@ -359,6 +441,7 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
359
441
  server.listen(paths.socket, resolve);
360
442
  });
361
443
  log(`harnessd ${process.pid} started`);
444
+ setInterval(() => void checkUpdate(), UPDATE_CHECK_MS);
362
445
 
363
446
  let stopping = false;
364
447
  const shutdown = async (signal: string) => {