@cloop/runner 0.3.31 → 0.3.34

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.
@@ -239,6 +239,199 @@ function stamp(now) {
239
239
  return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
240
240
  }
241
241
 
242
+ // src/outside-sessions.ts
243
+ import { createReadStream } from "fs";
244
+ import { readFile, readdir, stat } from "fs/promises";
245
+ import { homedir as homedir2 } from "os";
246
+ import { dirname as dirname3, join as join4 } from "path";
247
+ import { createInterface } from "readline";
248
+ var seen = /* @__PURE__ */ new Map();
249
+ var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
250
+ async function listOutsideSessions(root = join4(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
251
+ const files = [];
252
+ for (const project of await readdir(root, { withFileTypes: true }).catch(() => [])) {
253
+ if (!project.isDirectory()) continue;
254
+ for (const entry of await readdir(join4(root, project.name), { withFileTypes: true }).catch(
255
+ () => []
256
+ )) {
257
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
258
+ const id = entry.name.slice(0, -6);
259
+ if (!UUID.test(id) || own.has(id)) continue;
260
+ const path = join4(root, project.name, entry.name);
261
+ const info = await stat(path).catch(() => null);
262
+ if (info && info.mtimeMs >= now - 7 * 864e5)
263
+ files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
264
+ }
265
+ }
266
+ const results = [];
267
+ const newest = files.sort((a, b) => b.mtime - a.mtime).slice(0, 20);
268
+ for (const path of seen.keys()) if (!newest.some((file) => file.file === path)) seen.delete(path);
269
+ for (const file of newest) {
270
+ const { title, cwd } = await claudeMeta(file.file, file.mtime);
271
+ results.push({
272
+ id: file.id,
273
+ project: file.project,
274
+ updatedAt: new Date(file.mtime).toISOString(),
275
+ status: "idle",
276
+ ...cwd ? { cwd } : {},
277
+ ...title ? { title } : {}
278
+ });
279
+ }
280
+ return results;
281
+ }
282
+ async function claudeMeta(file, mtime) {
283
+ const known = seen.get(file);
284
+ if (known?.mtime === mtime) return known;
285
+ let title;
286
+ let cwd;
287
+ const stream = createReadStream(file, { encoding: "utf8" });
288
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
289
+ try {
290
+ for await (const line of lines) {
291
+ if (!cwd && line.includes('"cwd"')) {
292
+ try {
293
+ const record = JSON.parse(line);
294
+ if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
295
+ cwd = record.cwd;
296
+ } catch {
297
+ }
298
+ }
299
+ if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
300
+ try {
301
+ const record = JSON.parse(line);
302
+ const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
303
+ if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
304
+ } catch {
305
+ }
306
+ }
307
+ } finally {
308
+ lines.close();
309
+ stream.destroy();
310
+ }
311
+ const meta = { mtime, ...title ? { title } : {}, ...cwd ? { cwd } : {} };
312
+ seen.set(file, meta);
313
+ return meta;
314
+ }
315
+ function sessionRoots(home = homedir2()) {
316
+ return { claude: join4(home, ".claude", "projects"), codex: join4(home, ".codex", "sessions") };
317
+ }
318
+ async function findSession(id, roots, harnesses) {
319
+ if (!UUID.test(id)) return null;
320
+ if (harnesses.includes("claude-code")) {
321
+ for (const project of await readdir(roots.claude, { withFileTypes: true }).catch(() => [])) {
322
+ if (!project.isDirectory()) continue;
323
+ const file = join4(roots.claude, project.name, `${id}.jsonl`);
324
+ const info = await stat(file).catch(() => null);
325
+ if (!info?.isFile()) continue;
326
+ const meta = await claudeMeta(file, info.mtimeMs);
327
+ return {
328
+ harness: "claude-code",
329
+ id,
330
+ cwd: meta.cwd ?? null,
331
+ ...meta.title ? { title: meta.title } : {},
332
+ mtime: info.mtimeMs
333
+ };
334
+ }
335
+ }
336
+ if (harnesses.includes("codex")) {
337
+ const file = (await codexFiles(roots.codex)).find((f) => f.id === id);
338
+ if (file) {
339
+ const meta = await codexMeta(file.file, file.mtime);
340
+ if (meta?.id === id) {
341
+ const title = (await codexTitles(roots.codex)).get(id);
342
+ return {
343
+ harness: "codex",
344
+ id,
345
+ cwd: meta.cwd,
346
+ ...title ? { title } : {},
347
+ mtime: file.mtime
348
+ };
349
+ }
350
+ }
351
+ }
352
+ return null;
353
+ }
354
+ async function listCodexSessions(root, own = /* @__PURE__ */ new Set(), now = Date.now()) {
355
+ const files = (await codexFiles(root, now - 7 * 864e5)).filter((f) => !own.has(f.id)).slice(0, 20);
356
+ const titles = files.length ? await codexTitles(root) : /* @__PURE__ */ new Map();
357
+ const results = [];
358
+ for (const file of files) {
359
+ const meta = await codexMeta(file.file, file.mtime);
360
+ if (meta?.id !== file.id) continue;
361
+ const title = titles.get(file.id);
362
+ results.push({
363
+ id: file.id,
364
+ updatedAt: new Date(file.mtime).toISOString(),
365
+ status: "idle",
366
+ ...meta.cwd ? { cwd: meta.cwd } : {},
367
+ ...title ? { title } : {}
368
+ });
369
+ }
370
+ return results;
371
+ }
372
+ 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;
373
+ async function codexFiles(root, since = 0) {
374
+ const out = [];
375
+ const names = async (dir) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).filter((d) => d.isDirectory() && /^\d+$/.test(d.name)).map((d) => d.name).sort().reverse();
376
+ for (const year of await names(root))
377
+ for (const month of await names(join4(root, year)))
378
+ for (const day of await names(join4(root, year, month))) {
379
+ const dir = join4(root, year, month, day);
380
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
381
+ const id = entry.isFile() ? ROLLOUT.exec(entry.name)?.[1] : void 0;
382
+ if (!id) continue;
383
+ const file = join4(dir, entry.name);
384
+ const info = await stat(file).catch(() => null);
385
+ if (info && info.mtimeMs >= since) out.push({ id, file, mtime: info.mtimeMs });
386
+ }
387
+ }
388
+ return out.sort((a, b) => b.mtime - a.mtime);
389
+ }
390
+ var codexSeen = /* @__PURE__ */ new Map();
391
+ async function codexMeta(file, mtime) {
392
+ const known = codexSeen.get(file);
393
+ if (known?.mtime === mtime) return known.meta;
394
+ const stream = createReadStream(file, { encoding: "utf8" });
395
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
396
+ let meta = null;
397
+ try {
398
+ for await (const line of lines) {
399
+ try {
400
+ const record = JSON.parse(line);
401
+ const payload = record?.type === "session_meta" ? record.payload : null;
402
+ if (typeof payload?.id === "string") {
403
+ const cwd = payload.cwd;
404
+ meta = {
405
+ id: payload.id,
406
+ cwd: typeof cwd === "string" && cwd.startsWith("/") && cwd.length <= 500 ? cwd : null
407
+ };
408
+ }
409
+ } catch {
410
+ }
411
+ break;
412
+ }
413
+ } finally {
414
+ lines.close();
415
+ stream.destroy();
416
+ }
417
+ if (codexSeen.size > 200) codexSeen.clear();
418
+ codexSeen.set(file, { mtime, meta });
419
+ return meta;
420
+ }
421
+ async function codexTitles(root) {
422
+ const titles = /* @__PURE__ */ new Map();
423
+ const text3 = await readFile(join4(dirname3(root), "session_index.jsonl"), "utf8").catch(() => "");
424
+ for (const line of text3.split("\n")) {
425
+ try {
426
+ const record = JSON.parse(line);
427
+ if (typeof record?.id === "string" && typeof record.thread_name === "string" && record.thread_name.trim())
428
+ titles.set(record.id, record.thread_name.trim().slice(0, 120));
429
+ } catch {
430
+ }
431
+ }
432
+ return titles;
433
+ }
434
+
242
435
  // src/spawn-command.ts
243
436
  import { execFileSync } from "child_process";
244
437
  function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
@@ -297,7 +490,7 @@ function windowsPowerShellEnv(env = process.env) {
297
490
  // src/t3-bin.ts
298
491
  import { execFileSync as execFileSync2 } from "child_process";
299
492
  import { existsSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
300
- import { join as join4 } from "path";
493
+ import { join as join5 } from "path";
301
494
  var CLEAN_ENV = () => ({
302
495
  HOME: process.env.HOME,
303
496
  USER: process.env.USER,
@@ -307,7 +500,7 @@ function defaultT3BinSources(home, stored) {
307
500
  return {
308
501
  env: process.env,
309
502
  home,
310
- appDirs: process.platform === "darwin" ? ["/Applications", join4(home, "Applications")] : [],
503
+ appDirs: process.platform === "darwin" ? ["/Applications", join5(home, "Applications")] : [],
311
504
  onPath: () => whichAll("t3"),
312
505
  ...stored ? { stored } : {}
313
506
  };
@@ -328,9 +521,9 @@ function bundleBinaries(appDir) {
328
521
  return [];
329
522
  }
330
523
  return bundles.flatMap((bundle) => {
331
- const root = join4(appDir, bundle);
524
+ const root = join5(appDir, bundle);
332
525
  try {
333
- return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join4(root, rel)).filter(isExecutable);
526
+ return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join5(root, rel)).filter(isExecutable);
334
527
  } catch {
335
528
  return [];
336
529
  }
@@ -339,8 +532,8 @@ function bundleBinaries(appDir) {
339
532
  function t3Candidates(serverVersion, sources) {
340
533
  const ordered = [
341
534
  sources.env.T3_BIN,
342
- join4(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
343
- join4(sources.env.T3CODE_HOME || join4(sources.home, ".t3"), "bin", "t3"),
535
+ join5(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
536
+ join5(sources.env.T3CODE_HOME || join5(sources.home, ".t3"), "bin", "t3"),
344
537
  ...sources.appDirs.flatMap(bundleBinaries),
345
538
  ...sources.onPath(),
346
539
  sources.stored
@@ -562,7 +755,7 @@ function parseFrames(data) {
562
755
  import { execFile, execFileSync as execFileSync3 } from "child_process";
563
756
  import { randomUUID } from "crypto";
564
757
  import { existsSync as existsSync2 } from "fs";
565
- import { join as join6 } from "path";
758
+ import { join as join7 } from "path";
566
759
 
567
760
  // ../clo0p-app/contracts/run-result.ts
568
761
  var WIZARD_STEPS_MAX = 6;
@@ -708,7 +901,7 @@ function droppedLine(dropped, run2) {
708
901
 
709
902
  // src/drivers/attachments.ts
710
903
  import { mkdir, writeFile } from "fs/promises";
711
- import { join as join5 } from "path";
904
+ import { join as join6 } from "path";
712
905
 
713
906
  // ../clo0p-app/contracts/work-spec.ts
714
907
  var IMAGE_TYPES = {
@@ -782,7 +975,7 @@ async function saveImages(images, dir) {
782
975
  await mkdir(dir, { recursive: true, mode: 448 });
783
976
  return Promise.all(
784
977
  images.map(async (image) => {
785
- const path = join5(dir, image.name);
978
+ const path = join6(dir, image.name);
786
979
  await writeFile(path, image.data, { mode: 384 });
787
980
  return path;
788
981
  })
@@ -1266,6 +1459,8 @@ function steerableRun(p) {
1266
1459
  }
1267
1460
  var STEER_WAIT_MS = 8e3;
1268
1461
  var STEER_POLL_MS = 500;
1462
+ var ASKS_READ_MAX = 8;
1463
+ var START_WAIT_MS = 5e3;
1269
1464
  function outcomeOf(p) {
1270
1465
  const run2 = latestRun(p.runs ?? []);
1271
1466
  const status = run2?.status ?? "pending";
@@ -1346,7 +1541,7 @@ function providerHarness(instanceId, cfg) {
1346
1541
  function pickProject(projects, repository) {
1347
1542
  if (!repository) {
1348
1543
  const repos = projects.filter(
1349
- (p) => p.repositoryIdentity || existsSync2(join6(p.workspaceRoot, ".git"))
1544
+ (p) => p.repositoryIdentity || existsSync2(join7(p.workspaceRoot, ".git"))
1350
1545
  );
1351
1546
  const pool = repos.length > 0 ? repos : projects;
1352
1547
  const only = pool.length === 1 ? pool[0] : void 0;
@@ -1543,14 +1738,48 @@ var T3Driver = class {
1543
1738
  const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1544
1739
  const all = (shell.threads ?? []).filter((t) => !isChild(t));
1545
1740
  const threads = scope === "all" ? all : all.filter(isUnsettled);
1741
+ const listed = orderThreads(threads, limit);
1742
+ const asks = await this.asksOf(listed);
1546
1743
  return {
1547
1744
  scope,
1548
1745
  unsettled: all.filter(isUnsettled).length,
1549
1746
  settled: all.length - all.filter(isUnsettled).length,
1550
1747
  running: threads.filter((t) => t.status === "running").length,
1551
- threads: orderThreads(threads, limit).map(threadView)
1748
+ threads: listed.map((t) => {
1749
+ const view = threadView(t);
1750
+ const waiting = asks.get(t.id);
1751
+ return waiting?.length ? { ...view, asks: waiting } : view;
1752
+ })
1552
1753
  };
1553
1754
  }
1755
+ /**
1756
+ * The questions each listed thread waits on, in the words the owner reads.
1757
+ * The shell names a thread's pending request but not its words, so the
1758
+ * projection is read only for a thread the shell says waits, or, from a T3
1759
+ * that names none, for a running one. A run that ended waits on nothing.
1760
+ */
1761
+ async asksOf(threads) {
1762
+ const waiting = threads.filter(
1763
+ (t) => !TERMINAL_RUN.has(t.status) && (t.pendingRuntimeRequest === void 0 ? t.status === "running" : Boolean(t.pendingRuntimeRequest))
1764
+ ).slice(0, ASKS_READ_MAX);
1765
+ const read = await Promise.all(
1766
+ waiting.map(async (t) => {
1767
+ try {
1768
+ const pending = pendingQuestions(await this.readProjection(t.id));
1769
+ return [
1770
+ t.id,
1771
+ pending.map((q) => ({ question_id: q.request_id, question: questionText(q) }))
1772
+ ];
1773
+ } catch (err) {
1774
+ this.log(
1775
+ `asks read failed thread=${t.id}: ${err instanceof Error ? err.message : String(err)}`
1776
+ );
1777
+ return [t.id, []];
1778
+ }
1779
+ })
1780
+ );
1781
+ return new Map(read);
1782
+ }
1554
1783
  /**
1555
1784
  * `work_id` is T3's `commandId`, so a second launch of the same work returns
1556
1785
  * the same thread with `resumed: true` and runs nothing twice. The worktree
@@ -1601,7 +1830,10 @@ var T3Driver = class {
1601
1830
  type: "worktree",
1602
1831
  baseRef: this.baseRefFor(project.workspaceRoot)
1603
1832
  },
1833
+ // Stored images belong to the thread their ids name, so the thread takes that id.
1834
+ ...photos2.attachments.length ? { threadId: a.work_id } : {},
1604
1835
  initialMessage: {
1836
+ ...photos2.attachments.length ? { messageId: a.work_id } : {},
1605
1837
  text: [a.prompt, photos2.line, RESULT_INSTRUCTION].filter(Boolean).join("\n\n"),
1606
1838
  attachments: photos2.attachments
1607
1839
  }
@@ -1630,23 +1862,30 @@ var T3Driver = class {
1630
1862
  ...launched.resumed ? {} : delivery(a.attachments, photos2.attachments.length)
1631
1863
  };
1632
1864
  }
1633
- /** The Task's photos as T3 image attachments, which T3 shows in the thread and hands its harness. */
1865
+ /**
1866
+ * The Task's photos, stored in T3 as image attachments, which T3 shows in the
1867
+ * thread and hands its harness. The work_id is the thread and message id, so a
1868
+ * retried launch stores the same bytes under the same ids.
1869
+ */
1634
1870
  async photos(a) {
1635
1871
  if (!a.attachments?.length) return { attachments: [], line: "" };
1636
1872
  const { images, missed } = await fetchImages(a.attachments, {
1637
1873
  log: (line) => this.log(`${line} work=${a.work_id}`)
1638
1874
  });
1639
1875
  this.log(`attachments work=${a.work_id} attached=${images.length} missed=${missed}`);
1640
- return {
1876
+ if (!images.length) return { attachments: [], line: attachedLine(0, missed) };
1877
+ const stored = await this.t3.rpc("assets.persistChatAttachments", {
1878
+ threadId: a.work_id,
1879
+ messageId: a.work_id,
1641
1880
  attachments: images.map((image) => ({
1642
1881
  type: "image",
1643
1882
  name: image.name,
1644
- mimeType: image.type,
1883
+ mimeType: image.type.toLowerCase(),
1645
1884
  sizeBytes: image.data.length,
1646
- dataUrl: `data:${image.type};base64,${image.data.toString("base64")}`
1647
- })),
1648
- line: attachedLine(images.length, missed)
1649
- };
1885
+ dataUrl: `data:${image.type.toLowerCase()};base64,${image.data.toString("base64")}`
1886
+ }))
1887
+ });
1888
+ return { attachments: stored.attachments, line: attachedLine(images.length, missed) };
1650
1889
  }
1651
1890
  /**
1652
1891
  * Say something to a thread. While the thread waits on a question, only
@@ -1698,6 +1937,7 @@ var T3Driver = class {
1698
1937
  const active = activeRun(p.runs ?? []);
1699
1938
  if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1700
1939
  throw new BoxToolError("already_finished");
1940
+ const before = latestRun(p.runs ?? [])?.id;
1701
1941
  const receipt = await this.dispatch({
1702
1942
  type: "message.dispatch",
1703
1943
  commandId: a.command_id,
@@ -1709,8 +1949,17 @@ var T3Driver = class {
1709
1949
  createdBy: "user",
1710
1950
  creationSource: "mcp"
1711
1951
  });
1952
+ if (!active && (a.resume || a.work_id)) await this.untilNewRun(a.thread_id, before);
1712
1953
  return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1713
1954
  }
1955
+ async untilNewRun(threadId, before) {
1956
+ for (let waited = 0; waited < START_WAIT_MS; waited += STEER_POLL_MS) {
1957
+ const latest = latestRun((await this.readProjection(threadId)).runs ?? []);
1958
+ if (latest && latest.id !== before) return;
1959
+ await sleep(STEER_POLL_MS);
1960
+ }
1961
+ this.log(`new turn not seen thread=${threadId} after ${START_WAIT_MS} ms; watching on`);
1962
+ }
1714
1963
  /**
1715
1964
  * Stop the running turn. A thread with nothing running answers
1716
1965
  * `was_running: false`, and so does a run that ended while the interrupt
@@ -2181,8 +2430,8 @@ ${RESULT_INSTRUCTION}`
2181
2430
  import { execFile as execFile2, execFileSync as execFileSync4, spawn } from "child_process";
2182
2431
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
2183
2432
  import { hostname } from "os";
2184
- import { basename, dirname as dirname3, join as join7 } from "path";
2185
- import { createInterface } from "readline";
2433
+ import { basename, dirname as dirname4, join as join8 } from "path";
2434
+ import { createInterface as createInterface2 } from "readline";
2186
2435
 
2187
2436
  // src/drivers/harness-check.ts
2188
2437
  var HARNESS_STALE_MS = 5 * 6e4;
@@ -2231,6 +2480,7 @@ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
2231
2480
  function takeoverSummary(machine) {
2232
2481
  return `You took this over on ${machine}.`;
2233
2482
  }
2483
+ var ADOPT_QUIET_MS = 2 * 6e4;
2234
2484
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
2235
2485
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
2236
2486
  var COMMANDS_KEPT = 50;
@@ -2261,7 +2511,7 @@ function failedEnd(harness, run2) {
2261
2511
  return { summary: `${lead}${quoted}"`, ...error };
2262
2512
  }
2263
2513
  function localRunsFilePath(env) {
2264
- return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join7(dir, "local-runs.json"));
2514
+ return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join8(dir, "local-runs.json"));
2265
2515
  }
2266
2516
  function pickRepo(repos, repository) {
2267
2517
  if (!repository) {
@@ -2420,22 +2670,95 @@ var LocalDriver = class {
2420
2670
  }) {
2421
2671
  const all = [...this.runs.values()];
2422
2672
  const unsettled = all.filter((r) => !r.end);
2423
- const shown = (scope === "all" ? all : unsettled).map((r) => ({
2424
- id: r.work_id,
2425
- title: r.title,
2426
- status: this.statusOf(r),
2427
- branch: null,
2428
- source: "cloop",
2429
- cloop: true,
2430
- settled: Boolean(r.end),
2431
- updatedAt: r.end?.at ?? r.started_at
2432
- }));
2673
+ const shown = (scope === "all" ? all : unsettled).map((r) => {
2674
+ const asks = this.lives.get(r.work_id)?.asks ?? [];
2675
+ return {
2676
+ id: r.work_id,
2677
+ title: r.title,
2678
+ status: this.statusOf(r),
2679
+ branch: null,
2680
+ source: r.adopted ? this.dialectOf(r).name : "cloop",
2681
+ cloop: !r.adopted,
2682
+ settled: Boolean(r.end),
2683
+ updatedAt: r.end?.at ?? r.started_at,
2684
+ ...asks.length ? { asks: asks.map((a) => ({ question_id: a.request_id, question: a.summary })) } : {}
2685
+ };
2686
+ });
2433
2687
  return {
2434
2688
  scope,
2435
2689
  unsettled: unsettled.length,
2436
2690
  settled: all.length - unsettled.length,
2437
2691
  running: shown.filter((t) => t.status === "running").length,
2438
- threads: orderThreads(shown, limit)
2692
+ threads: orderThreads([...shown, ...await this.ownSessions()], limit)
2693
+ };
2694
+ }
2695
+ /**
2696
+ * The owner's own Claude Code and Codex sessions on this machine, the ones
2697
+ * Cloop did not start, so a thread id from this list can be steered. Each
2698
+ * is idle: a send resumes it.
2699
+ */
2700
+ async ownSessions() {
2701
+ const known = new Set(
2702
+ [...this.runs.values()].flatMap((r) => [r.work_id, ...r.session_id ? [r.session_id] : []])
2703
+ );
2704
+ const roots = this.deps.sessions ?? sessionRoots();
2705
+ const harnesses = this.sessionHarnesses();
2706
+ const [claude, codex] = await Promise.all([
2707
+ harnesses.includes("claude-code") ? listOutsideSessions(roots.claude, known) : [],
2708
+ harnesses.includes("codex") ? listCodexSessions(roots.codex, known) : []
2709
+ ]);
2710
+ const view = (source) => (t) => ({
2711
+ id: t.id,
2712
+ title: t.title ?? t.project ?? "Untitled session",
2713
+ status: t.status,
2714
+ branch: null,
2715
+ source,
2716
+ cloop: false,
2717
+ settled: false,
2718
+ updatedAt: t.updatedAt
2719
+ });
2720
+ return [...claude.map(view("claude-code")), ...codex.map(view("codex"))];
2721
+ }
2722
+ sessionHarnesses() {
2723
+ return [this.deps.dialect, this.deps.fallbackHarness].flatMap(
2724
+ (d) => d && (d.name === "claude-code" || d.name === "codex") ? [d.name] : []
2725
+ );
2726
+ }
2727
+ /**
2728
+ * A session the owner started outside Cloop, as a run, the first time Cloop
2729
+ * sends it something. It keeps its own harness and folder, and a send
2730
+ * resumes it there. Not registered here: the send that takes it does that.
2731
+ */
2732
+ async adopt(id) {
2733
+ const found = await findSession(
2734
+ id,
2735
+ this.deps.sessions ?? sessionRoots(),
2736
+ this.sessionHarnesses()
2737
+ );
2738
+ if (!found) throw new BoxToolError("bad_args");
2739
+ if (!found.cwd) throw new BoxToolError("no_project");
2740
+ const age = this.now() - found.mtime;
2741
+ if (age < ADOPT_QUIET_MS) {
2742
+ this.log(`adopt refused work=${id} reason=thread_busy age_ms=${Math.round(age)}`);
2743
+ throw new BoxToolError("thread_busy");
2744
+ }
2745
+ this.refuseBusy(found.cwd);
2746
+ const head = await this.repo.head(found.cwd).catch(() => null);
2747
+ const raced = this.runs.get(id);
2748
+ if (raced) return raced;
2749
+ this.log(`adopt work=${id} harness=${found.harness}`);
2750
+ return {
2751
+ work_id: id,
2752
+ session_id: id,
2753
+ repo: found.cwd,
2754
+ title: found.title ?? "Your session",
2755
+ // A move to the other harness would leave the owner's session behind.
2756
+ harness_named: true,
2757
+ ...found.harness !== this.deps.dialect.name ? { harness: found.harness } : {},
2758
+ adopted: true,
2759
+ pid: null,
2760
+ started_at: new Date(this.now()).toISOString(),
2761
+ head_at_launch: head
2439
2762
  };
2440
2763
  }
2441
2764
  async readThread(id) {
@@ -2508,9 +2831,9 @@ ${photos2.line}` : a.prompt,
2508
2831
  };
2509
2832
  }
2510
2833
  async send(a) {
2511
- const r = this.record(a.thread_id);
2512
- const seen = r.commands?.find(([id]) => id === a.command_id);
2513
- if (seen) return { delivered: seen[1] };
2834
+ const r = this.runs.get(a.thread_id) ?? await this.adopt(a.thread_id);
2835
+ const seen2 = r.commands?.find(([id]) => id === a.command_id);
2836
+ if (seen2) return { delivered: seen2[1] };
2514
2837
  const live = this.lives.get(r.work_id);
2515
2838
  const ask = live?.asks[0];
2516
2839
  if (a.answer && (!ask || ask.request_id !== a.question_id)) {
@@ -2546,6 +2869,7 @@ ${photos2.line}` : a.prompt,
2546
2869
  r.end = void 0;
2547
2870
  r.last_text = void 0;
2548
2871
  }
2872
+ this.runs.set(r.work_id, r);
2549
2873
  this.spawnRun(r, a.text, true);
2550
2874
  this.remember(r, a.command_id, "start");
2551
2875
  return { delivered: "start" };
@@ -2681,7 +3005,7 @@ ${a.text}` : a.text;
2681
3005
  const { images, missed } = await fetchImages(a.attachments, { log });
2682
3006
  const paths = await saveImages(
2683
3007
  images,
2684
- join7(dirname3(this.file), "attachments", a.work_id)
3008
+ join8(dirname4(this.file), "attachments", a.work_id)
2685
3009
  ).catch((err) => {
2686
3010
  log(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
2687
3011
  return [];
@@ -2752,7 +3076,7 @@ ${RESULT_INSTRUCTION}`, images));
2752
3076
  child.stderr?.on("data", (chunk) => {
2753
3077
  live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
2754
3078
  });
2755
- const lines = createInterface({ input: child.stdout });
3079
+ const lines = createInterface2({ input: child.stdout });
2756
3080
  lines.on("line", (line) => {
2757
3081
  for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
2758
3082
  });
@@ -3020,7 +3344,7 @@ ${RESULT_INSTRUCTION}`, images));
3020
3344
  return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
3021
3345
  }
3022
3346
  save() {
3023
- mkdirSync3(dirname3(this.file), { recursive: true, mode: 448 });
3347
+ mkdirSync3(dirname4(this.file), { recursive: true, mode: 448 });
3024
3348
  const tmp = `${this.file}.tmp`;
3025
3349
  writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
3026
3350
  `, { mode: 384 });
@@ -3075,6 +3399,7 @@ export {
3075
3399
  redactSecrets,
3076
3400
  STOPPED_SUMMARY,
3077
3401
  isEndLogLine,
3402
+ listOutsideSessions,
3078
3403
  commandFor,
3079
3404
  quoteWindowsArg,
3080
3405
  windowsExecutable,
@@ -3,7 +3,7 @@ import {
3
3
  RUN_TEXT_MAX,
4
4
  boxPath,
5
5
  runnerPath
6
- } from "./chunk-R73PVAM2.js";
6
+ } from "./chunk-3ZZLIPFM.js";
7
7
 
8
8
  // src/box-watch.ts
9
9
  import { randomUUID } from "crypto";
@@ -97,7 +97,7 @@ var BoxWatch = class {
97
97
  start() {
98
98
  for (const e of this.entries) if (!e.settled_at) this.watch(e);
99
99
  }
100
- add(workId, threadId) {
100
+ add(workId, threadId, why = "launch") {
101
101
  if (this.entries.some((e) => e.work_id === workId)) return;
102
102
  const entry = {
103
103
  work_id: workId,
@@ -106,15 +106,35 @@ var BoxWatch = class {
106
106
  };
107
107
  this.entries.push(entry);
108
108
  this.save();
109
- this.deps.log(`launch work=${workId} thread=${threadId}`);
109
+ this.deps.log(`${why} work=${workId} thread=${threadId}`);
110
110
  this.watch(entry);
111
111
  }
112
- resume(threadId) {
112
+ /**
113
+ * A send the thread took. A settled entry is watched again, so the turn
114
+ * the send started reports its own end. A thread with no entry, one the
115
+ * owner started outside Cloop, is watched from now under the app's
116
+ * `workId`; without one nobody would read its end, so it stays unwatched.
117
+ * A `workId` other than the entry's moves the entry to that row.
118
+ */
119
+ follow(threadId, workId) {
113
120
  const entry = this.entries.find((e) => e.thread_id === threadId);
114
- if (!entry?.settled_at) return;
115
- entry.settled_at = void 0;
116
- entry.event = void 0;
117
- entry.sent_at = void 0;
121
+ if (!entry) {
122
+ if (workId) this.add(workId, threadId, "adopt");
123
+ return;
124
+ }
125
+ if (workId && workId !== entry.work_id) {
126
+ const unwatch = this.live.get(entry.work_id);
127
+ this.live.delete(entry.work_id);
128
+ if (unwatch) this.live.set(workId, unwatch);
129
+ this.deps.log(`rebind thread=${threadId} work=${entry.work_id} to=${workId}`);
130
+ entry.work_id = workId;
131
+ entry.questions = void 0;
132
+ }
133
+ if (entry.settled_at) {
134
+ entry.settled_at = void 0;
135
+ entry.event = void 0;
136
+ entry.sent_at = void 0;
137
+ }
118
138
  this.save();
119
139
  this.watch(entry);
120
140
  }
@@ -2,17 +2,17 @@
2
2
  import {
3
3
  findRun,
4
4
  ownHarness
5
- } from "./chunk-FKYVJUIR.js";
5
+ } from "./chunk-CQZQENZD.js";
6
6
  import {
7
7
  lockThreadsFile,
8
8
  threadsFilePath
9
- } from "./chunk-YLVOEZWH.js";
9
+ } from "./chunk-75AQLUDA.js";
10
10
  import {
11
11
  localRunsFilePath,
12
12
  readRunRecords,
13
13
  runHarness,
14
14
  takeoverSummary
15
- } from "./chunk-R73PVAM2.js";
15
+ } from "./chunk-3ZZLIPFM.js";
16
16
  import {
17
17
  sanitizeLabel
18
18
  } from "./chunk-VK6GV757.js";
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-WYU74GLG.js";
5
+ } from "./chunk-YOMSLSLT.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,