@cloop/runner 0.3.68 → 0.3.69

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 (30) hide show
  1. package/dist/{box-YFGM56QY.js → box-UOJ6ET2B.js} +156 -511
  2. package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
  3. package/dist/{chunk-BVPS6DCH.js → chunk-57E5WOOP.js} +574 -1673
  4. package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
  5. package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
  6. package/dist/{chunk-HWNRORIZ.js → chunk-DTUNRKBC.js} +1 -1
  7. package/dist/chunk-EEG5JOZ7.js +939 -0
  8. package/dist/chunk-GAEZIKCK.js +626 -0
  9. package/dist/chunk-HIBAH65V.js +1178 -0
  10. package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
  11. package/dist/chunk-JJWSPBM4.js +40 -0
  12. package/dist/{chunk-L7D3ANPW.js → chunk-KIYCULVE.js} +4 -2
  13. package/dist/{chunk-34VZ5LZI.js → chunk-SJAGZNFF.js} +3 -83
  14. package/dist/chunk-TPKYD3JF.js +43 -0
  15. package/dist/chunk-WCKW2Z2G.js +459 -0
  16. package/dist/chunk-ZHQSGJCE.js +85 -0
  17. package/dist/{connect-D2SXLADA.js → connect-HVOAYXWM.js} +11 -47
  18. package/dist/disconnect-DQ6WSDR7.js +163 -0
  19. package/dist/existing-runner-BSSRQFFP.js +15 -0
  20. package/dist/index.js +14 -14
  21. package/dist/{login-VNDFCJD4.js → login-4HWP4PF4.js} +3 -2
  22. package/dist/{mcp-server-XPHCDBFR.js → mcp-server-DTJVCFRG.js} +10 -10
  23. package/dist/{runner-A3HFZ727.js → runner-4XWS2RJL.js} +4 -3
  24. package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
  25. package/dist/{statusline-VA2DSWVT.js → statusline-C2FH3YQ4.js} +1 -1
  26. package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
  27. package/dist/{use-7D5GQFGB.js → use-U3E55XBK.js} +20 -13
  28. package/package.json +1 -1
  29. package/dist/disconnect-7SJKPYIN.js +0 -30
  30. package/dist/existing-runner-XT3HLIPM.js +0 -20
@@ -0,0 +1,939 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ claudeHome,
4
+ codexHome
5
+ } from "./chunk-JJWSPBM4.js";
6
+ import {
7
+ redactSecrets
8
+ } from "./chunk-DN6TQALA.js";
9
+
10
+ // src/threads/capture.ts
11
+ import {
12
+ chmodSync,
13
+ closeSync,
14
+ mkdirSync,
15
+ openSync,
16
+ readFileSync,
17
+ readSync,
18
+ renameSync,
19
+ statSync,
20
+ unlinkSync,
21
+ writeFileSync
22
+ } from "fs";
23
+ import { dirname, join as join3 } from "path";
24
+
25
+ // src/threads/claude-code.ts
26
+ import { readdirSync } from "fs";
27
+ import { join } from "path";
28
+
29
+ // src/threads/turns.ts
30
+ var TURN_TEXT_MAX = 2e4;
31
+ var TURN_ACTIONS_MAX = 100;
32
+ var COMMAND_MAX = 300;
33
+ var PATH_MAX = 1e3;
34
+ var BATCH_TURNS_MAX = 200;
35
+ var CWD_MAX = 1e3;
36
+ var BRANCH_MAX = 300;
37
+ var TITLE_MAX = 300;
38
+ var TASK_TOOL_MAX = 100;
39
+ var HOST_ID_MAX = 300;
40
+ var OWNER_TURNS_HOSTED = 1;
41
+ var OWNER_TURNS_BARE = 2;
42
+ var HOST_NOTICES = [
43
+ "Update on pull request",
44
+ "Delegated task node",
45
+ "Background command completed",
46
+ "T3 Code stopped watching",
47
+ "Note: the T3 server restarted"
48
+ ];
49
+ function isHostNotice(text) {
50
+ return HOST_NOTICES.some((prefix) => text.startsWith(prefix));
51
+ }
52
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
53
+ var COMMIT_LINE = /^\[(?:[^\]\n]+ )?([0-9a-f]{7,40})\] [^\n]*\n\s*\d+ files? changed/gm;
54
+ function foundActions(text) {
55
+ const actions = [];
56
+ for (const m of text.matchAll(PR_URL)) actions.push({ kind: "pr", url: m[0] });
57
+ for (const m of text.matchAll(COMMIT_LINE)) actions.push({ kind: "commit", sha: m[1] });
58
+ return actions;
59
+ }
60
+ function commandAction(command) {
61
+ const flat = redactSecrets(command.trim());
62
+ if (!flat) return null;
63
+ return {
64
+ kind: "command",
65
+ command: flat.length > COMMAND_MAX ? `${flat.slice(0, COMMAND_MAX - 1)}\u2026` : flat
66
+ };
67
+ }
68
+ function editAction(path) {
69
+ return typeof path === "string" && path && path.length <= PATH_MAX ? { kind: "edit", path } : null;
70
+ }
71
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
72
+ var TASK_ID_KEYS = ["lineage_id", "lineageId", "task_id", "taskId", "item_id", "itemId"];
73
+ function taskAction(tool, input) {
74
+ if (!tool || tool.length > TASK_TOOL_MAX || !isRecord(input)) return null;
75
+ const keys = /task/i.test(tool) ? [...TASK_ID_KEYS, "id"] : TASK_ID_KEYS;
76
+ for (const key of keys) {
77
+ const value = input[key];
78
+ if (typeof value === "string" && UUID.test(value))
79
+ return { kind: "task", id: value.toLowerCase(), tool };
80
+ }
81
+ return null;
82
+ }
83
+ var NONE = { kind: "none" };
84
+ var ONCE = { kind: "once" };
85
+ function pullRequest(input) {
86
+ if (typeof input.url === "string") return input.url.match(PR_URL)?.[0] ?? str(input.url);
87
+ const repo = str(input.repository);
88
+ const number = input.number;
89
+ return repo && (typeof number === "number" || typeof number === "string") ? `https://github.com/${repo}/pull/${number}` : void 0;
90
+ }
91
+ function background(input) {
92
+ return input.run_in_background === true ? ONCE : NONE;
93
+ }
94
+ var WAKE_TOOLS = {
95
+ t3_background_wait: () => ONCE,
96
+ watch_pull_request: (input) => {
97
+ const url = pullRequest(input);
98
+ return url ? { kind: "watch", url } : NONE;
99
+ },
100
+ unwatch_pull_request: (input) => {
101
+ const url = pullRequest(input);
102
+ return url ? { kind: "unwatch", url } : NONE;
103
+ },
104
+ // `{ stop: true }` ends a /loop: it cancels the wakeup instead.
105
+ ScheduleWakeup: (input) => input.stop === true ? NONE : ONCE,
106
+ Monitor: () => ONCE,
107
+ Bash: background,
108
+ Agent: background
109
+ };
110
+ function toolWake(name, input) {
111
+ const short = name.split("__").at(-1);
112
+ if (!Object.hasOwn(WAKE_TOOLS, short)) return NONE;
113
+ return WAKE_TOOLS[short](
114
+ isRecord(input) ? input : {}
115
+ );
116
+ }
117
+ function isRecord(value) {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+ function str(value) {
121
+ return typeof value === "string" && value ? value : void 0;
122
+ }
123
+
124
+ // src/threads/claude-code.ts
125
+ var UUID2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
126
+ var NOT_TYPED = [
127
+ "<local-command-",
128
+ "<task-notification>",
129
+ "<bash-",
130
+ "<user-memory-input>",
131
+ "<system-reminder>"
132
+ ];
133
+ var CLOOP_TOOL = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
134
+ var EDIT_TOOLS = {
135
+ Edit: "file_path",
136
+ Write: "file_path",
137
+ MultiEdit: "file_path",
138
+ NotebookEdit: "notebook_path"
139
+ };
140
+ function files(home) {
141
+ const root = join(home, "projects");
142
+ const out = [];
143
+ for (const project of safeDir(root)) {
144
+ if (!project.isDirectory()) continue;
145
+ for (const entry of safeDir(join(root, project.name))) {
146
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
147
+ const sessionId = entry.name.slice(0, -6);
148
+ if (UUID2.test(sessionId)) out.push({ path: join(root, project.name, entry.name), sessionId });
149
+ }
150
+ }
151
+ return out;
152
+ }
153
+ function safeDir(dir) {
154
+ try {
155
+ return readdirSync(dir, { withFileTypes: true });
156
+ } catch {
157
+ return [];
158
+ }
159
+ }
160
+ function typedText(content) {
161
+ 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") : "";
162
+ const trimmed = text.trim();
163
+ if (!trimmed) return null;
164
+ const command = /<command-name>([^<]*)<\/command-name>/.exec(trimmed);
165
+ if (command) {
166
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(trimmed)?.[1] ?? "";
167
+ return `${command[1]?.trim()} ${args.trim()}`.trim();
168
+ }
169
+ if (trimmed.startsWith("<command-message>")) return null;
170
+ return NOT_TYPED.some((prefix) => trimmed.startsWith(prefix)) || isHostNotice(trimmed) ? null : trimmed;
171
+ }
172
+ function resultText(block) {
173
+ const content = block.content;
174
+ if (typeof content === "string") return content;
175
+ if (!Array.isArray(content)) return "";
176
+ return content.filter((b) => isRecord(b) && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
177
+ }
178
+ function userSignals(r, at) {
179
+ const content = isRecord(r.message) ? r.message.content : void 0;
180
+ if (Array.isArray(content) && content.some((b) => isRecord(b) && b.type === "tool_result")) {
181
+ const actions = content.filter(isRecord).filter((b) => b.type === "tool_result").flatMap((b) => foundActions(resultText(b)));
182
+ return actions.length ? [{ kind: "agent", at, actions }] : [];
183
+ }
184
+ if (r.isMeta === true || r.isCompactSummary === true || r.origin !== void 0) return [];
185
+ const text = typedText(content);
186
+ return text ? [{ kind: "owner", at, text }] : [];
187
+ }
188
+ function toolAction(block) {
189
+ const name = str(block.name);
190
+ const input = isRecord(block.input) ? block.input : {};
191
+ if (!name) return null;
192
+ const field = EDIT_TOOLS[name];
193
+ if (field) return editAction(input[field]);
194
+ if (name === "Bash" && typeof input.command === "string") return commandAction(input.command);
195
+ const cloop = CLOOP_TOOL.exec(name);
196
+ return cloop ? taskAction(cloop[1], input) : null;
197
+ }
198
+ function assistantSignals(r, at) {
199
+ const message = isRecord(r.message) ? r.message : {};
200
+ const blocks = Array.isArray(message.content) ? message.content.filter(isRecord) : [];
201
+ const text = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n\n").trim();
202
+ const uses = blocks.filter((b) => b.type === "tool_use");
203
+ const actions = [
204
+ ...uses.map(toolAction).filter((a) => a !== null),
205
+ ...foundActions(text)
206
+ ];
207
+ const calls = uses.map((b) => toolWake(str(b.name) ?? "", b.input));
208
+ const signals = [];
209
+ if (text || actions.length || calls.length)
210
+ signals.push({
211
+ kind: "agent",
212
+ at,
213
+ ...text ? { text } : {},
214
+ ...actions.length ? { actions } : {},
215
+ ...calls.length ? { calls } : {}
216
+ });
217
+ const stop = message.stop_reason;
218
+ if (text && (stop === "end_turn" || stop === "stop_sequence")) signals.push({ kind: "end", at });
219
+ return signals;
220
+ }
221
+ function parse(record) {
222
+ if (!isRecord(record) || record.isSidechain === true) return [];
223
+ const signals = [];
224
+ const cwd = str(record.cwd);
225
+ const branch = str(record.gitBranch);
226
+ if (cwd || branch)
227
+ signals.push({ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} });
228
+ const at = str(record.timestamp);
229
+ switch (record.type) {
230
+ case "user":
231
+ if (at) signals.push(...userSignals(record, at));
232
+ break;
233
+ case "assistant":
234
+ if (at) signals.push(...assistantSignals(record, at));
235
+ break;
236
+ case "pr-link": {
237
+ const url = str(record.prUrl);
238
+ if (at && url) signals.push({ kind: "agent", at, actions: foundActions(url) });
239
+ break;
240
+ }
241
+ case "summary":
242
+ case "ai-title": {
243
+ const title = str(record.summary) ?? str(record.aiTitle);
244
+ if (title) signals.push({ kind: "thread", title });
245
+ break;
246
+ }
247
+ case "custom-title": {
248
+ const customTitle = str(record.customTitle);
249
+ if (customTitle) signals.push({ kind: "thread", customTitle });
250
+ break;
251
+ }
252
+ }
253
+ return signals;
254
+ }
255
+ var claudeCodeLogs = { home: claudeHome, files, parse };
256
+
257
+ // src/threads/codex.ts
258
+ import { readdirSync as readdirSync2 } from "fs";
259
+ import { join as join2 } from "path";
260
+ 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;
261
+ var INJECTED = [
262
+ "<environment_context",
263
+ "<user_instructions",
264
+ "# AGENTS.md instructions",
265
+ "<INSTRUCTIONS>",
266
+ "<skill>",
267
+ "<recommended_plugins",
268
+ "<permissions instructions",
269
+ "<turn_aborted",
270
+ "<user_shell_command",
271
+ "<subagent_notification",
272
+ "<model_switch",
273
+ "[Historical user",
274
+ "Context handoff"
275
+ ];
276
+ function files2(home) {
277
+ const out = [];
278
+ const walk = (dir, depth) => {
279
+ for (const entry of safeDir2(dir)) {
280
+ const path = join2(dir, entry.name);
281
+ if (entry.isDirectory() && depth < 3) walk(path, depth + 1);
282
+ else if (entry.isFile() && depth === 3) {
283
+ const m = ROLLOUT.exec(entry.name);
284
+ if (m) out.push({ path, sessionId: m[1].toLowerCase() });
285
+ }
286
+ }
287
+ };
288
+ walk(join2(home, "sessions"), 0);
289
+ return out;
290
+ }
291
+ function safeDir2(dir) {
292
+ try {
293
+ return readdirSync2(dir, { withFileTypes: true });
294
+ } catch {
295
+ return [];
296
+ }
297
+ }
298
+ function blockText(content, type) {
299
+ if (!Array.isArray(content)) return "";
300
+ return content.filter((b) => isRecord(b) && b.type === type && typeof b.text === "string").map((b) => b.text).join("\n").trim();
301
+ }
302
+ function ownerText(r, p) {
303
+ const meta = isRecord(r.metadata) ? r.metadata : {};
304
+ if (meta.inherited_user_message === true) return null;
305
+ const passthrough = isRecord(p.internal_chat_message_metadata_passthrough) ? p.internal_chat_message_metadata_passthrough : {};
306
+ const kinds = passthrough.content_item_kinds;
307
+ if (Array.isArray(kinds) && kinds.some((k) => typeof k !== "string" || !k.startsWith("user.")))
308
+ return null;
309
+ const text = blockText(p.content, "input_text");
310
+ if (!text || INJECTED.some((prefix) => text.startsWith(prefix)) || isHostNotice(text))
311
+ return null;
312
+ return text;
313
+ }
314
+ function commandText(command) {
315
+ if (typeof command === "string") return command;
316
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return null;
317
+ const argv = command;
318
+ if (argv.length >= 3 && (argv[1] === "-lc" || argv[1] === "-c")) return argv[2];
319
+ return argv.join(" ");
320
+ }
321
+ function patchedPaths(patch) {
322
+ return [...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => editAction(m[1]?.trim())).filter((a) => a !== null);
323
+ }
324
+ function scriptCommands(script) {
325
+ const out = [];
326
+ for (const m of script.matchAll(
327
+ /tools\.exec_command\(\s*\{\s*"?cmd"?\s*:\s*("(?:[^"\\]|\\.)*")/g
328
+ )) {
329
+ try {
330
+ const action = commandAction(JSON.parse(m[1]));
331
+ if (action) out.push(action);
332
+ } catch {
333
+ }
334
+ }
335
+ return [...out, ...patchedPaths(script)];
336
+ }
337
+ var CLOOP_SERVER = /^cloop(?:[-_]staging)?$/;
338
+ var CLOOP_FUNCTION = /^mcp__cloop(?:[-_]staging)?__(.+)$/;
339
+ function mcpTaskAction(call) {
340
+ const server = str(call.server);
341
+ const tool = str(call.tool);
342
+ if (!server || !tool || !CLOOP_SERVER.test(server)) return [];
343
+ const args = typeof call.arguments === "string" ? parseArgs(call.arguments) : call.arguments;
344
+ const action = taskAction(tool, args);
345
+ return action ? [action] : [];
346
+ }
347
+ function mcpWake(call) {
348
+ return toolWake(
349
+ str(call.tool) ?? "",
350
+ typeof call.arguments === "string" ? parseArgs(call.arguments) : call.arguments
351
+ );
352
+ }
353
+ function parseArgs(raw) {
354
+ if (typeof raw !== "string") return {};
355
+ try {
356
+ const parsed = JSON.parse(raw);
357
+ return isRecord(parsed) ? parsed : {};
358
+ } catch {
359
+ return {};
360
+ }
361
+ }
362
+ function callActions(p) {
363
+ const name = str(p.name);
364
+ if (p.type === "local_shell_call") {
365
+ const action = isRecord(p.action) ? commandText(p.action.command) : null;
366
+ const command = action ? commandAction(action) : null;
367
+ return command ? [command] : [];
368
+ }
369
+ if (p.type === "custom_tool_call") {
370
+ const input = typeof p.input === "string" ? p.input : "";
371
+ if (name === "apply_patch") return patchedPaths(input);
372
+ if (name === "exec") return scriptCommands(input);
373
+ return [];
374
+ }
375
+ const args = parseArgs(p.arguments);
376
+ if (name === "shell" || name === "container.exec" || name === "exec_command") {
377
+ const text = commandText(args.command ?? args.cmd);
378
+ const command = text ? commandAction(text) : null;
379
+ return command ? [command] : [];
380
+ }
381
+ if (name === "apply_patch" && typeof args.input === "string") return patchedPaths(args.input);
382
+ const cloop = name ? CLOOP_FUNCTION.exec(name) : null;
383
+ const task = cloop ? taskAction(cloop[1], args) : null;
384
+ return task ? [task] : [];
385
+ }
386
+ function outputText(output) {
387
+ if (typeof output === "string") return output;
388
+ if (isRecord(output) && typeof output.content === "string") return output.content;
389
+ if (Array.isArray(output))
390
+ return output.filter((b) => isRecord(b) && typeof b.text === "string").map((b) => b.text).join("\n");
391
+ return "";
392
+ }
393
+ function changedPaths(changes) {
394
+ return isRecord(changes) ? Object.keys(changes).map(editAction).filter((a) => a !== null) : [];
395
+ }
396
+ function itemActions(item) {
397
+ if (item.type === "FileChange") return changedPaths(item.changes);
398
+ if (item.type === "McpToolCall") return mcpTaskAction(item);
399
+ if (item.type === "CommandExecution") {
400
+ const text = commandText(item.command);
401
+ const command = text ? commandAction(text) : null;
402
+ const stdout = typeof item.stdout === "string" ? foundActions(item.stdout) : [];
403
+ return [...command ? [command] : [], ...stdout];
404
+ }
405
+ return [];
406
+ }
407
+ function agent(at, actions, calls = []) {
408
+ return actions.length || calls.length ? [{ kind: "agent", at, actions, ...calls.length ? { calls } : {} }] : [];
409
+ }
410
+ function responseItem(r, p, at) {
411
+ switch (p.type) {
412
+ case "message": {
413
+ if (p.role === "user") {
414
+ const text2 = ownerText(r, p);
415
+ return text2 ? [{ kind: "owner", at, text: text2 }] : [];
416
+ }
417
+ if (p.role !== "assistant") return [];
418
+ const text = blockText(p.content, "output_text");
419
+ if (!text) return [];
420
+ const found = foundActions(text);
421
+ return [{ kind: "agent", at, text, ...found.length ? { actions: found } : {} }];
422
+ }
423
+ case "function_call":
424
+ case "custom_tool_call":
425
+ case "local_shell_call":
426
+ return agent(at, callActions(p), [toolWake(str(p.name) ?? "", parseArgs(p.arguments))]);
427
+ case "function_call_output":
428
+ case "custom_tool_call_output":
429
+ return agent(at, foundActions(outputText(p.output)));
430
+ default:
431
+ return [];
432
+ }
433
+ }
434
+ function eventMsg(p, at) {
435
+ switch (p.type) {
436
+ case "task_complete":
437
+ case "turn_aborted":
438
+ return [{ kind: "end", at }];
439
+ case "mcp_tool_call_end":
440
+ return isRecord(p.invocation) ? agent(at, mcpTaskAction(p.invocation), [mcpWake(p.invocation)]) : [];
441
+ case "patch_apply_end":
442
+ return agent(at, changedPaths(p.changes));
443
+ case "item_completed":
444
+ if (!isRecord(p.item)) return [];
445
+ return agent(at, itemActions(p.item), p.item.type === "McpToolCall" ? [mcpWake(p.item)] : []);
446
+ default:
447
+ return [];
448
+ }
449
+ }
450
+ function parse2(record) {
451
+ if (!isRecord(record) || !isRecord(record.payload)) return [];
452
+ const p = record.payload;
453
+ const at = str(record.timestamp);
454
+ switch (record.type) {
455
+ case "session_meta": {
456
+ const source = isRecord(p.source) ? p.source : {};
457
+ if (p.parent_thread_id || source.subagent) return [{ kind: "subagent" }];
458
+ const git = isRecord(p.git) ? p.git : {};
459
+ const cwd = str(p.cwd);
460
+ const branch = str(git.branch);
461
+ return [{ kind: "thread", ...cwd ? { cwd } : {}, ...branch ? { branch } : {} }];
462
+ }
463
+ case "turn_context": {
464
+ const cwd = str(p.cwd);
465
+ return cwd ? [{ kind: "thread", cwd }] : [];
466
+ }
467
+ case "response_item":
468
+ return at ? responseItem(record, p, at) : [];
469
+ case "event_msg":
470
+ return at ? eventMsg(p, at) : [];
471
+ default:
472
+ return [];
473
+ }
474
+ }
475
+ var codexLogs = { home: codexHome, files: files2, parse: parse2 };
476
+
477
+ // src/threads/capture.ts
478
+ var CLOOP_OPENERS = [
479
+ "You are working on a Task from the user's Cloop.",
480
+ "You are running a Routine for the user, from their Cloop."
481
+ ];
482
+ var HARNESS_LOGS = {
483
+ "claude-code": claudeCodeLogs,
484
+ codex: codexLogs
485
+ };
486
+ var CAPTURE_TICK_MS = 6e4;
487
+ var TICK_READ_BYTES = 2 * 1024 * 1024;
488
+ var TICK_TURNS = 500;
489
+ var BASE_SLACK_BYTES = 256 * 1024;
490
+ var PROBE_LINES = 50;
491
+ var REPLY_IDLE_MS = 10 * 6e4;
492
+ var GATE_OFF_PAUSE_MS = 60 * 6e4;
493
+ var BODY_BYTES_MAX = 512 * 1024;
494
+ var READ_CHUNK = 1024 * 1024;
495
+ function captureCursorPath(threadsFile) {
496
+ return join3(dirname(threadsFile), "thread-capture.json");
497
+ }
498
+ var ThreadCapture = class {
499
+ constructor(deps) {
500
+ this.deps = deps;
501
+ }
502
+ deps;
503
+ running = false;
504
+ pausedUntil = 0;
505
+ /** One tick. Null when nothing ran: opted out, paused, or a tick already running. */
506
+ async tick() {
507
+ if (this.running) return null;
508
+ this.running = true;
509
+ try {
510
+ return await this.run();
511
+ } finally {
512
+ this.running = false;
513
+ }
514
+ }
515
+ now() {
516
+ return this.deps.now?.() ?? Date.now();
517
+ }
518
+ async run() {
519
+ const now = this.now();
520
+ if (now < this.pausedUntil) return null;
521
+ const state = load(this.deps.cursorFile) ?? {
522
+ startedAt: new Date(now).toISOString(),
523
+ files: {}
524
+ };
525
+ const since = Date.parse(state.startedAt);
526
+ const own = new Set(await (this.deps.ownSessions?.() ?? Promise.resolve([])).catch(() => []));
527
+ const hosts = await (this.deps.hostThreads?.() ?? Promise.resolve(/* @__PURE__ */ new Map())).catch(() => /* @__PURE__ */ new Map());
528
+ const listed = /* @__PURE__ */ new Set();
529
+ const candidates = [];
530
+ for (const [harness, logs] of Object.entries(HARNESS_LOGS)) {
531
+ for (const file of logs.files(logs.home())) {
532
+ listed.add(file.path);
533
+ const info = statOrNull(file.path);
534
+ if (!info || info.mtimeMs < since) continue;
535
+ candidates.push({
536
+ ...file,
537
+ harness,
538
+ logs,
539
+ ino: info.ino,
540
+ size: info.size,
541
+ mtimeMs: info.mtimeMs
542
+ });
543
+ }
544
+ }
545
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
546
+ for (const file of candidates) {
547
+ const known = state.files[file.path];
548
+ if (!(known && known.ino === file.ino && file.size >= known.offset))
549
+ state.files[file.path] = freshCursor(file, since);
550
+ }
551
+ const budget = { bytes: TICK_READ_BYTES, turns: TICK_TURNS };
552
+ const outgoing = [];
553
+ for (const file of candidates) {
554
+ if (budget.bytes <= 0 || budget.turns <= 0) break;
555
+ const known = state.files[file.path];
556
+ const cursor = structuredClone(known);
557
+ const host = hosts.get(file.sessionId);
558
+ if (own.has(file.sessionId)) cursor.verdict = "cloop";
559
+ const need = host ? OWNER_TURNS_HOSTED : OWNER_TURNS_BARE;
560
+ if (cursor.verdict === "pending" && cursor.ownerTurns >= need) becomeOwner(cursor);
561
+ const idle = now - file.mtimeMs >= REPLY_IDLE_MS;
562
+ const metaOf = () => threadMeta(cursor.thread, host);
563
+ const liveToSend = () => {
564
+ const current = cursor.verdict === "owner" ? hostedLive(cursor.live, host) : void 0;
565
+ return current && Date.parse(current.at) >= since && !sameLive(current, known?.sentLive ?? known?.live) ? current : void 0;
566
+ };
567
+ if (cursor.verdict === "cloop" || cursor.verdict === "subagent" || file.size === cursor.offset && !(cursor.open && idle) && !(cursor.verdict === "owner" && JSON.stringify(metaOf()) !== cursor.sentMeta) && !liveToSend()) {
568
+ state.files[file.path] = cursor;
569
+ continue;
570
+ }
571
+ const turns = [];
572
+ const consumedAll = readInto(file, cursor, budget, turns, need);
573
+ if (consumedAll && cursor.verdict === "owner" && cursor.open && idle) close(cursor, turns);
574
+ const meta = metaOf();
575
+ const metaKey = JSON.stringify(meta);
576
+ const metaChanged = cursor.verdict === "owner" && metaKey !== cursor.sentMeta;
577
+ const send = turns.filter((t) => Date.parse(t.at) >= since);
578
+ budget.turns -= send.length;
579
+ const live = liveToSend();
580
+ if (send.length === 0 && !live && !metaChanged) state.files[file.path] = cursor;
581
+ else
582
+ outgoing.push({
583
+ path: file.path,
584
+ next: { ...cursor, sentMeta: metaKey, ...live ? { sentLive: live } : {} },
585
+ batch: {
586
+ harness: file.harness,
587
+ session_id: file.sessionId,
588
+ thread: meta,
589
+ turns: send,
590
+ ...live ? { live } : {}
591
+ }
592
+ });
593
+ }
594
+ const report = {
595
+ sessionsSeen: candidates.length,
596
+ sessionsSent: 0,
597
+ sessionsCloop: candidates.filter((f) => state.files[f.path]?.verdict === "cloop").length,
598
+ sessionsSubagent: candidates.filter((f) => state.files[f.path]?.verdict === "subagent").length,
599
+ turns: 0,
600
+ dropped: 0,
601
+ bytes: 0,
602
+ readBytes: TICK_READ_BYTES - budget.bytes,
603
+ status: null
604
+ };
605
+ for (const out of outgoing) {
606
+ const result = await this.send(out.batch, report);
607
+ if (result.ok || result.drop) state.files[out.path] = out.next;
608
+ if (result.ok) {
609
+ report.sessionsSent++;
610
+ report.turns += out.batch.turns.length;
611
+ report.status = 200;
612
+ continue;
613
+ }
614
+ report.status = result.status;
615
+ if (result.drop) {
616
+ report.dropped += out.batch.turns.length;
617
+ continue;
618
+ }
619
+ if (result.status === 403) this.pausedUntil = now + GATE_OFF_PAUSE_MS;
620
+ break;
621
+ }
622
+ for (const path of Object.keys(state.files)) if (!listed.has(path)) delete state.files[path];
623
+ if (report.status === 403) forget(this.deps.cursorFile);
624
+ else save(this.deps.cursorFile, state);
625
+ if (outgoing.length)
626
+ this.deps.log(
627
+ `[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}`
628
+ );
629
+ return report;
630
+ }
631
+ /** Every chunk of one session's turns. A 400 or 413 is a refusal for good: the cursor moves on. */
632
+ async send(batch, report) {
633
+ for (const chunk of chunks(batch)) {
634
+ const body = JSON.stringify(chunk);
635
+ let res;
636
+ try {
637
+ res = await (this.deps.fetchFn ?? fetch)(
638
+ `${this.deps.origin}/api/agent/mesh/thread-turns`,
639
+ {
640
+ method: "POST",
641
+ headers: {
642
+ "content-type": "application/json",
643
+ authorization: `Bearer ${this.deps.deviceToken()}`
644
+ },
645
+ body,
646
+ signal: AbortSignal.timeout(3e4)
647
+ }
648
+ );
649
+ } catch {
650
+ return { ok: false, status: "unreachable", drop: false };
651
+ }
652
+ if (!res.ok) {
653
+ return { ok: false, status: res.status, drop: res.status === 400 || res.status === 413 };
654
+ }
655
+ report.bytes += Buffer.byteLength(body);
656
+ }
657
+ return { ok: true };
658
+ }
659
+ };
660
+ function freshCursor(file, since) {
661
+ const base = baseFor(file.path, file.size, since);
662
+ return {
663
+ harness: file.harness,
664
+ sessionId: file.sessionId,
665
+ ino: file.ino,
666
+ offset: 0,
667
+ ...base ? { base } : {},
668
+ seq: 0,
669
+ ownerTurns: 0,
670
+ verdict: "pending",
671
+ thread: {}
672
+ };
673
+ }
674
+ function baseFor(path, size, since) {
675
+ let lo = 0;
676
+ let hi = size;
677
+ while (hi - lo > BASE_SLACK_BYTES) {
678
+ const mid = lo + Math.floor((hi - lo) / 2);
679
+ const probe = datedLineAt(path, mid, hi);
680
+ if (!probe || probe.at >= since) hi = mid;
681
+ else lo = probe.end;
682
+ }
683
+ return lo === 0 ? 0 : lineStartAtOrAfter(path, lo, size);
684
+ }
685
+ function datedLineAt(path, pos, limit) {
686
+ let lines = 0;
687
+ for (const { line, end } of completeLines(path, lineStartAtOrAfter(path, pos, limit), limit)) {
688
+ if (++lines > PROBE_LINES) return null;
689
+ let at = Number.NaN;
690
+ try {
691
+ const record = JSON.parse(line);
692
+ if (isRecord(record) && typeof record.timestamp === "string")
693
+ at = Date.parse(record.timestamp);
694
+ } catch {
695
+ }
696
+ if (!Number.isNaN(at)) return { at, end };
697
+ }
698
+ return null;
699
+ }
700
+ function lineStartAtOrAfter(path, pos, size) {
701
+ if (pos <= 0) return 0;
702
+ const fd = openSync(path, "r");
703
+ try {
704
+ for (let at = pos - 1; at < size; at += READ_CHUNK) {
705
+ const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - at));
706
+ const n = readSync(fd, chunk, 0, chunk.length, at);
707
+ if (n <= 0) break;
708
+ const nl = chunk.subarray(0, n).indexOf(10);
709
+ if (nl !== -1) return at + nl + 1;
710
+ }
711
+ return size;
712
+ } finally {
713
+ closeSync(fd);
714
+ }
715
+ }
716
+ function becomeOwner(cursor) {
717
+ const base = cursor.base ?? 0;
718
+ Object.assign(cursor, { offset: base, seq: base, ownerTurns: 0, verdict: "owner" });
719
+ cursor.open = void 0;
720
+ cursor.live = void 0;
721
+ }
722
+ function readInto(file, cursor, budget, out, need) {
723
+ for (; ; ) {
724
+ let restart = false;
725
+ for (const { line, end } of completeLines(file.path, cursor.offset, file.size)) {
726
+ if (budget.bytes <= 0 || out.length >= budget.turns) return false;
727
+ budget.bytes -= end - cursor.offset;
728
+ cursor.offset = end;
729
+ let record;
730
+ try {
731
+ record = JSON.parse(line);
732
+ } catch {
733
+ continue;
734
+ }
735
+ fold(cursor, file.logs.parse(record), out);
736
+ if (cursor.verdict === "cloop" || cursor.verdict === "subagent") return false;
737
+ if (cursor.verdict === "pending" && cursor.ownerTurns >= need) {
738
+ becomeOwner(cursor);
739
+ restart = true;
740
+ break;
741
+ }
742
+ }
743
+ if (!restart) return true;
744
+ }
745
+ }
746
+ function* completeLines(path, from, size) {
747
+ const fd = openSync(path, "r");
748
+ try {
749
+ let pos = from;
750
+ let carry = Buffer.alloc(0);
751
+ while (pos < size) {
752
+ const chunk = Buffer.alloc(Math.min(READ_CHUNK, size - pos));
753
+ const n = readSync(fd, chunk, 0, chunk.length, pos);
754
+ if (n <= 0) break;
755
+ pos += n;
756
+ const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
757
+ const base = pos - data.length;
758
+ let start = 0;
759
+ for (let nl = data.indexOf(10, start); nl !== -1; nl = data.indexOf(10, start)) {
760
+ yield { line: data.toString("utf8", start, nl), end: base + nl + 1 };
761
+ start = nl + 1;
762
+ }
763
+ carry = Buffer.from(data.subarray(start));
764
+ }
765
+ } finally {
766
+ closeSync(fd);
767
+ }
768
+ }
769
+ function clip(text) {
770
+ return text.length > TURN_TEXT_MAX ? `${text.slice(0, TURN_TEXT_MAX - 1)}\u2026` : text;
771
+ }
772
+ function close(cursor, out) {
773
+ const open = cursor.open;
774
+ if (!open) return;
775
+ out.push({ seq: open.seq, at: open.at, role: "agent", text: open.text, actions: open.actions });
776
+ cursor.open = void 0;
777
+ }
778
+ function addAction(turn, action) {
779
+ if (turn.actions.length >= TURN_ACTIONS_MAX) return;
780
+ const key = JSON.stringify(action);
781
+ if (!turn.actions.some((a) => JSON.stringify(a) === key)) turn.actions.push(action);
782
+ }
783
+ function follow(cursor, call) {
784
+ cursor.wakeArmed = call.kind === "once";
785
+ if (call.kind !== "watch" && call.kind !== "unwatch") return;
786
+ const others = (cursor.watching ?? []).filter((url) => url !== call.url);
787
+ cursor.watching = call.kind === "watch" ? [...others, call.url] : others;
788
+ }
789
+ function fold(cursor, signals, out) {
790
+ for (const signal of signals) {
791
+ switch (signal.kind) {
792
+ case "subagent":
793
+ cursor.verdict = "subagent";
794
+ return;
795
+ case "thread":
796
+ if (signal.cwd) cursor.thread.cwd = signal.cwd;
797
+ if (signal.branch) cursor.thread.branch = signal.branch;
798
+ if (signal.title) cursor.thread.title = signal.title;
799
+ if (signal.customTitle) cursor.thread.customTitle = signal.customTitle;
800
+ break;
801
+ case "owner":
802
+ cursor.live = { at: signal.at, state: "working" };
803
+ cursor.wakeArmed = false;
804
+ cursor.ownerTurns++;
805
+ if (cursor.ownerTurns === 1 && CLOOP_OPENERS.some((o) => signal.text.startsWith(o))) {
806
+ cursor.verdict = "cloop";
807
+ return;
808
+ }
809
+ if (!cursor.thread.firstAsk) {
810
+ const ask = askTitle(signal.text);
811
+ if (ask) cursor.thread.firstAsk = ask;
812
+ }
813
+ if (cursor.verdict !== "owner") break;
814
+ close(cursor, out);
815
+ out.push({
816
+ seq: cursor.seq++,
817
+ at: signal.at,
818
+ role: "owner",
819
+ text: clip(redactSecrets(signal.text)),
820
+ actions: []
821
+ });
822
+ break;
823
+ case "agent": {
824
+ for (const call of signal.calls ?? []) follow(cursor, call);
825
+ if (!signal.text && !signal.actions?.length) break;
826
+ if (signal.text || signal.calls?.length) cursor.live = { at: signal.at, state: "working" };
827
+ if (cursor.verdict !== "owner") break;
828
+ if (!cursor.open) cursor.open = { seq: cursor.seq++, at: signal.at, text: "", actions: [] };
829
+ const open = cursor.open;
830
+ if (signal.text) {
831
+ const said = redactSecrets(signal.text);
832
+ open.text = clip(open.text ? `${open.text}
833
+
834
+ ${said}` : said);
835
+ }
836
+ for (const action of signal.actions ?? []) addAction(open, action);
837
+ break;
838
+ }
839
+ case "end": {
840
+ const at = signal.at ?? cursor.live?.at;
841
+ const waits = cursor.wakeArmed || (cursor.watching?.length ?? 0) > 0;
842
+ if (at) cursor.live = { at, state: waits ? "waiting" : "your_turn" };
843
+ cursor.wakeArmed = false;
844
+ if (cursor.verdict === "owner") close(cursor, out);
845
+ break;
846
+ }
847
+ }
848
+ }
849
+ }
850
+ var ASK_TITLE_MAX = 80;
851
+ function askTitle(text) {
852
+ const line = redactSecrets(text).split("\n").map((l) => l.replace(/\s+/g, " ").trim()).find((l) => l && !/^\/\S+$/.test(l));
853
+ if (!line) return void 0;
854
+ if (line.length <= ASK_TITLE_MAX) return line;
855
+ const cut = line.slice(0, ASK_TITLE_MAX - 1);
856
+ const space = cut.lastIndexOf(" ");
857
+ return `${space > ASK_TITLE_MAX / 2 ? cut.slice(0, space) : cut}\u2026`;
858
+ }
859
+ function threadMeta(thread, host) {
860
+ const title = host?.title ?? thread.customTitle ?? thread.title ?? thread.firstAsk;
861
+ return {
862
+ ...thread.cwd ? { cwd: thread.cwd.slice(0, CWD_MAX) } : {},
863
+ ...thread.branch ? { branch: thread.branch.slice(0, BRANCH_MAX) } : {},
864
+ ...title ? { title: title.slice(0, TITLE_MAX) } : {},
865
+ ...host?.delegated ? { delegated: true } : {},
866
+ ...host ? {
867
+ host: host.host,
868
+ host_thread_id: host.threadId,
869
+ ...host.parentId ? { host_parent_id: host.parentId } : {},
870
+ settled: host.settled
871
+ } : {}
872
+ };
873
+ }
874
+ function hostedLive(live, host) {
875
+ if (!live || !host?.state) return live;
876
+ if (host.state === "your_turn") return { at: live.at, state: "your_turn" };
877
+ if (live.state === "working") return live;
878
+ return { at: live.at, state: "waiting" };
879
+ }
880
+ function sameLive(a, b) {
881
+ return a?.at === b?.at && a?.state === b?.state;
882
+ }
883
+ function* chunks(batch) {
884
+ const { live, ...rest } = batch;
885
+ let turns = [];
886
+ let bytes = 0;
887
+ for (const turn of batch.turns) {
888
+ const size = Buffer.byteLength(JSON.stringify(turn));
889
+ if (turns.length && (turns.length >= BATCH_TURNS_MAX || bytes + size > BODY_BYTES_MAX)) {
890
+ yield { ...rest, turns };
891
+ turns = [];
892
+ bytes = 0;
893
+ }
894
+ turns.push(turn);
895
+ bytes += size;
896
+ }
897
+ yield { ...rest, turns, ...live ? { live } : {} };
898
+ }
899
+ function statOrNull(path) {
900
+ try {
901
+ return statSync(path);
902
+ } catch {
903
+ return null;
904
+ }
905
+ }
906
+ function load(file) {
907
+ try {
908
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
909
+ if (typeof raw.startedAt !== "string" || Number.isNaN(Date.parse(raw.startedAt))) return null;
910
+ return {
911
+ startedAt: raw.startedAt,
912
+ files: typeof raw.files === "object" && raw.files ? raw.files : {}
913
+ };
914
+ } catch {
915
+ return null;
916
+ }
917
+ }
918
+ function save(file, state) {
919
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
920
+ const tmp = `${file}.tmp`;
921
+ writeFileSync(tmp, `${JSON.stringify(state)}
922
+ `, { mode: 384 });
923
+ chmodSync(tmp, 384);
924
+ renameSync(tmp, file);
925
+ }
926
+ function forget(file) {
927
+ try {
928
+ unlinkSync(file);
929
+ } catch {
930
+ }
931
+ }
932
+
933
+ export {
934
+ TITLE_MAX,
935
+ HOST_ID_MAX,
936
+ CAPTURE_TICK_MS,
937
+ captureCursorPath,
938
+ ThreadCapture
939
+ };