@cloop/runner 0.3.29 → 0.3.31

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 (29) hide show
  1. package/README.md +7 -0
  2. package/dist/{box-6TJMXQXM.js → box-RFAHCXZS.js} +239 -69
  3. package/dist/chunk-52CUSFDQ.js +401 -0
  4. package/dist/{chunk-P56EL4D4.js → chunk-7AHYPGSU.js} +2 -2
  5. package/dist/{chunk-65KJPIZC.js → chunk-FKYVJUIR.js} +1 -1
  6. package/dist/{chunk-4FXRG3Q3.js → chunk-GL77IQQE.js} +1 -1
  7. package/dist/{chunk-SVHQXVCH.js → chunk-MEAVT5SJ.js} +986 -205
  8. package/dist/{chunk-AIOOLVM7.js → chunk-R73PVAM2.js} +182 -88
  9. package/dist/{chunk-NTXQLEMQ.js → chunk-SBYSVZ7J.js} +94 -2
  10. package/dist/{chunk-PSA5EC65.js → chunk-UERK5AHI.js} +6 -6
  11. package/dist/{chunk-TWDKR7XV.js → chunk-WYU74GLG.js} +5 -5
  12. package/dist/{chunk-GURADB5L.js → chunk-YLVOEZWH.js} +1 -1
  13. package/dist/{connect-HVUNZ6A2.js → connect-WRTLQW5H.js} +10 -9
  14. package/dist/{disconnect-NXVDABS5.js → disconnect-I44BWWFB.js} +8 -9
  15. package/dist/existing-runner-SP6SNFH4.js +20 -0
  16. package/dist/{hook-activity-GAJ5NABA.js → hook-activity-3T6IMEM6.js} +2 -3
  17. package/dist/{hook-session-start-5JYNMGX4.js → hook-session-start-DLP77G4H.js} +5 -7
  18. package/dist/index.js +20 -17
  19. package/dist/{login-PH2RZNOE.js → login-LH2KF7N2.js} +3 -3
  20. package/dist/{mcp-server-U2H4U4BZ.js → mcp-server-SGIWNLLL.js} +9 -11
  21. package/dist/{runner-YTGTJPPR.js → runner-SXUQH5IU.js} +4 -4
  22. package/dist/{runs-D7XT2PYS.js → runs-3YZO57MX.js} +2 -2
  23. package/dist/{statusline-U4K2IQIT.js → statusline-UHZTCNCB.js} +1 -1
  24. package/dist/{takeover-M2SDWTVK.js → takeover-M4QHMXTZ.js} +5 -6
  25. package/dist/{use-7OUFEREN.js → use-YB75NHTE.js} +8 -9
  26. package/package.json +1 -1
  27. package/dist/chunk-ES5BRAKJ.js +0 -88
  28. package/dist/chunk-KYGYU5G2.js +0 -220
  29. package/dist/existing-runner-7E6RUUJH.js +0 -21
@@ -1,16 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- freshness
4
- } from "./chunk-KYGYU5G2.js";
3
+ callOutcome,
4
+ freshness,
5
+ outcomeLine,
6
+ runnerLog
7
+ } from "./chunk-52CUSFDQ.js";
5
8
  import {
6
9
  readRunnerState,
7
10
  runnerStatePath,
8
11
  threadsFilePath
9
- } from "./chunk-GURADB5L.js";
12
+ } from "./chunk-YLVOEZWH.js";
10
13
  import {
11
14
  BoxToolError,
12
15
  CLOOP_THREAD_PREFIX,
13
16
  ENVIRONMENTS,
17
+ HARNESS_SIGNED_OUT,
14
18
  IMAGE_TYPES,
15
19
  MIN_PROTOCOL,
16
20
  RUNTIME_MODES,
@@ -34,6 +38,7 @@ import {
34
38
  quoteWindowsArg,
35
39
  readEnvironment,
36
40
  readRunnerConfig,
41
+ redactSecrets,
37
42
  runT3,
38
43
  runnerDir,
39
44
  runnerEnvironment,
@@ -43,11 +48,7 @@ import {
43
48
  windowsExecutable,
44
49
  windowsPowerShellEnv,
45
50
  writeBoxConfig
46
- } from "./chunk-AIOOLVM7.js";
47
- import {
48
- getMachine,
49
- shortMachineName
50
- } from "./chunk-NTXQLEMQ.js";
51
+ } from "./chunk-R73PVAM2.js";
51
52
  import {
52
53
  CLAUDE_FLOOR,
53
54
  CODEX_FLOOR,
@@ -61,17 +62,22 @@ import {
61
62
  } from "./chunk-PKIEWBR7.js";
62
63
  import {
63
64
  connectWebhook
64
- } from "./chunk-P56EL4D4.js";
65
+ } from "./chunk-7AHYPGSU.js";
65
66
  import {
66
67
  ConnectFailure,
67
68
  connectReport,
68
69
  deviceLogin,
69
70
  newAttempt,
70
71
  sendConnectReport
71
- } from "./chunk-TWDKR7XV.js";
72
+ } from "./chunk-WYU74GLG.js";
73
+ import {
74
+ defaultDeviceName,
75
+ getMachine,
76
+ shortMachineName
77
+ } from "./chunk-SBYSVZ7J.js";
72
78
  import {
73
79
  VERSION
74
- } from "./chunk-4FXRG3Q3.js";
80
+ } from "./chunk-GL77IQQE.js";
75
81
  import {
76
82
  STAGING_ORIGIN,
77
83
  getOrigin,
@@ -84,14 +90,14 @@ import { execFileSync as execFileSync2, spawnSync } from "child_process";
84
90
  import { randomUUID } from "crypto";
85
91
  import {
86
92
  existsSync as existsSync5,
87
- mkdirSync as mkdirSync2,
88
- readdirSync as readdirSync2,
93
+ mkdirSync as mkdirSync3,
94
+ readdirSync as readdirSync4,
89
95
  rmSync as rmSync3,
90
- statSync,
91
- writeFileSync
96
+ statSync as statSync2,
97
+ writeFileSync as writeFileSync2
92
98
  } from "fs";
93
- import { homedir as homedir4, userInfo } from "os";
94
- import { basename as basename5, dirname as dirname2, join as join3, resolve as resolve2 } from "path";
99
+ import { homedir as homedir5, userInfo } from "os";
100
+ import { basename as basename5, dirname as dirname3, join as join7, resolve as resolve2 } from "path";
95
101
  import { createInterface } from "readline/promises";
96
102
  import { Writable } from "stream";
97
103
 
@@ -258,127 +264,23 @@ function hasChatGptApp(home, platform = process.platform, env = process.env, fs
258
264
  return false;
259
265
  }
260
266
 
261
- // src/runner-log.ts
262
- var RUNNER_TOOLS = [
263
- "status",
264
- "threads.list",
265
- "thread.read",
266
- "thread.launch",
267
- "thread.send",
268
- "thread.interrupt",
269
- "setup.share",
270
- "diag"
271
- ];
272
- var RUNNER_ERRORS = [
273
- "expired",
274
- "bad_args",
275
- "no_project",
276
- "harness_unavailable",
277
- "harness_signed_out",
278
- "runtime_mode_unknown",
279
- "already_finished",
280
- "repo_busy",
281
- "repo_unreachable",
282
- "cannot_steer",
283
- "cannot_share",
284
- "t3_unauthorized",
285
- "t3_unreachable",
286
- "t3_error",
287
- "harness_error",
288
- "unknown_tool",
289
- "registry_unreachable",
290
- "fetch_failed",
291
- "npx_missing",
292
- "handover_failed"
293
- ];
294
- var HARNESS_IDS = ["claude-code", "codex", "claudeAgent", "opencode"];
295
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
296
- var VERSION2 = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
297
- var oneOf = (list) => (value) => list.includes(value) ? value : void 0;
298
- var toolCode = oneOf(RUNNER_TOOLS);
299
- var uuid = (value) => typeof value === "string" && UUID.test(value) ? value : void 0;
300
- var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1e12 ? value : void 0;
301
- var version = (value) => typeof value === "string" && VERSION2.test(value) ? value : void 0;
302
- function errorCode(value) {
303
- const code = typeof value === "string" && value.startsWith("unknown_tool:") ? "unknown_tool" : value;
304
- return oneOf(RUNNER_ERRORS)(code);
305
- }
306
- function runnerLog(code, fields = {}) {
307
- const shaped = {
308
- call: uuid(fields.call),
309
- work: uuid(fields.work),
310
- tool: toolCode(fields.tool),
311
- ms: count(fields.ms),
312
- error: errorCode(fields.error),
313
- n: count(fields.n),
314
- ver: version(fields.ver)
315
- };
316
- const frame = { type: "log", code };
317
- for (const [key, value] of Object.entries(shaped)) {
318
- if (value !== void 0) Object.assign(frame, { [key]: value });
319
- }
320
- return frame;
321
- }
322
- function callOutcome(input) {
323
- return {
324
- at: new Date(input.at).toISOString(),
325
- tool: toolCode(input.tool) ?? "other",
326
- call: uuid(input.call) ?? null,
327
- work: uuid(input.work) ?? null,
328
- ms: count(Math.round(input.ms)) ?? 0,
329
- ok: input.ok,
330
- error: input.ok ? null : errorCode(input.error) ?? "other"
331
- };
332
- }
333
- function outcomeLine(o) {
334
- return `call tool=${o.tool} call=${o.call ?? "-"} work=${o.work ?? "-"} ms=${o.ms} ok=${o.ok}${o.error ? ` error=${o.error}` : ""}`;
335
- }
336
- var PLATFORMS = ["darwin", "linux", "win32", "freebsd", "openbsd", "aix", "sunos"];
337
- var ARCHES = ["arm64", "x64", "arm", "ia32", "ppc64", "s390x"];
338
- var iso = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && /^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value) ? value : null;
339
- function buildDiag(input) {
340
- return {
341
- version: version(input.version) ?? null,
342
- platform: oneOf(PLATFORMS)(input.platform) ?? "other",
343
- arch: oneOf(ARCHES)(input.arch) ?? "other",
344
- uptime_ms: count(Math.round(input.uptimeMs)) ?? 0,
345
- last_beat_at: iso(input.lastBeatAt),
346
- last_wake: input.lastWake && iso(input.lastWake.woke_at) ? { slept_ms: count(input.lastWake.slept_ms) ?? 0, woke_at: input.lastWake.woke_at } : null,
347
- harnesses: input.harnesses.map((h) => ({
348
- id: oneOf(HARNESS_IDS)(h.id) ?? "other",
349
- version: typeof h.version === "string" ? h.version.match(/\b\d{1,4}\.\d{1,4}\.\d{1,4}\b/)?.[0] ?? null : null,
350
- ready: h.ready === true,
351
- signed_in: h.signedIn === true
352
- })),
353
- update: {
354
- checked_at: iso(input.update.checked_at),
355
- latest: version(input.update.latest) ?? null,
356
- error: errorCode(input.update.error) ?? null
357
- },
358
- unacked_results: count(input.unacked) ?? 0,
359
- clock_offset_ms: typeof input.clockOffsetMs === "number" && Number.isInteger(input.clockOffsetMs) && Math.abs(input.clockOffsetMs) <= 1e12 ? input.clockOffsetMs : null,
360
- // Already shaped: callOutcome is the only way to make one.
361
- calls: input.calls
362
- };
363
- }
364
-
365
267
  // src/box-tools.ts
366
- var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
268
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
367
269
  function parseLaunchArgs(args) {
368
- const str = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
369
- const work_id = str(args.work_id, 36);
370
- const title = str(args.title, 200);
371
- const prompt = str(args.prompt, 1e5);
372
- if (!work_id || !UUID2.test(work_id) || !title || !prompt) throw new BoxToolError("bad_args");
373
- const runtime_mode = str(args.runtime_mode, 40);
270
+ const str2 = (v, max) => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : void 0;
271
+ const work_id = str2(args.work_id, 36);
272
+ const title = str2(args.title, 200);
273
+ const prompt = str2(args.prompt, 1e5);
274
+ if (!work_id || !UUID.test(work_id) || !title || !prompt) throw new BoxToolError("bad_args");
275
+ const runtime_mode = str2(args.runtime_mode, 40);
374
276
  if (runtime_mode && !RUNTIME_MODES.has(runtime_mode)) throw new BoxToolError("bad_args");
375
277
  return {
376
278
  work_id,
377
279
  title: title.startsWith(CLOOP_THREAD_PREFIX) ? title : `${CLOOP_THREAD_PREFIX} ${title}`,
378
280
  prompt,
379
- repository: str(args.repository, 200),
380
- harness: str(args.harness, 80),
381
- model: str(args.model, 120),
281
+ repository: str2(args.repository, 200),
282
+ harness: str2(args.harness, 80),
283
+ model: str2(args.model, 120),
382
284
  runtime_mode,
383
285
  attachments: parseAttachments(args.attachments)
384
286
  };
@@ -390,7 +292,7 @@ function parseThreadId(args) {
390
292
  }
391
293
  function parseCommandId(args) {
392
294
  const id = args.command_id;
393
- if (typeof id !== "string" || !UUID2.test(id)) throw new BoxToolError("bad_args");
295
+ if (typeof id !== "string" || !UUID.test(id)) throw new BoxToolError("bad_args");
394
296
  return id;
395
297
  }
396
298
  function parseSendArgs(args) {
@@ -573,13 +475,13 @@ async function probeClaude(bin = "claude") {
573
475
  exec(bin, ["--version"]),
574
476
  exec(bin, ["auth", "status", "--json"])
575
477
  ]);
576
- const version2 = versionOut?.trim().split(/\s+/)[0];
577
- if (!version2) return null;
478
+ const version = versionOut?.trim().split(/\s+/)[0];
479
+ if (!version) return null;
578
480
  const { signedIn, account } = claudeAccount(auth);
579
481
  return {
580
482
  id: "claude-code",
581
483
  name: "Claude Code",
582
- version: version2,
484
+ version,
583
485
  ready: signedIn,
584
486
  signedIn,
585
487
  account,
@@ -715,7 +617,8 @@ function parseClaudeLine(raw, run) {
715
617
  if (msg.type === "assistant") {
716
618
  const content = msg.message?.content;
717
619
  if (!Array.isArray(content)) return [];
718
- return content.flatMap((block) => {
620
+ const signedOut = msg.error === "authentication_failed" ? [{ type: "signed_out" }] : [];
621
+ const items = content.flatMap((block) => {
719
622
  if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
720
623
  return [{ type: "text", text: block.text }];
721
624
  if (block?.type === "tool_use" && typeof block.name === "string" && block.name !== "AskUserQuestion") {
@@ -735,6 +638,7 @@ function parseClaudeLine(raw, run) {
735
638
  }
736
639
  return [];
737
640
  });
641
+ return [...items, ...signedOut];
738
642
  }
739
643
  if (msg.type === "control_request") {
740
644
  const request = msg.request;
@@ -859,16 +763,16 @@ function codexAccount(ok, out2) {
859
763
  return { signedIn: true, account: /chatgpt/i.test(out2) ? "ChatGPT" : "API key" };
860
764
  }
861
765
  async function probeCodex(bin = "codex") {
862
- const [version2, status] = await Promise.all([
766
+ const [version, status] = await Promise.all([
863
767
  exec2(bin, ["--version"]),
864
768
  exec2(bin, ["login", "status"])
865
769
  ]);
866
- if (!version2.ok) return null;
770
+ if (!version.ok) return null;
867
771
  const { signedIn, account } = codexAccount(status.ok, status.out);
868
772
  return {
869
773
  id: "codex",
870
774
  name: "Codex",
871
- version: version2.out.trim().split(/\s+/).at(-1) ?? null,
775
+ version: version.out.trim().split(/\s+/).at(-1) ?? null,
872
776
  ready: signedIn,
873
777
  signedIn,
874
778
  account,
@@ -929,12 +833,10 @@ function parseCodexLine(raw) {
929
833
  if (msg.type === "turn.completed") return [{ type: "result", ok: true }];
930
834
  if (msg.type === "turn.failed") {
931
835
  const message = msg.error?.message;
836
+ const text = typeof message === "string" ? errorMessage(message) : void 0;
932
837
  return [
933
- {
934
- type: "result",
935
- ok: false,
936
- ...typeof message === "string" ? { text: errorMessage(message) } : {}
937
- }
838
+ { type: "result", ok: false, ...text ? { text } : {} },
839
+ ...text && HARNESS_SIGNED_OUT.test(text) ? [{ type: "signed_out" }] : []
938
840
  ];
939
841
  }
940
842
  return [];
@@ -964,14 +866,14 @@ function codexDialect(bin = "codex") {
964
866
  }
965
867
 
966
868
  // src/legacy-staging.ts
967
- import { existsSync as existsSync4, mkdirSync, renameSync, rmSync as rmSync2 } from "fs";
968
- import { homedir as homedir2 } from "os";
969
- import { join as join2 } from "path";
869
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, renameSync as renameSync2, rmSync as rmSync2 } from "fs";
870
+ import { homedir as homedir3 } from "os";
871
+ import { join as join6 } from "path";
970
872
 
971
873
  // src/commands/disconnect.ts
972
874
  import { execFileSync } from "child_process";
973
- import { existsSync as existsSync3, readFileSync as readFileSync2, rmSync } from "fs";
974
- import { homedir } from "os";
875
+ import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
876
+ import { homedir as homedir2 } from "os";
975
877
  import { basename as basename4 } from "path";
976
878
 
977
879
  // src/existing-runner.ts
@@ -998,6 +900,870 @@ function pinExistingRunner() {
998
900
  };
999
901
  }
1000
902
 
903
+ // src/threads/capture.ts
904
+ import {
905
+ chmodSync,
906
+ closeSync,
907
+ mkdirSync,
908
+ openSync,
909
+ readFileSync as readFileSync2,
910
+ readSync,
911
+ renameSync,
912
+ statSync,
913
+ unlinkSync,
914
+ writeFileSync
915
+ } from "fs";
916
+ import { dirname as dirname2, join as join5 } from "path";
917
+
918
+ // src/threads/claude-code.ts
919
+ import { readdirSync as readdirSync2 } from "fs";
920
+ import { join as join3 } from "path";
921
+
922
+ // src/harness-home.ts
923
+ import { homedir } from "os";
924
+ import { join as join2 } from "path";
925
+ function claudeHome() {
926
+ return process.env.CLAUDE_CONFIG_DIR || join2(homedir(), ".claude");
927
+ }
928
+ function codexHome2() {
929
+ return process.env.CODEX_HOME || join2(homedir(), ".codex");
930
+ }
931
+
932
+ // src/threads/turns.ts
933
+ var TURN_TEXT_MAX = 2e4;
934
+ var TURN_ACTIONS_MAX = 100;
935
+ var COMMAND_MAX = 300;
936
+ var PATH_MAX = 1e3;
937
+ var BATCH_TURNS_MAX = 200;
938
+ var CWD_MAX = 1e3;
939
+ var BRANCH_MAX = 300;
940
+ var TITLE_MAX = 300;
941
+ var TASK_TOOL_MAX = 100;
942
+ var HOST_ID_MAX = 300;
943
+ var HOST_NOTICES = [
944
+ "Update on pull request",
945
+ "Delegated task node",
946
+ "Background command completed",
947
+ "T3 Code stopped watching",
948
+ "Note: the T3 server restarted"
949
+ ];
950
+ function isHostNotice(text) {
951
+ return HOST_NOTICES.some((prefix) => text.startsWith(prefix));
952
+ }
953
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
954
+ var COMMIT_LINE = /^\[(?:[^\]\n]+ )?([0-9a-f]{7,40})\] [^\n]*\n\s*\d+ files? changed/gm;
955
+ function foundActions(text) {
956
+ const actions = [];
957
+ for (const m of text.matchAll(PR_URL)) actions.push({ kind: "pr", url: m[0] });
958
+ for (const m of text.matchAll(COMMIT_LINE)) actions.push({ kind: "commit", sha: m[1] });
959
+ return actions;
960
+ }
961
+ function commandAction(command) {
962
+ const flat = redactSecrets(command.trim());
963
+ if (!flat) return null;
964
+ return {
965
+ kind: "command",
966
+ command: flat.length > COMMAND_MAX ? `${flat.slice(0, COMMAND_MAX - 1)}\u2026` : flat
967
+ };
968
+ }
969
+ function editAction(path) {
970
+ return typeof path === "string" && path && path.length <= PATH_MAX ? { kind: "edit", path } : null;
971
+ }
972
+ var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
973
+ var TASK_ID_KEYS = ["lineage_id", "lineageId", "task_id", "taskId", "item_id", "itemId"];
974
+ function taskAction(tool, input) {
975
+ if (!tool || tool.length > TASK_TOOL_MAX || !isRecord(input)) return null;
976
+ const keys = /task/i.test(tool) ? [...TASK_ID_KEYS, "id"] : TASK_ID_KEYS;
977
+ for (const key of keys) {
978
+ const value = input[key];
979
+ if (typeof value === "string" && UUID2.test(value))
980
+ return { kind: "task", id: value.toLowerCase(), tool };
981
+ }
982
+ return null;
983
+ }
984
+ function isRecord(value) {
985
+ return typeof value === "object" && value !== null && !Array.isArray(value);
986
+ }
987
+ function str(value) {
988
+ return typeof value === "string" && value ? value : void 0;
989
+ }
990
+
991
+ // src/threads/claude-code.ts
992
+ var UUID3 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
993
+ var NOT_TYPED = [
994
+ "<local-command-",
995
+ "<task-notification>",
996
+ "<bash-",
997
+ "<user-memory-input>",
998
+ "<system-reminder>"
999
+ ];
1000
+ var CLOOP_TOOL = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
1001
+ var EDIT_TOOLS = {
1002
+ Edit: "file_path",
1003
+ Write: "file_path",
1004
+ MultiEdit: "file_path",
1005
+ NotebookEdit: "notebook_path"
1006
+ };
1007
+ function files(home) {
1008
+ const root = join3(home, "projects");
1009
+ const out2 = [];
1010
+ for (const project of safeDir(root)) {
1011
+ if (!project.isDirectory()) continue;
1012
+ for (const entry of safeDir(join3(root, project.name))) {
1013
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
1014
+ const sessionId = entry.name.slice(0, -6);
1015
+ if (UUID3.test(sessionId)) out2.push({ path: join3(root, project.name, entry.name), sessionId });
1016
+ }
1017
+ }
1018
+ return out2;
1019
+ }
1020
+ function safeDir(dir) {
1021
+ try {
1022
+ return readdirSync2(dir, { withFileTypes: true });
1023
+ } catch {
1024
+ return [];
1025
+ }
1026
+ }
1027
+ function typedText(content) {
1028
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isRecord(b) && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n") : "";
1029
+ const trimmed = text.trim();
1030
+ if (!trimmed) return null;
1031
+ const command = /<command-name>([^<]*)<\/command-name>/.exec(trimmed);
1032
+ if (command) {
1033
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(trimmed)?.[1] ?? "";
1034
+ return `${command[1]?.trim()} ${args.trim()}`.trim();
1035
+ }
1036
+ if (trimmed.startsWith("<command-message>")) return null;
1037
+ return NOT_TYPED.some((prefix) => trimmed.startsWith(prefix)) || isHostNotice(trimmed) ? null : trimmed;
1038
+ }
1039
+ function resultText(block) {
1040
+ const content = block.content;
1041
+ if (typeof content === "string") return content;
1042
+ if (!Array.isArray(content)) return "";
1043
+ return content.filter((b) => isRecord(b) && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
1044
+ }
1045
+ function userSignals(r, at) {
1046
+ const content = isRecord(r.message) ? r.message.content : void 0;
1047
+ if (Array.isArray(content) && content.some((b) => isRecord(b) && b.type === "tool_result")) {
1048
+ const actions = content.filter(isRecord).filter((b) => b.type === "tool_result").flatMap((b) => foundActions(resultText(b)));
1049
+ return actions.length ? [{ kind: "agent", at, actions }] : [];
1050
+ }
1051
+ if (r.isMeta === true || r.isCompactSummary === true || r.origin !== void 0) return [];
1052
+ const text = typedText(content);
1053
+ return text ? [{ kind: "owner", at, text }] : [];
1054
+ }
1055
+ function toolAction(block) {
1056
+ const name = str(block.name);
1057
+ const input = isRecord(block.input) ? block.input : {};
1058
+ if (!name) return null;
1059
+ const field = EDIT_TOOLS[name];
1060
+ if (field) return editAction(input[field]);
1061
+ if (name === "Bash" && typeof input.command === "string") return commandAction(input.command);
1062
+ const cloop = CLOOP_TOOL.exec(name);
1063
+ return cloop ? taskAction(cloop[1], input) : null;
1064
+ }
1065
+ function assistantSignals(r, at) {
1066
+ const message = isRecord(r.message) ? r.message : {};
1067
+ const blocks = Array.isArray(message.content) ? message.content.filter(isRecord) : [];
1068
+ const text = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n\n").trim();
1069
+ const actions = [
1070
+ ...blocks.filter((b) => b.type === "tool_use").map(toolAction).filter((a) => a !== null),
1071
+ ...foundActions(text)
1072
+ ];
1073
+ const signals = [];
1074
+ if (text || actions.length)
1075
+ signals.push({
1076
+ kind: "agent",
1077
+ at,
1078
+ ...text ? { text } : {},
1079
+ ...actions.length ? { actions } : {}
1080
+ });
1081
+ const stop = message.stop_reason;
1082
+ if (text && (stop === "end_turn" || stop === "stop_sequence")) signals.push({ kind: "end", at });
1083
+ return signals;
1084
+ }
1085
+ function parse(record) {
1086
+ if (!isRecord(record) || record.isSidechain === true) return [];
1087
+ const signals = [];
1088
+ const cwd = str(record.cwd);
1089
+ const branch = str(record.gitBranch);
1090
+ if (cwd || branch)
1091
+ signals.push({ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} });
1092
+ const at = str(record.timestamp);
1093
+ switch (record.type) {
1094
+ case "user":
1095
+ if (at) signals.push(...userSignals(record, at));
1096
+ break;
1097
+ case "assistant":
1098
+ if (at) signals.push(...assistantSignals(record, at));
1099
+ break;
1100
+ case "pr-link": {
1101
+ const url = str(record.prUrl);
1102
+ if (at && url) signals.push({ kind: "agent", at, actions: foundActions(url) });
1103
+ break;
1104
+ }
1105
+ case "summary":
1106
+ case "ai-title": {
1107
+ const title = str(record.summary) ?? str(record.aiTitle);
1108
+ if (title) signals.push({ kind: "thread", title });
1109
+ break;
1110
+ }
1111
+ case "custom-title": {
1112
+ const customTitle = str(record.customTitle);
1113
+ if (customTitle) signals.push({ kind: "thread", customTitle });
1114
+ break;
1115
+ }
1116
+ }
1117
+ return signals;
1118
+ }
1119
+ var claudeCodeLogs = { home: claudeHome, files, parse };
1120
+
1121
+ // src/threads/codex.ts
1122
+ import { readdirSync as readdirSync3 } from "fs";
1123
+ import { join as join4 } from "path";
1124
+ var ROLLOUT = /^rollout-.*([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i;
1125
+ var INJECTED = [
1126
+ "<environment_context",
1127
+ "<user_instructions",
1128
+ "# AGENTS.md instructions",
1129
+ "<INSTRUCTIONS>",
1130
+ "<skill>",
1131
+ "<recommended_plugins",
1132
+ "<permissions instructions",
1133
+ "<turn_aborted",
1134
+ "<user_shell_command",
1135
+ "<subagent_notification",
1136
+ "<model_switch",
1137
+ "[Historical user",
1138
+ "Context handoff"
1139
+ ];
1140
+ function files2(home) {
1141
+ const out2 = [];
1142
+ const walk = (dir, depth) => {
1143
+ for (const entry of safeDir2(dir)) {
1144
+ const path = join4(dir, entry.name);
1145
+ if (entry.isDirectory() && depth < 3) walk(path, depth + 1);
1146
+ else if (entry.isFile() && depth === 3) {
1147
+ const m = ROLLOUT.exec(entry.name);
1148
+ if (m) out2.push({ path, sessionId: m[1].toLowerCase() });
1149
+ }
1150
+ }
1151
+ };
1152
+ walk(join4(home, "sessions"), 0);
1153
+ return out2;
1154
+ }
1155
+ function safeDir2(dir) {
1156
+ try {
1157
+ return readdirSync3(dir, { withFileTypes: true });
1158
+ } catch {
1159
+ return [];
1160
+ }
1161
+ }
1162
+ function blockText(content, type) {
1163
+ if (!Array.isArray(content)) return "";
1164
+ return content.filter((b) => isRecord(b) && b.type === type && typeof b.text === "string").map((b) => b.text).join("\n").trim();
1165
+ }
1166
+ function ownerText(r, p) {
1167
+ const meta = isRecord(r.metadata) ? r.metadata : {};
1168
+ if (meta.inherited_user_message === true) return null;
1169
+ const passthrough = isRecord(p.internal_chat_message_metadata_passthrough) ? p.internal_chat_message_metadata_passthrough : {};
1170
+ const kinds = passthrough.content_item_kinds;
1171
+ if (Array.isArray(kinds) && kinds.some((k) => typeof k !== "string" || !k.startsWith("user.")))
1172
+ return null;
1173
+ const text = blockText(p.content, "input_text");
1174
+ if (!text || INJECTED.some((prefix) => text.startsWith(prefix)) || isHostNotice(text))
1175
+ return null;
1176
+ return text;
1177
+ }
1178
+ function commandText(command) {
1179
+ if (typeof command === "string") return command;
1180
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return null;
1181
+ const argv = command;
1182
+ if (argv.length >= 3 && (argv[1] === "-lc" || argv[1] === "-c")) return argv[2];
1183
+ return argv.join(" ");
1184
+ }
1185
+ function patchedPaths(patch) {
1186
+ return [...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => editAction(m[1]?.trim())).filter((a) => a !== null);
1187
+ }
1188
+ function scriptCommands(script) {
1189
+ const out2 = [];
1190
+ for (const m of script.matchAll(
1191
+ /tools\.exec_command\(\s*\{\s*"?cmd"?\s*:\s*("(?:[^"\\]|\\.)*")/g
1192
+ )) {
1193
+ try {
1194
+ const action = commandAction(JSON.parse(m[1]));
1195
+ if (action) out2.push(action);
1196
+ } catch {
1197
+ }
1198
+ }
1199
+ return [...out2, ...patchedPaths(script)];
1200
+ }
1201
+ var CLOOP_SERVER = /^cloop(?:[-_]staging)?$/;
1202
+ var CLOOP_FUNCTION = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
1203
+ function mcpTaskAction(call) {
1204
+ const server = str(call.server);
1205
+ const tool = str(call.tool);
1206
+ if (!server || !tool || !CLOOP_SERVER.test(server)) return [];
1207
+ const args = typeof call.arguments === "string" ? parseArgs(call.arguments) : call.arguments;
1208
+ const action = taskAction(tool, args);
1209
+ return action ? [action] : [];
1210
+ }
1211
+ function parseArgs(raw) {
1212
+ if (typeof raw !== "string") return {};
1213
+ try {
1214
+ const parsed = JSON.parse(raw);
1215
+ return isRecord(parsed) ? parsed : {};
1216
+ } catch {
1217
+ return {};
1218
+ }
1219
+ }
1220
+ function callActions(p) {
1221
+ const name = str(p.name);
1222
+ if (p.type === "local_shell_call") {
1223
+ const action = isRecord(p.action) ? commandText(p.action.command) : null;
1224
+ const command = action ? commandAction(action) : null;
1225
+ return command ? [command] : [];
1226
+ }
1227
+ if (p.type === "custom_tool_call") {
1228
+ const input = typeof p.input === "string" ? p.input : "";
1229
+ if (name === "apply_patch") return patchedPaths(input);
1230
+ if (name === "exec") return scriptCommands(input);
1231
+ return [];
1232
+ }
1233
+ const args = parseArgs(p.arguments);
1234
+ if (name === "shell" || name === "container.exec" || name === "exec_command") {
1235
+ const text = commandText(args.command ?? args.cmd);
1236
+ const command = text ? commandAction(text) : null;
1237
+ return command ? [command] : [];
1238
+ }
1239
+ if (name === "apply_patch" && typeof args.input === "string") return patchedPaths(args.input);
1240
+ const cloop = name ? CLOOP_FUNCTION.exec(name) : null;
1241
+ const task = cloop ? taskAction(cloop[1], args) : null;
1242
+ return task ? [task] : [];
1243
+ }
1244
+ function outputText(output) {
1245
+ if (typeof output === "string") return output;
1246
+ if (isRecord(output) && typeof output.content === "string") return output.content;
1247
+ if (Array.isArray(output))
1248
+ return output.filter((b) => isRecord(b) && typeof b.text === "string").map((b) => b.text).join("\n");
1249
+ return "";
1250
+ }
1251
+ function changedPaths(changes) {
1252
+ return isRecord(changes) ? Object.keys(changes).map(editAction).filter((a) => a !== null) : [];
1253
+ }
1254
+ function itemActions(item) {
1255
+ if (item.type === "FileChange") return changedPaths(item.changes);
1256
+ if (item.type === "McpToolCall") return mcpTaskAction(item);
1257
+ if (item.type === "CommandExecution") {
1258
+ const text = commandText(item.command);
1259
+ const command = text ? commandAction(text) : null;
1260
+ const stdout = typeof item.stdout === "string" ? foundActions(item.stdout) : [];
1261
+ return [...command ? [command] : [], ...stdout];
1262
+ }
1263
+ return [];
1264
+ }
1265
+ function agent(at, actions) {
1266
+ return actions.length ? [{ kind: "agent", at, actions }] : [];
1267
+ }
1268
+ function responseItem(r, p, at) {
1269
+ switch (p.type) {
1270
+ case "message": {
1271
+ if (p.role === "user") {
1272
+ const text2 = ownerText(r, p);
1273
+ return text2 ? [{ kind: "owner", at, text: text2 }] : [];
1274
+ }
1275
+ if (p.role !== "assistant") return [];
1276
+ const text = blockText(p.content, "output_text");
1277
+ if (!text) return [];
1278
+ const found = foundActions(text);
1279
+ return [{ kind: "agent", at, text, ...found.length ? { actions: found } : {} }];
1280
+ }
1281
+ case "function_call":
1282
+ case "custom_tool_call":
1283
+ case "local_shell_call":
1284
+ return agent(at, callActions(p));
1285
+ case "function_call_output":
1286
+ case "custom_tool_call_output":
1287
+ return agent(at, foundActions(outputText(p.output)));
1288
+ default:
1289
+ return [];
1290
+ }
1291
+ }
1292
+ function eventMsg(p, at) {
1293
+ switch (p.type) {
1294
+ case "task_complete":
1295
+ case "turn_aborted":
1296
+ return [{ kind: "end", at }];
1297
+ case "mcp_tool_call_end":
1298
+ return isRecord(p.invocation) ? agent(at, mcpTaskAction(p.invocation)) : [];
1299
+ case "patch_apply_end":
1300
+ return agent(at, changedPaths(p.changes));
1301
+ case "item_completed":
1302
+ return isRecord(p.item) ? agent(at, itemActions(p.item)) : [];
1303
+ default:
1304
+ return [];
1305
+ }
1306
+ }
1307
+ function parse2(record) {
1308
+ if (!isRecord(record) || !isRecord(record.payload)) return [];
1309
+ const p = record.payload;
1310
+ const at = str(record.timestamp);
1311
+ switch (record.type) {
1312
+ case "session_meta": {
1313
+ const source = isRecord(p.source) ? p.source : {};
1314
+ if (p.parent_thread_id || source.subagent) return [{ kind: "subagent" }];
1315
+ const git = isRecord(p.git) ? p.git : {};
1316
+ const cwd = str(p.cwd);
1317
+ const branch = str(git.branch);
1318
+ return [{ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} }];
1319
+ }
1320
+ case "turn_context": {
1321
+ const cwd = str(p.cwd);
1322
+ return cwd ? [{ kind: "thread", cwd }] : [];
1323
+ }
1324
+ case "response_item":
1325
+ return at ? responseItem(record, p, at) : [];
1326
+ case "event_msg":
1327
+ return at ? eventMsg(p, at) : [];
1328
+ default:
1329
+ return [];
1330
+ }
1331
+ }
1332
+ var codexLogs = { home: codexHome2, files: files2, parse: parse2 };
1333
+
1334
+ // src/threads/capture.ts
1335
+ var CLOOP_OPENERS = [
1336
+ "You are working on a Task from the user's Cloop.",
1337
+ "You are running a Routine for the user, from their Cloop."
1338
+ ];
1339
+ var HARNESS_LOGS = {
1340
+ "claude-code": claudeCodeLogs,
1341
+ codex: codexLogs
1342
+ };
1343
+ var CAPTURE_TICK_MS = 6e4;
1344
+ var TICK_READ_BYTES = 2 * 1024 * 1024;
1345
+ var TICK_TURNS = 500;
1346
+ var BASE_SLACK_BYTES = 256 * 1024;
1347
+ var PROBE_LINES = 50;
1348
+ var REPLY_IDLE_MS = 10 * 6e4;
1349
+ var GATE_OFF_PAUSE_MS = 60 * 6e4;
1350
+ var BODY_BYTES_MAX = 512 * 1024;
1351
+ var READ_CHUNK = 1024 * 1024;
1352
+ function captureCursorPath(threadsFile) {
1353
+ return join5(dirname2(threadsFile), "thread-capture.json");
1354
+ }
1355
+ var ThreadCapture = class {
1356
+ constructor(deps) {
1357
+ this.deps = deps;
1358
+ }
1359
+ deps;
1360
+ running = false;
1361
+ pausedUntil = 0;
1362
+ /** One tick. Null when nothing ran: opted out, paused, or a tick already running. */
1363
+ async tick() {
1364
+ if (this.running) return null;
1365
+ this.running = true;
1366
+ try {
1367
+ return await this.run();
1368
+ } finally {
1369
+ this.running = false;
1370
+ }
1371
+ }
1372
+ now() {
1373
+ return this.deps.now?.() ?? Date.now();
1374
+ }
1375
+ async run() {
1376
+ const now = this.now();
1377
+ if (now < this.pausedUntil) return null;
1378
+ const state = load(this.deps.cursorFile) ?? {
1379
+ startedAt: new Date(now).toISOString(),
1380
+ files: {}
1381
+ };
1382
+ const since = Date.parse(state.startedAt);
1383
+ const own = new Set(await (this.deps.ownSessions?.() ?? Promise.resolve([])).catch(() => []));
1384
+ const hosts = await (this.deps.hostThreads?.() ?? Promise.resolve(/* @__PURE__ */ new Map())).catch(() => /* @__PURE__ */ new Map());
1385
+ const listed = /* @__PURE__ */ new Set();
1386
+ const candidates = [];
1387
+ for (const [harness, logs] of Object.entries(HARNESS_LOGS)) {
1388
+ for (const file of logs.files(logs.home())) {
1389
+ listed.add(file.path);
1390
+ const info = statOrNull(file.path);
1391
+ if (!info || info.mtimeMs < since) continue;
1392
+ candidates.push({
1393
+ ...file,
1394
+ harness,
1395
+ logs,
1396
+ ino: info.ino,
1397
+ size: info.size,
1398
+ mtimeMs: info.mtimeMs
1399
+ });
1400
+ }
1401
+ }
1402
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
1403
+ for (const file of candidates) {
1404
+ const known = state.files[file.path];
1405
+ if (!(known && known.ino === file.ino && file.size >= known.offset))
1406
+ state.files[file.path] = freshCursor(file, since);
1407
+ }
1408
+ const budget = { bytes: TICK_READ_BYTES, turns: TICK_TURNS };
1409
+ const outgoing = [];
1410
+ for (const file of candidates) {
1411
+ if (budget.bytes <= 0 || budget.turns <= 0) break;
1412
+ const known = state.files[file.path];
1413
+ const cursor = structuredClone(known);
1414
+ const host = hosts.get(file.sessionId);
1415
+ if (own.has(file.sessionId)) cursor.verdict = "cloop";
1416
+ if (host?.delegated && cursor.verdict === "pending") becomeOwner(cursor);
1417
+ const idle = now - file.mtimeMs >= REPLY_IDLE_MS;
1418
+ const metaOf = () => threadMeta(cursor.thread, host);
1419
+ if (cursor.verdict === "cloop" || cursor.verdict === "subagent" || file.size === cursor.offset && !(cursor.open && idle) && !(cursor.verdict === "owner" && JSON.stringify(metaOf()) !== cursor.sentMeta)) {
1420
+ state.files[file.path] = cursor;
1421
+ continue;
1422
+ }
1423
+ const turns = [];
1424
+ const consumedAll = readInto(file, cursor, budget, turns);
1425
+ if (consumedAll && cursor.verdict === "owner" && cursor.open && idle) close(cursor, turns);
1426
+ const meta = metaOf();
1427
+ const metaKey = JSON.stringify(meta);
1428
+ const metaChanged = cursor.verdict === "owner" && metaKey !== cursor.sentMeta;
1429
+ const send = turns.filter((t) => Date.parse(t.at) >= since);
1430
+ budget.turns -= send.length;
1431
+ const live = cursor.verdict === "owner" && cursor.live && Date.parse(cursor.live.at) >= since && !sameLive(cursor.live, known?.live) ? cursor.live : void 0;
1432
+ if (send.length === 0 && !live && !metaChanged) state.files[file.path] = cursor;
1433
+ else
1434
+ outgoing.push({
1435
+ path: file.path,
1436
+ next: { ...cursor, sentMeta: metaKey },
1437
+ batch: {
1438
+ harness: file.harness,
1439
+ session_id: file.sessionId,
1440
+ thread: meta,
1441
+ turns: send,
1442
+ ...live ? { live } : {}
1443
+ }
1444
+ });
1445
+ }
1446
+ const report = {
1447
+ sessionsSeen: candidates.length,
1448
+ sessionsSent: 0,
1449
+ sessionsCloop: candidates.filter((f) => state.files[f.path]?.verdict === "cloop").length,
1450
+ sessionsSubagent: candidates.filter((f) => state.files[f.path]?.verdict === "subagent").length,
1451
+ turns: 0,
1452
+ dropped: 0,
1453
+ bytes: 0,
1454
+ readBytes: TICK_READ_BYTES - budget.bytes,
1455
+ status: null
1456
+ };
1457
+ for (const out2 of outgoing) {
1458
+ const result = await this.send(out2.batch, report);
1459
+ if (result.ok || result.drop) state.files[out2.path] = out2.next;
1460
+ if (result.ok) {
1461
+ report.sessionsSent++;
1462
+ report.turns += out2.batch.turns.length;
1463
+ report.status = 200;
1464
+ continue;
1465
+ }
1466
+ report.status = result.status;
1467
+ if (result.drop) {
1468
+ report.dropped += out2.batch.turns.length;
1469
+ continue;
1470
+ }
1471
+ if (result.status === 403) this.pausedUntil = now + GATE_OFF_PAUSE_MS;
1472
+ break;
1473
+ }
1474
+ for (const path of Object.keys(state.files)) if (!listed.has(path)) delete state.files[path];
1475
+ if (report.status === 403) forget(this.deps.cursorFile);
1476
+ else save(this.deps.cursorFile, state);
1477
+ if (outgoing.length)
1478
+ this.deps.log(
1479
+ `[runner-threads:capture] ${report.status === 200 ? "sent" : "failed"} sessions=${report.sessionsSent}/${outgoing.length} turns=${report.turns} dropped=${report.dropped} bytes=${report.bytes} read=${report.readBytes} status=${report.status}`
1480
+ );
1481
+ return report;
1482
+ }
1483
+ /** Every chunk of one session's turns. A 400 or 413 is a refusal for good: the cursor moves on. */
1484
+ async send(batch, report) {
1485
+ for (const chunk of chunks(batch)) {
1486
+ const body = JSON.stringify(chunk);
1487
+ let res;
1488
+ try {
1489
+ res = await (this.deps.fetchFn ?? fetch)(
1490
+ `${this.deps.origin}/api/agent/mesh/thread-turns`,
1491
+ {
1492
+ method: "POST",
1493
+ headers: {
1494
+ "content-type": "application/json",
1495
+ authorization: `Bearer ${this.deps.deviceToken()}`
1496
+ },
1497
+ body,
1498
+ signal: AbortSignal.timeout(3e4)
1499
+ }
1500
+ );
1501
+ } catch {
1502
+ return { ok: false, status: "unreachable", drop: false };
1503
+ }
1504
+ if (!res.ok) {
1505
+ return { ok: false, status: res.status, drop: res.status === 400 || res.status === 413 };
1506
+ }
1507
+ report.bytes += Buffer.byteLength(body);
1508
+ }
1509
+ return { ok: true };
1510
+ }
1511
+ };
1512
+ function freshCursor(file, since) {
1513
+ const base = baseFor(file.path, file.size, since);
1514
+ return {
1515
+ harness: file.harness,
1516
+ sessionId: file.sessionId,
1517
+ ino: file.ino,
1518
+ offset: 0,
1519
+ ...base ? { base } : {},
1520
+ seq: 0,
1521
+ ownerTurns: 0,
1522
+ verdict: "pending",
1523
+ thread: {}
1524
+ };
1525
+ }
1526
+ function baseFor(path, size, since) {
1527
+ let lo = 0;
1528
+ let hi = size;
1529
+ while (hi - lo > BASE_SLACK_BYTES) {
1530
+ const mid = lo + Math.floor((hi - lo) / 2);
1531
+ const probe = datedLineAt(path, mid, hi);
1532
+ if (!probe || probe.at >= since) hi = mid;
1533
+ else lo = probe.end;
1534
+ }
1535
+ return lo === 0 ? 0 : lineStartAtOrAfter(path, lo, size);
1536
+ }
1537
+ function datedLineAt(path, pos, limit) {
1538
+ let lines = 0;
1539
+ for (const { line: line2, end } of completeLines(path, lineStartAtOrAfter(path, pos, limit), limit)) {
1540
+ if (++lines > PROBE_LINES) return null;
1541
+ let at = Number.NaN;
1542
+ try {
1543
+ const record = JSON.parse(line2);
1544
+ if (isRecord(record) && typeof record.timestamp === "string")
1545
+ at = Date.parse(record.timestamp);
1546
+ } catch {
1547
+ }
1548
+ if (!Number.isNaN(at)) return { at, end };
1549
+ }
1550
+ return null;
1551
+ }
1552
+ function lineStartAtOrAfter(path, pos, size) {
1553
+ if (pos <= 0) return 0;
1554
+ const fd = openSync(path, "r");
1555
+ try {
1556
+ for (let at = pos - 1; at < size; at += READ_CHUNK) {
1557
+ const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - at));
1558
+ const n = readSync(fd, chunk, 0, chunk.length, at);
1559
+ if (n <= 0) break;
1560
+ const nl = chunk.subarray(0, n).indexOf(10);
1561
+ if (nl !== -1) return at + nl + 1;
1562
+ }
1563
+ return size;
1564
+ } finally {
1565
+ closeSync(fd);
1566
+ }
1567
+ }
1568
+ function becomeOwner(cursor) {
1569
+ const base = cursor.base ?? 0;
1570
+ Object.assign(cursor, { offset: base, seq: base, ownerTurns: 0, verdict: "owner" });
1571
+ cursor.open = void 0;
1572
+ cursor.live = void 0;
1573
+ }
1574
+ function readInto(file, cursor, budget, out2) {
1575
+ for (; ; ) {
1576
+ let restart = false;
1577
+ for (const { line: line2, end } of completeLines(file.path, cursor.offset, file.size)) {
1578
+ if (budget.bytes <= 0 || out2.length >= budget.turns) return false;
1579
+ budget.bytes -= end - cursor.offset;
1580
+ cursor.offset = end;
1581
+ let record;
1582
+ try {
1583
+ record = JSON.parse(line2);
1584
+ } catch {
1585
+ continue;
1586
+ }
1587
+ fold(cursor, file.logs.parse(record), out2);
1588
+ if (cursor.verdict === "cloop" || cursor.verdict === "subagent") return false;
1589
+ if (cursor.verdict === "pending" && cursor.ownerTurns >= 2) {
1590
+ becomeOwner(cursor);
1591
+ restart = true;
1592
+ break;
1593
+ }
1594
+ }
1595
+ if (!restart) return true;
1596
+ }
1597
+ }
1598
+ function* completeLines(path, from, size) {
1599
+ const fd = openSync(path, "r");
1600
+ try {
1601
+ let pos = from;
1602
+ let carry = Buffer.alloc(0);
1603
+ while (pos < size) {
1604
+ const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - pos));
1605
+ const n = readSync(fd, chunk, 0, chunk.length, pos);
1606
+ if (n <= 0) break;
1607
+ pos += n;
1608
+ const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
1609
+ const base = pos - data.length;
1610
+ let start = 0;
1611
+ for (let nl = data.indexOf(10, start); nl !== -1; nl = data.indexOf(10, start)) {
1612
+ yield { line: data.toString("utf8", start, nl), end: base + nl + 1 };
1613
+ start = nl + 1;
1614
+ }
1615
+ carry = Buffer.from(data.subarray(start));
1616
+ }
1617
+ } finally {
1618
+ closeSync(fd);
1619
+ }
1620
+ }
1621
+ function clip(text) {
1622
+ return text.length > TURN_TEXT_MAX ? `${text.slice(0, TURN_TEXT_MAX - 1)}\u2026` : text;
1623
+ }
1624
+ function close(cursor, out2) {
1625
+ const open = cursor.open;
1626
+ if (!open) return;
1627
+ out2.push({ seq: open.seq, at: open.at, role: "agent", text: open.text, actions: open.actions });
1628
+ cursor.open = void 0;
1629
+ }
1630
+ function addAction(turn, action) {
1631
+ if (turn.actions.length >= TURN_ACTIONS_MAX) return;
1632
+ const key = JSON.stringify(action);
1633
+ if (!turn.actions.some((a) => JSON.stringify(a) === key)) turn.actions.push(action);
1634
+ }
1635
+ function fold(cursor, signals, out2) {
1636
+ for (const signal of signals) {
1637
+ switch (signal.kind) {
1638
+ case "subagent":
1639
+ cursor.verdict = "subagent";
1640
+ return;
1641
+ case "thread": {
1642
+ const { kind: _, ...meta } = signal;
1643
+ Object.assign(cursor.thread, meta);
1644
+ break;
1645
+ }
1646
+ case "owner":
1647
+ cursor.live = { at: signal.at, state: "working" };
1648
+ cursor.ownerTurns++;
1649
+ if (cursor.ownerTurns === 1 && CLOOP_OPENERS.some((o) => signal.text.startsWith(o))) {
1650
+ cursor.verdict = "cloop";
1651
+ return;
1652
+ }
1653
+ if (!cursor.thread.firstAsk) {
1654
+ const ask = askTitle(signal.text);
1655
+ if (ask) cursor.thread.firstAsk = ask;
1656
+ }
1657
+ if (cursor.verdict !== "owner") break;
1658
+ close(cursor, out2);
1659
+ out2.push({
1660
+ seq: cursor.seq++,
1661
+ at: signal.at,
1662
+ role: "owner",
1663
+ text: clip(redactSecrets(signal.text)),
1664
+ actions: []
1665
+ });
1666
+ break;
1667
+ case "agent": {
1668
+ cursor.live = { at: signal.at, state: "working" };
1669
+ if (cursor.verdict !== "owner") break;
1670
+ if (!cursor.open) cursor.open = { seq: cursor.seq++, at: signal.at, text: "", actions: [] };
1671
+ const open = cursor.open;
1672
+ if (signal.text) {
1673
+ const said = redactSecrets(signal.text);
1674
+ open.text = clip(open.text ? `${open.text}
1675
+
1676
+ ${said}` : said);
1677
+ }
1678
+ for (const action of signal.actions ?? []) addAction(open, action);
1679
+ break;
1680
+ }
1681
+ case "end": {
1682
+ const at = signal.at ?? cursor.live?.at;
1683
+ if (at) cursor.live = { at, state: "your_turn" };
1684
+ if (cursor.verdict === "owner") close(cursor, out2);
1685
+ break;
1686
+ }
1687
+ }
1688
+ }
1689
+ }
1690
+ var ASK_TITLE_MAX = 80;
1691
+ function askTitle(text) {
1692
+ const line2 = redactSecrets(text).split("\n").map((l) => l.replace(/\s+/g, " ").trim()).find((l) => l && !/^\/\S+$/.test(l));
1693
+ if (!line2) return void 0;
1694
+ if (line2.length <= ASK_TITLE_MAX) return line2;
1695
+ const cut2 = line2.slice(0, ASK_TITLE_MAX - 1);
1696
+ const space = cut2.lastIndexOf(" ");
1697
+ return `${space > ASK_TITLE_MAX / 2 ? cut2.slice(0, space) : cut2}\u2026`;
1698
+ }
1699
+ function threadMeta(thread, host) {
1700
+ const title = host?.title ?? thread.customTitle ?? thread.title ?? thread.firstAsk;
1701
+ return {
1702
+ ...thread.cwd ? { cwd: thread.cwd.slice(0, CWD_MAX) } : {},
1703
+ ...thread.branch ? { branch: thread.branch.slice(0, BRANCH_MAX) } : {},
1704
+ ...title ? { title: title.slice(0, TITLE_MAX) } : {},
1705
+ ...host?.delegated ? { delegated: true } : {},
1706
+ ...host ? {
1707
+ host: host.host,
1708
+ host_thread_id: host.threadId,
1709
+ ...host.parentId ? { host_parent_id: host.parentId } : {},
1710
+ settled: host.settled
1711
+ } : {}
1712
+ };
1713
+ }
1714
+ function sameLive(a, b) {
1715
+ return a?.at === b?.at && a?.state === b?.state;
1716
+ }
1717
+ function* chunks(batch) {
1718
+ const { live, ...rest } = batch;
1719
+ let turns = [];
1720
+ let bytes = 0;
1721
+ for (const turn of batch.turns) {
1722
+ const size = Buffer.byteLength(JSON.stringify(turn));
1723
+ if (turns.length && (turns.length >= BATCH_TURNS_MAX || bytes + size > BODY_BYTES_MAX)) {
1724
+ yield { ...rest, turns };
1725
+ turns = [];
1726
+ bytes = 0;
1727
+ }
1728
+ turns.push(turn);
1729
+ bytes += size;
1730
+ }
1731
+ yield { ...rest, turns, ...live ? { live } : {} };
1732
+ }
1733
+ function statOrNull(path) {
1734
+ try {
1735
+ return statSync(path);
1736
+ } catch {
1737
+ return null;
1738
+ }
1739
+ }
1740
+ function load(file) {
1741
+ try {
1742
+ const raw = JSON.parse(readFileSync2(file, "utf-8"));
1743
+ if (typeof raw.startedAt !== "string" || Number.isNaN(Date.parse(raw.startedAt))) return null;
1744
+ return {
1745
+ startedAt: raw.startedAt,
1746
+ files: typeof raw.files === "object" && raw.files ? raw.files : {}
1747
+ };
1748
+ } catch {
1749
+ return null;
1750
+ }
1751
+ }
1752
+ function save(file, state) {
1753
+ mkdirSync(dirname2(file), { recursive: true, mode: 448 });
1754
+ const tmp = `${file}.tmp`;
1755
+ writeFileSync(tmp, `${JSON.stringify(state)}
1756
+ `, { mode: 384 });
1757
+ chmodSync(tmp, 384);
1758
+ renameSync(tmp, file);
1759
+ }
1760
+ function forget(file) {
1761
+ try {
1762
+ unlinkSync(file);
1763
+ } catch {
1764
+ }
1765
+ }
1766
+
1001
1767
  // src/commands/disconnect.ts
1002
1768
  function doneLine(env) {
1003
1769
  return `This computer is no longer a ${env} Cloop machine. To connect it again: ${["npx -y @cloop/runner@latest connect", ENVIRONMENTS[env].flag].filter(Boolean).join(" ")}`;
@@ -1012,7 +1778,7 @@ function unitOrigin(contents) {
1012
1778
  }
1013
1779
  function disconnectPlan(opts) {
1014
1780
  const exists = opts.exists ?? existsSync3;
1015
- const read = opts.read ?? ((path) => readFileSync2(path, "utf-8"));
1781
+ const read = opts.read ?? ((path) => readFileSync3(path, "utf-8"));
1016
1782
  const installed = ["local", "workstation"].map((kind) => ({ kind, service: installedService({ ...opts, kind }) })).filter(({ service }) => exists(service.path));
1017
1783
  const services = installed.map(({ service }) => service);
1018
1784
  const fromUnit = services.map((service) => {
@@ -1115,14 +1881,19 @@ function thisComputer(env, fallbackOrigin) {
1115
1881
  return {
1116
1882
  platform: process.platform,
1117
1883
  environment: env,
1118
- home: homedir(),
1884
+ home: homedir2(),
1119
1885
  uid: process.getuid?.() ?? 0,
1120
1886
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {},
1121
1887
  box: boxPath(env),
1122
1888
  deviceToken: cfg?.deviceToken ?? null,
1123
1889
  ...cfg?.origin ? { boxOrigin: cfg.origin } : {},
1124
1890
  fallbackOrigin,
1125
- files: [localRunsFilePath(env), runnerStatePath(env), threadsFilePath(env)]
1891
+ files: [
1892
+ localRunsFilePath(env),
1893
+ runnerStatePath(env),
1894
+ threadsFilePath(env),
1895
+ captureCursorPath(threadsFilePath(env))
1896
+ ]
1126
1897
  };
1127
1898
  }
1128
1899
  async function disconnectCommand(argv) {
@@ -1155,11 +1926,11 @@ function legacyStagingRunner() {
1155
1926
  return origin !== void 0 && environmentOf(origin) === "staging";
1156
1927
  }
1157
1928
  function moveRunnerFiles(from, to) {
1158
- mkdirSync(to, { recursive: true, mode: 448 });
1929
+ mkdirSync2(to, { recursive: true, mode: 448 });
1159
1930
  for (const name of MOVED) {
1160
- const source = join2(from, name);
1161
- const target = join2(to, name);
1162
- if (existsSync4(source) && !existsSync4(target)) renameSync(source, target);
1931
+ const source = join6(from, name);
1932
+ const target = join6(to, name);
1933
+ if (existsSync4(source) && !existsSync4(target)) renameSync2(source, target);
1163
1934
  }
1164
1935
  }
1165
1936
  function legacyServices(platform) {
@@ -1168,7 +1939,7 @@ function legacyServices(platform) {
1168
1939
  platform,
1169
1940
  kind,
1170
1941
  environment: "production",
1171
- home: homedir2(),
1942
+ home: homedir3(),
1172
1943
  uid: process.getuid?.() ?? 0,
1173
1944
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1174
1945
  })
@@ -1195,7 +1966,7 @@ function movedLine(connecting) {
1195
1966
 
1196
1967
  // src/mcp-registration.ts
1197
1968
  import { execFile as execFile3, spawn as spawn2 } from "child_process";
1198
- import { homedir as homedir3 } from "os";
1969
+ import { homedir as homedir4 } from "os";
1199
1970
  var MCP_HARNESS_NAME = {
1200
1971
  "claude-code": "Claude Code",
1201
1972
  codex: "Codex"
@@ -1242,7 +2013,7 @@ var systemMcpCli = {
1242
2013
  command.args,
1243
2014
  {
1244
2015
  // A project's own MCP config under the folder connect ran in must not stand in for the user's.
1245
- cwd: homedir3(),
2016
+ cwd: homedir4(),
1246
2017
  timeout: 45e3,
1247
2018
  encoding: "utf-8",
1248
2019
  env: { ...process.env, ...env },
@@ -1259,7 +2030,7 @@ var systemMcpCli = {
1259
2030
  };
1260
2031
  process.on("SIGINT", ignore);
1261
2032
  const child = spawn2(command.file, command.args, {
1262
- cwd: homedir3(),
2033
+ cwd: homedir4(),
1263
2034
  stdio: "inherit",
1264
2035
  ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1265
2036
  });
@@ -1483,7 +2254,7 @@ function boxSession(t3Url, t3Bin, env, token) {
1483
2254
  }
1484
2255
  async function mintSession(t3Url, opts = {}) {
1485
2256
  const env = await workstationEnvironment(t3Url, opts.fetchFn);
1486
- const sources = opts.sources ?? defaultT3BinSources(homedir4(), opts.stored);
2257
+ const sources = opts.sources ?? defaultT3BinSources(homedir5(), opts.stored);
1487
2258
  try {
1488
2259
  const t3Bin = opts.bin ?? pickT3Bin(t3Candidates(env.serverVersion, sources), env.serverVersion);
1489
2260
  if (!t3Bin) throw new Error("no t3 binary found; pass --t3-bin or set T3_BIN");
@@ -1605,7 +2376,7 @@ function boxServiceInstalled() {
1605
2376
  platform: process.platform,
1606
2377
  kind: "workstation",
1607
2378
  environment: runnerEnvironment(),
1608
- home: homedir4(),
2379
+ home: homedir5(),
1609
2380
  uid: process.getuid?.() ?? 0,
1610
2381
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
1611
2382
  }).path
@@ -1696,18 +2467,19 @@ var endDaemonStep = (environment) => ({
1696
2467
  ],
1697
2468
  mayFail: true
1698
2469
  });
1699
- function programFor(script, node, npx, version2) {
2470
+ function programFor(script, node, npx, version) {
1700
2471
  if (!/[\\/]_npx[\\/]/.test(script)) return [node, script, "box", "run"];
1701
2472
  if (!npx)
1702
2473
  return "npx is not on PATH, so the service cannot run Cloop. Install it with `npm install -g @cloop/runner` and run `cloop connect` again.";
1703
- return [npx, "-y", `@cloop/runner@${version2}`, "box", "run"];
2474
+ return [npx, "-y", `@cloop/runner@${version}`, "box", "run"];
1704
2475
  }
1705
2476
  function findNpx() {
1706
2477
  const name = process.platform === "win32" ? "npx.cmd" : "npx";
1707
- const beside = join3(dirname2(process.execPath), name);
2478
+ const beside = join7(dirname3(process.execPath), name);
1708
2479
  return existsSync5(beside) ? beside : which(name);
1709
2480
  }
1710
- async function awaitDaemon(since, read = readRunnerState, { timeoutMs = 15e3, pollMs = 500 } = {}) {
2481
+ var FIRST_CONNECT_MS = 9e4;
2482
+ async function awaitDaemon(since, read = readRunnerState, { timeoutMs = FIRST_CONNECT_MS, pollMs = 500 } = {}) {
1711
2483
  for (let waited = 0; ; waited += pollMs) {
1712
2484
  const state = read();
1713
2485
  if (state && Date.parse(state.connected_at) >= since) return true;
@@ -1742,14 +2514,14 @@ function installedService(opts) {
1742
2514
  const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
1743
2515
  if (opts.platform === "darwin") {
1744
2516
  return {
1745
- path: join3(opts.dir ?? join3(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
2517
+ path: join7(opts.dir ?? join7(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
1746
2518
  steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
1747
2519
  running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
1748
2520
  };
1749
2521
  }
1750
2522
  if (opts.platform === "win32") {
1751
2523
  return {
1752
- path: join3(opts.dir ?? join3(opts.home, "AppData", "Local", "Cloop"), `${file}.cmd`),
2524
+ path: join7(opts.dir ?? join7(opts.home, "AppData", "Local", "Cloop"), `${file}.cmd`),
1753
2525
  steps: [
1754
2526
  { command: ["schtasks", "/end", "/tn", task], mayFail: true },
1755
2527
  endDaemonStep(opts.environment),
@@ -1759,7 +2531,7 @@ function installedService(opts) {
1759
2531
  };
1760
2532
  }
1761
2533
  return {
1762
- path: join3(opts.dir ?? join3(opts.home, ".config", "systemd", "user"), unit),
2534
+ path: join7(opts.dir ?? join7(opts.home, ".config", "systemd", "user"), unit),
1763
2535
  steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
1764
2536
  running: ["systemctl", "--user", "is-active", "--quiet", unit]
1765
2537
  };
@@ -1772,9 +2544,9 @@ function unitFor(opts) {
1772
2544
  kind: opts.kind === "workstation" ? "local" : "workstation"
1773
2545
  });
1774
2546
  if (opts.platform === "darwin") {
1775
- const agents = opts.dir ?? join3(opts.home, "Library", "LaunchAgents");
1776
- const path2 = join3(agents, `${label}.plist`);
1777
- const log = join3(opts.home, "Library", "Logs", `${file}.log`);
2547
+ const agents = opts.dir ?? join7(opts.home, "Library", "LaunchAgents");
2548
+ const path2 = join7(agents, `${label}.plist`);
2549
+ const log = join7(opts.home, "Library", "Logs", `${file}.log`);
1778
2550
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1779
2551
  const contents2 = [
1780
2552
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -1811,9 +2583,9 @@ function unitFor(opts) {
1811
2583
  };
1812
2584
  }
1813
2585
  if (opts.platform === "win32") {
1814
- const dir = opts.dir ?? join3(opts.home, "AppData", "Local", "Cloop");
1815
- const path2 = join3(dir, `${file}.cmd`);
1816
- const log = join3(dir, `${file}.log`);
2586
+ const dir = opts.dir ?? join7(opts.home, "AppData", "Local", "Cloop");
2587
+ const path2 = join7(dir, `${file}.cmd`);
2588
+ const log = join7(dir, `${file}.log`);
1817
2589
  const psLog = log.replace(/'/g, "''");
1818
2590
  const contents2 = [
1819
2591
  "@echo off",
@@ -1853,8 +2625,8 @@ function unitFor(opts) {
1853
2625
  ]
1854
2626
  };
1855
2627
  }
1856
- const units = opts.dir ?? join3(opts.home, ".config", "systemd", "user");
1857
- const path = join3(units, unit);
2628
+ const units = opts.dir ?? join7(opts.home, ".config", "systemd", "user");
2629
+ const path = join7(units, unit);
1858
2630
  const contents = [
1859
2631
  "[Unit]",
1860
2632
  `Description=${task}: answers the Cloop Agent over the mesh`,
@@ -1901,7 +2673,7 @@ function resolveRepos(paths, toplevel, isFolder = folderAt) {
1901
2673
  }
1902
2674
  function folderAt(path) {
1903
2675
  try {
1904
- return statSync(path).isDirectory();
2676
+ return statSync2(path).isDirectory();
1905
2677
  } catch {
1906
2678
  return false;
1907
2679
  }
@@ -1925,13 +2697,13 @@ function findCheckouts(home, limit = 8) {
1925
2697
  for (const root of CHECKOUT_ROOTS) {
1926
2698
  let entries;
1927
2699
  try {
1928
- entries = readdirSync2(join3(home, root), { withFileTypes: true });
2700
+ entries = readdirSync4(join7(home, root), { withFileTypes: true });
1929
2701
  } catch {
1930
2702
  continue;
1931
2703
  }
1932
2704
  for (const entry of entries) {
1933
- const path = join3(home, root, entry.name);
1934
- if (!entry.isDirectory() || !existsSync5(join3(path, ".git"))) continue;
2705
+ const path = join7(home, root, entry.name);
2706
+ if (!entry.isDirectory() || !existsSync5(join7(path, ".git"))) continue;
1935
2707
  found.push({ repo: { label: entry.name, path }, at: lastCommitAt(path) });
1936
2708
  }
1937
2709
  }
@@ -1951,7 +2723,7 @@ function rerunCommand(argv, script = process.argv[1] ?? "") {
1951
2723
  return [base, "connect", ...staging, ...argv].join(" ");
1952
2724
  }
1953
2725
  function workFolder(home) {
1954
- return { label: "Cloop", path: join3(home, "Cloop") };
2726
+ return { label: "Cloop", path: join7(home, "Cloop") };
1955
2727
  }
1956
2728
  function workFolderLine(found, home, argv, terminal) {
1957
2729
  const rerun = rerunCommand(argv.filter((a) => a !== "--ask"));
@@ -1987,7 +2759,7 @@ async function reposFor(argv) {
1987
2759
  }
1988
2760
  const here = gitTop(process.cwd());
1989
2761
  if (here) return [{ label: basename5(here), path: here }];
1990
- const home = homedir4();
2762
+ const home = homedir5();
1991
2763
  const work = workFolder(home);
1992
2764
  const found = findCheckouts(home);
1993
2765
  let repos = [work];
@@ -2004,7 +2776,7 @@ async function reposFor(argv) {
2004
2776
  prompt.close();
2005
2777
  }
2006
2778
  } else out(`${bold("Cloop machine")} ${workFolderLine(found, home, argv, terminal)}`);
2007
- if (repos.some((r) => r.path === work.path)) mkdirSync2(work.path, { recursive: true });
2779
+ if (repos.some((r) => r.path === work.path)) mkdirSync3(work.path, { recursive: true });
2008
2780
  return repos;
2009
2781
  }
2010
2782
  function askOrClosed(prompt, closed) {
@@ -2042,9 +2814,9 @@ async function t3Answers(t3Url) {
2042
2814
  }
2043
2815
  }
2044
2816
  function harnessLine(h) {
2045
- const version2 = h.version ? ` ${h.version}` : "";
2817
+ const version = h.version ? ` ${h.version}` : "";
2046
2818
  const account = h.signedIn ? h.account ?? "signed in" : "signed out";
2047
- return `${h.name}${version2}, ${account}${h.experimental ? " (experimental)" : ""}`;
2819
+ return `${h.name}${version}, ${account}${h.experimental ? " (experimental)" : ""}`;
2048
2820
  }
2049
2821
  async function runSteps(steps, run = (command) => void execFileSync2(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
2050
2822
  for (const step of steps) {
@@ -2103,14 +2875,14 @@ async function installService(kind, argv, attempt, services = systemServices) {
2103
2875
  platform: services.platform,
2104
2876
  kind,
2105
2877
  environment,
2106
- home: homedir4(),
2878
+ home: homedir5(),
2107
2879
  program,
2108
2880
  env: serviceEnv(),
2109
2881
  uid: process.getuid?.() ?? 0,
2110
2882
  ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
2111
2883
  });
2112
- mkdirSync2(join3(unit.path, ".."), { recursive: true });
2113
- writeFileSync(unit.path, unit.contents);
2884
+ mkdirSync3(join7(unit.path, ".."), { recursive: true });
2885
+ writeFileSync2(unit.path, unit.contents);
2114
2886
  if (argv.includes("--no-start")) {
2115
2887
  out(
2116
2888
  ` Service: wrote ${unit.path}. Start it with: ${dim(unit.start.map((step) => step.command.join(" ")).join(" && "))}`
@@ -2136,9 +2908,12 @@ async function installService(kind, argv, attempt, services = systemServices) {
2136
2908
  );
2137
2909
  }
2138
2910
  attempt.step = "first_connect";
2911
+ out(
2912
+ " Waiting for the machine to reach Cloop. A first start downloads the runner, so this can take a minute."
2913
+ );
2139
2914
  if (!await services.awaitUp(since)) {
2140
2915
  out(
2141
- `${red("\u2717")} ${unit.path} started, but the machine did not reach Cloop within 15 s. Its last log lines:`
2916
+ `${red("\u2717")} ${unit.path} started, but the machine did not reach Cloop within ${FIRST_CONNECT_MS / 1e3} s. Its last log lines:`
2142
2917
  );
2143
2918
  try {
2144
2919
  out(services.run(unit.tail));
@@ -2257,12 +3032,12 @@ async function connectT3(argv, attempt, fallback, chosen, services) {
2257
3032
  async function connectLocal(driver, found, argv, attempt, chosen, services) {
2258
3033
  attempt.step = "repos";
2259
3034
  const repos = await reposFor(argv);
2260
- const work = workFolder(homedir4()).path;
3035
+ const work = workFolder(homedir5()).path;
2261
3036
  attempt.workFolder = repos.every((r) => r.path === work);
2262
3037
  const harness = driver === "claude-code" ? found.claude : found.codex;
2263
3038
  const bin = which(driver === "claude-code" ? "claude" : "codex") ?? (driver === "claude-code" ? "claude" : "codex");
2264
3039
  const previous = readRunnerConfig();
2265
- const deviceName = flag(argv, "--name") ?? shortMachineName();
3040
+ const deviceName = flag(argv, "--name") ?? defaultDeviceName();
2266
3041
  const fallbackModels = driver === "claude-code" ? flag(argv, "--fallback-model") ?? (previous && isLocal(previous) ? previous.fallbackModels : void 0) ?? DEFAULT_FALLBACK_MODEL : void 0;
2267
3042
  const device = {
2268
3043
  kind: "local",
@@ -2351,8 +3126,8 @@ async function connect(argv, attempt, deps = {}) {
2351
3126
  );
2352
3127
  const t3Url = (flag(argv, "--t3-url") ?? DEFAULT_T3_URL).replace(/\/+$/, "");
2353
3128
  const harnessBin = (name) => process.platform === "win32" ? which(name) ?? name : name;
2354
- findLocalCodex(homedir4());
2355
- findLocalClaude(homedir4());
3129
+ findLocalCodex(homedir5());
3130
+ findLocalClaude(homedir5());
2356
3131
  const readCodex = deps.probes?.codex ?? (() => probeCodex(harnessBin("codex")));
2357
3132
  const readClaude = deps.probes?.claude ?? (() => probeClaude(harnessBin("claude")));
2358
3133
  const found = await detect(
@@ -2367,19 +3142,19 @@ async function connect(argv, attempt, deps = {}) {
2367
3142
  const machine = !deps.probes;
2368
3143
  const terminal = deps.terminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
2369
3144
  const current = await prepareAgents(found, forced, workstation, {
2370
- chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir4())),
3145
+ chatGptApp: deps.chatGptApp ?? (() => machine && hasChatGptApp(homedir5())),
2371
3146
  codexHostMissing: deps.codexHostMissing ?? (() => machine && codexHostMissing(which("codex"))),
2372
- installCodex: deps.installCodex ?? (async () => machine && installCodex(homedir4())),
2373
- installClaude: deps.installClaude ?? (async () => machine && installClaude(homedir4())),
3147
+ installCodex: deps.installCodex ?? (async () => machine && installCodex(homedir5())),
3148
+ installClaude: deps.installClaude ?? (async () => machine && installClaude(homedir5())),
2374
3149
  readCodex,
2375
3150
  readClaude,
2376
3151
  updateClaude: deps.updateClaude ?? updateClaude,
2377
3152
  signInCodex: deps.signInCodex ?? (() => signInCodex(harnessBin("codex"))),
2378
3153
  signInClaude: deps.signInClaude ?? (() => signInClaude(harnessBin("claude"))),
2379
3154
  terminal,
2380
- installed: (agent, ok, reason) => {
2381
- attempt[agent === "codex" ? "codexInstall" : "claudeInstall"] = ok ? "ok" : "failed";
2382
- if (agent === "codex") attempt.codexInstallReason = reason ?? null;
3155
+ installed: (agent2, ok, reason) => {
3156
+ attempt[agent2 === "codex" ? "codexInstall" : "claudeInstall"] = ok ? "ok" : "failed";
3157
+ if (agent2 === "codex") attempt.codexInstallReason = reason ?? null;
2383
3158
  }
2384
3159
  });
2385
3160
  attempt.harnesses = harnessesFound(current);
@@ -2516,10 +3291,10 @@ function signInClaude(bin) {
2516
3291
  return runShown2([bin, "auth", "login"], true).status === 0 ? probeClaude(bin) : Promise.resolve(null);
2517
3292
  }
2518
3293
  async function claudeAtFloor(found, forced, update) {
2519
- const version2 = found.claude?.version;
3294
+ const version = found.claude?.version;
2520
3295
  const codex = forced === "codex" || !forced && !found.claude?.signedIn && Boolean(found.codex?.signedIn);
2521
- if (!version2 || codex || !olderThan(version2, CLAUDE_FLOOR)) return found;
2522
- out(`${bold("Cloop machine")} ${claudeTooOld(version2)} Updating it.`);
3296
+ if (!version || codex || !olderThan(version, CLAUDE_FLOOR)) return found;
3297
+ out(`${bold("Cloop machine")} ${claudeTooOld(version)} Updating it.`);
2523
3298
  const claude = await update();
2524
3299
  if (!claude?.version || olderThan(claude.version, CLAUDE_FLOOR))
2525
3300
  throw new ConnectFailure(
@@ -2605,8 +3380,6 @@ async function connectCommand(argv) {
2605
3380
  }
2606
3381
 
2607
3382
  export {
2608
- runnerLog,
2609
- buildDiag,
2610
3383
  classifyError,
2611
3384
  answerCall,
2612
3385
  SUBSCRIPTIONS,
@@ -2641,6 +3414,7 @@ export {
2641
3414
  endDaemonScript,
2642
3415
  programFor,
2643
3416
  findNpx,
3417
+ FIRST_CONNECT_MS,
2644
3418
  awaitDaemon,
2645
3419
  unitEnv,
2646
3420
  serviceEnv,
@@ -2671,6 +3445,13 @@ export {
2671
3445
  legacyStagingRunner,
2672
3446
  moveRunnerFiles,
2673
3447
  moveLegacyStagingRunner,
3448
+ claudeHome,
3449
+ codexHome2 as codexHome,
3450
+ TITLE_MAX,
3451
+ HOST_ID_MAX,
3452
+ CAPTURE_TICK_MS,
3453
+ captureCursorPath,
3454
+ ThreadCapture,
2674
3455
  doneLine,
2675
3456
  unitOrigin,
2676
3457
  disconnectPlan,