@cloop/runner 0.3.33 → 0.3.35

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;
@@ -706,10 +899,6 @@ function droppedLine(dropped, run2) {
706
899
  return dropped.outputs || dropped.checks ? `result_items_dropped run=${run2} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
707
900
  }
708
901
 
709
- // src/drivers/attachments.ts
710
- import { mkdir, writeFile } from "fs/promises";
711
- import { join as join5 } from "path";
712
-
713
902
  // ../clo0p-app/contracts/work-spec.ts
714
903
  var IMAGE_TYPES = {
715
904
  "image/jpeg": "jpg",
@@ -722,8 +911,14 @@ function isImageType(type) {
722
911
  }
723
912
  var IMAGE_MAX_BYTES = 10 * 1024 * 1024;
724
913
  var ATTACHMENTS_MAX = 8;
914
+ function repoName(repository) {
915
+ const name = repository?.trim().toLowerCase().split("/").filter(Boolean).at(-1);
916
+ return name || null;
917
+ }
725
918
 
726
919
  // src/drivers/attachments.ts
920
+ import { mkdir, writeFile } from "fs/promises";
921
+ import { join as join6 } from "path";
727
922
  var FETCH_BUDGET_MS = 1e4;
728
923
  function parseAttachments(value) {
729
924
  if (!Array.isArray(value)) return void 0;
@@ -782,7 +977,7 @@ async function saveImages(images, dir) {
782
977
  await mkdir(dir, { recursive: true, mode: 448 });
783
978
  return Promise.all(
784
979
  images.map(async (image) => {
785
- const path = join5(dir, image.name);
980
+ const path = join6(dir, image.name);
786
981
  await writeFile(path, image.data, { mode: 384 });
787
982
  return path;
788
983
  })
@@ -1203,6 +1398,7 @@ function isChild(t) {
1203
1398
  }
1204
1399
  var SESSIONS_TTL_MS = 5 * 6e4;
1205
1400
  var STATUS_TTL_MS = 3e4;
1401
+ var REPOS_TTL_MS = 10 * 6e4;
1206
1402
  var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1207
1403
  var STOPPED_IN_T3 = "You stopped this in T3.";
1208
1404
  var IDLE_SETTLE_MS = 20 * 6e4;
@@ -1266,6 +1462,8 @@ function steerableRun(p) {
1266
1462
  }
1267
1463
  var STEER_WAIT_MS = 8e3;
1268
1464
  var STEER_POLL_MS = 500;
1465
+ var ASKS_READ_MAX = 8;
1466
+ var START_WAIT_MS = 5e3;
1269
1467
  function outcomeOf(p) {
1270
1468
  const run2 = latestRun(p.runs ?? []);
1271
1469
  const status = run2?.status ?? "pending";
@@ -1343,20 +1541,23 @@ function providerHarness(instanceId, cfg) {
1343
1541
  const id = p?.driver ?? instanceId;
1344
1542
  return { harness: PROVIDER_HARNESS[id] ?? id };
1345
1543
  }
1544
+ function projectNames(p) {
1545
+ const names = [p.title, p.workspaceRoot.split("/").at(-1), p.repositoryIdentity?.displayName];
1546
+ return [...new Set(names.filter((name) => Boolean(name)))];
1547
+ }
1548
+ function isRepository(p) {
1549
+ return Boolean(p.repositoryIdentity) || existsSync2(join7(p.workspaceRoot, ".git"));
1550
+ }
1346
1551
  function pickProject(projects, repository) {
1347
1552
  if (!repository) {
1348
- const repos = projects.filter(
1349
- (p) => p.repositoryIdentity || existsSync2(join6(p.workspaceRoot, ".git"))
1350
- );
1553
+ const repos = projects.filter(isRepository);
1351
1554
  const pool = repos.length > 0 ? repos : projects;
1352
1555
  const only = pool.length === 1 ? pool[0] : void 0;
1353
1556
  if (only) return only;
1354
1557
  throw new BoxToolError("no_project");
1355
1558
  }
1356
- const want = repository.toLowerCase();
1357
- const found = projects.find(
1358
- (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
1359
- );
1559
+ const want = repoName(repository);
1560
+ const found = projects.find((p) => projectNames(p).some((name) => repoName(name) === want));
1360
1561
  if (!found) throw new BoxToolError("no_project");
1361
1562
  return found;
1362
1563
  }
@@ -1470,6 +1671,16 @@ var T3Driver = class {
1470
1671
  }
1471
1672
  return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
1472
1673
  }
1674
+ reposRead = null;
1675
+ /** The checkouts' projects, by every name `pickProject` matches. */
1676
+ async checkouts() {
1677
+ if (this.reposRead && this.now() - this.reposRead.at < REPOS_TTL_MS)
1678
+ return this.reposRead.names;
1679
+ const [, shell] = await this.readT3State();
1680
+ const names = [...new Set((shell.projects ?? []).filter(isRepository).flatMap(projectNames))];
1681
+ if (names.length) this.reposRead = { names, at: this.now() };
1682
+ return names;
1683
+ }
1473
1684
  async status() {
1474
1685
  const [cfg, shell] = await this.readT3State();
1475
1686
  const sessions = this.listSessions();
@@ -1543,14 +1754,48 @@ var T3Driver = class {
1543
1754
  const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1544
1755
  const all = (shell.threads ?? []).filter((t) => !isChild(t));
1545
1756
  const threads = scope === "all" ? all : all.filter(isUnsettled);
1757
+ const listed = orderThreads(threads, limit);
1758
+ const asks = await this.asksOf(listed);
1546
1759
  return {
1547
1760
  scope,
1548
1761
  unsettled: all.filter(isUnsettled).length,
1549
1762
  settled: all.length - all.filter(isUnsettled).length,
1550
1763
  running: threads.filter((t) => t.status === "running").length,
1551
- threads: orderThreads(threads, limit).map(threadView)
1764
+ threads: listed.map((t) => {
1765
+ const view = threadView(t);
1766
+ const waiting = asks.get(t.id);
1767
+ return waiting?.length ? { ...view, asks: waiting } : view;
1768
+ })
1552
1769
  };
1553
1770
  }
1771
+ /**
1772
+ * The questions each listed thread waits on, in the words the owner reads.
1773
+ * The shell names a thread's pending request but not its words, so the
1774
+ * projection is read only for a thread the shell says waits, or, from a T3
1775
+ * that names none, for a running one. A run that ended waits on nothing.
1776
+ */
1777
+ async asksOf(threads) {
1778
+ const waiting = threads.filter(
1779
+ (t) => !TERMINAL_RUN.has(t.status) && (t.pendingRuntimeRequest === void 0 ? t.status === "running" : Boolean(t.pendingRuntimeRequest))
1780
+ ).slice(0, ASKS_READ_MAX);
1781
+ const read = await Promise.all(
1782
+ waiting.map(async (t) => {
1783
+ try {
1784
+ const pending = pendingQuestions(await this.readProjection(t.id));
1785
+ return [
1786
+ t.id,
1787
+ pending.map((q) => ({ question_id: q.request_id, question: questionText(q) }))
1788
+ ];
1789
+ } catch (err) {
1790
+ this.log(
1791
+ `asks read failed thread=${t.id}: ${err instanceof Error ? err.message : String(err)}`
1792
+ );
1793
+ return [t.id, []];
1794
+ }
1795
+ })
1796
+ );
1797
+ return new Map(read);
1798
+ }
1554
1799
  /**
1555
1800
  * `work_id` is T3's `commandId`, so a second launch of the same work returns
1556
1801
  * the same thread with `resumed: true` and runs nothing twice. The worktree
@@ -1629,6 +1874,7 @@ var T3Driver = class {
1629
1874
  resumed: launched.resumed,
1630
1875
  permission,
1631
1876
  ...providerHarness(modelSelection.instanceId, cfg),
1877
+ repository: project.repositoryIdentity?.displayName ?? project.workspaceRoot.split("/").at(-1) ?? project.title,
1632
1878
  // A resumed thread kept its first message: these photos did not go in.
1633
1879
  ...launched.resumed ? {} : delivery(a.attachments, photos2.attachments.length)
1634
1880
  };
@@ -1708,6 +1954,7 @@ var T3Driver = class {
1708
1954
  const active = activeRun(p.runs ?? []);
1709
1955
  if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1710
1956
  throw new BoxToolError("already_finished");
1957
+ const before = latestRun(p.runs ?? [])?.id;
1711
1958
  const receipt = await this.dispatch({
1712
1959
  type: "message.dispatch",
1713
1960
  commandId: a.command_id,
@@ -1719,8 +1966,17 @@ var T3Driver = class {
1719
1966
  createdBy: "user",
1720
1967
  creationSource: "mcp"
1721
1968
  });
1969
+ if (!active && (a.resume || a.work_id)) await this.untilNewRun(a.thread_id, before);
1722
1970
  return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1723
1971
  }
1972
+ async untilNewRun(threadId, before) {
1973
+ for (let waited = 0; waited < START_WAIT_MS; waited += STEER_POLL_MS) {
1974
+ const latest = latestRun((await this.readProjection(threadId)).runs ?? []);
1975
+ if (latest && latest.id !== before) return;
1976
+ await sleep(STEER_POLL_MS);
1977
+ }
1978
+ this.log(`new turn not seen thread=${threadId} after ${START_WAIT_MS} ms; watching on`);
1979
+ }
1724
1980
  /**
1725
1981
  * Stop the running turn. A thread with nothing running answers
1726
1982
  * `was_running: false`, and so does a run that ended while the interrupt
@@ -2191,8 +2447,8 @@ ${RESULT_INSTRUCTION}`
2191
2447
  import { execFile as execFile2, execFileSync as execFileSync4, spawn } from "child_process";
2192
2448
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
2193
2449
  import { hostname } from "os";
2194
- import { basename, dirname as dirname3, join as join7 } from "path";
2195
- import { createInterface } from "readline";
2450
+ import { basename, dirname as dirname4, join as join8 } from "path";
2451
+ import { createInterface as createInterface2 } from "readline";
2196
2452
 
2197
2453
  // src/drivers/harness-check.ts
2198
2454
  var HARNESS_STALE_MS = 5 * 6e4;
@@ -2241,6 +2497,7 @@ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
2241
2497
  function takeoverSummary(machine) {
2242
2498
  return `You took this over on ${machine}.`;
2243
2499
  }
2500
+ var ADOPT_QUIET_MS = 2 * 6e4;
2244
2501
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
2245
2502
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
2246
2503
  var COMMANDS_KEPT = 50;
@@ -2271,16 +2528,16 @@ function failedEnd(harness, run2) {
2271
2528
  return { summary: `${lead}${quoted}"`, ...error };
2272
2529
  }
2273
2530
  function localRunsFilePath(env) {
2274
- return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join7(dir, "local-runs.json"));
2531
+ return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join8(dir, "local-runs.json"));
2275
2532
  }
2276
2533
  function pickRepo(repos, repository) {
2277
2534
  if (!repository) {
2278
2535
  if (repos.length === 1 && repos[0]) return repos[0];
2279
2536
  throw new BoxToolError("no_project");
2280
2537
  }
2281
- const want = repository.toLowerCase().split("/").at(-1) ?? "";
2538
+ const want = repoName(repository);
2282
2539
  const found = repos.find(
2283
- (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
2540
+ (r) => repoName(r.label) === want || repoName(basename(r.path)) === want
2284
2541
  );
2285
2542
  if (!found) throw new BoxToolError("no_project");
2286
2543
  return found;
@@ -2399,6 +2656,10 @@ var LocalDriver = class {
2399
2656
  warmHarnesses() {
2400
2657
  void this.harnessCheck.refresh().then(() => this.status()).catch((err) => this.log(`usage warm failed: ${err?.message}`));
2401
2658
  }
2659
+ /** Its repository folders, by label and folder name, the names `pickRepo` matches. */
2660
+ async checkouts() {
2661
+ return [...new Set(this.deps.repos.flatMap((r) => [r.label, basename(r.path)]))];
2662
+ }
2402
2663
  async status() {
2403
2664
  const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
2404
2665
  const all = [...this.runs.values()];
@@ -2430,22 +2691,95 @@ var LocalDriver = class {
2430
2691
  }) {
2431
2692
  const all = [...this.runs.values()];
2432
2693
  const unsettled = all.filter((r) => !r.end);
2433
- const shown = (scope === "all" ? all : unsettled).map((r) => ({
2434
- id: r.work_id,
2435
- title: r.title,
2436
- status: this.statusOf(r),
2437
- branch: null,
2438
- source: "cloop",
2439
- cloop: true,
2440
- settled: Boolean(r.end),
2441
- updatedAt: r.end?.at ?? r.started_at
2442
- }));
2694
+ const shown = (scope === "all" ? all : unsettled).map((r) => {
2695
+ const asks = this.lives.get(r.work_id)?.asks ?? [];
2696
+ return {
2697
+ id: r.work_id,
2698
+ title: r.title,
2699
+ status: this.statusOf(r),
2700
+ branch: null,
2701
+ source: r.adopted ? this.dialectOf(r).name : "cloop",
2702
+ cloop: !r.adopted,
2703
+ settled: Boolean(r.end),
2704
+ updatedAt: r.end?.at ?? r.started_at,
2705
+ ...asks.length ? { asks: asks.map((a) => ({ question_id: a.request_id, question: a.summary })) } : {}
2706
+ };
2707
+ });
2443
2708
  return {
2444
2709
  scope,
2445
2710
  unsettled: unsettled.length,
2446
2711
  settled: all.length - unsettled.length,
2447
2712
  running: shown.filter((t) => t.status === "running").length,
2448
- threads: orderThreads(shown, limit)
2713
+ threads: orderThreads([...shown, ...await this.ownSessions()], limit)
2714
+ };
2715
+ }
2716
+ /**
2717
+ * The owner's own Claude Code and Codex sessions on this machine, the ones
2718
+ * Cloop did not start, so a thread id from this list can be steered. Each
2719
+ * is idle: a send resumes it.
2720
+ */
2721
+ async ownSessions() {
2722
+ const known = new Set(
2723
+ [...this.runs.values()].flatMap((r) => [r.work_id, ...r.session_id ? [r.session_id] : []])
2724
+ );
2725
+ const roots = this.deps.sessions ?? sessionRoots();
2726
+ const harnesses = this.sessionHarnesses();
2727
+ const [claude, codex] = await Promise.all([
2728
+ harnesses.includes("claude-code") ? listOutsideSessions(roots.claude, known) : [],
2729
+ harnesses.includes("codex") ? listCodexSessions(roots.codex, known) : []
2730
+ ]);
2731
+ const view = (source) => (t) => ({
2732
+ id: t.id,
2733
+ title: t.title ?? t.project ?? "Untitled session",
2734
+ status: t.status,
2735
+ branch: null,
2736
+ source,
2737
+ cloop: false,
2738
+ settled: false,
2739
+ updatedAt: t.updatedAt
2740
+ });
2741
+ return [...claude.map(view("claude-code")), ...codex.map(view("codex"))];
2742
+ }
2743
+ sessionHarnesses() {
2744
+ return [this.deps.dialect, this.deps.fallbackHarness].flatMap(
2745
+ (d) => d && (d.name === "claude-code" || d.name === "codex") ? [d.name] : []
2746
+ );
2747
+ }
2748
+ /**
2749
+ * A session the owner started outside Cloop, as a run, the first time Cloop
2750
+ * sends it something. It keeps its own harness and folder, and a send
2751
+ * resumes it there. Not registered here: the send that takes it does that.
2752
+ */
2753
+ async adopt(id) {
2754
+ const found = await findSession(
2755
+ id,
2756
+ this.deps.sessions ?? sessionRoots(),
2757
+ this.sessionHarnesses()
2758
+ );
2759
+ if (!found) throw new BoxToolError("bad_args");
2760
+ if (!found.cwd) throw new BoxToolError("no_project");
2761
+ const age = this.now() - found.mtime;
2762
+ if (age < ADOPT_QUIET_MS) {
2763
+ this.log(`adopt refused work=${id} reason=thread_busy age_ms=${Math.round(age)}`);
2764
+ throw new BoxToolError("thread_busy");
2765
+ }
2766
+ this.refuseBusy(found.cwd);
2767
+ const head = await this.repo.head(found.cwd).catch(() => null);
2768
+ const raced = this.runs.get(id);
2769
+ if (raced) return raced;
2770
+ this.log(`adopt work=${id} harness=${found.harness}`);
2771
+ return {
2772
+ work_id: id,
2773
+ session_id: id,
2774
+ repo: found.cwd,
2775
+ title: found.title ?? "Your session",
2776
+ // A move to the other harness would leave the owner's session behind.
2777
+ harness_named: true,
2778
+ ...found.harness !== this.deps.dialect.name ? { harness: found.harness } : {},
2779
+ adopted: true,
2780
+ pid: null,
2781
+ started_at: new Date(this.now()).toISOString(),
2782
+ head_at_launch: head
2449
2783
  };
2450
2784
  }
2451
2785
  async readThread(id) {
@@ -2514,13 +2848,14 @@ ${photos2.line}` : a.prompt,
2514
2848
  permission: record.used_permission,
2515
2849
  takeover: true,
2516
2850
  harness: dialect.name,
2851
+ repository: basename(repo.path),
2517
2852
  ...delivery(a.attachments, photos2.paths.length)
2518
2853
  };
2519
2854
  }
2520
2855
  async send(a) {
2521
- const r = this.record(a.thread_id);
2522
- const seen = r.commands?.find(([id]) => id === a.command_id);
2523
- if (seen) return { delivered: seen[1] };
2856
+ const r = this.runs.get(a.thread_id) ?? await this.adopt(a.thread_id);
2857
+ const seen2 = r.commands?.find(([id]) => id === a.command_id);
2858
+ if (seen2) return { delivered: seen2[1] };
2524
2859
  const live = this.lives.get(r.work_id);
2525
2860
  const ask = live?.asks[0];
2526
2861
  if (a.answer && (!ask || ask.request_id !== a.question_id)) {
@@ -2556,6 +2891,7 @@ ${photos2.line}` : a.prompt,
2556
2891
  r.end = void 0;
2557
2892
  r.last_text = void 0;
2558
2893
  }
2894
+ this.runs.set(r.work_id, r);
2559
2895
  this.spawnRun(r, a.text, true);
2560
2896
  this.remember(r, a.command_id, "start");
2561
2897
  return { delivered: "start" };
@@ -2691,7 +3027,7 @@ ${a.text}` : a.text;
2691
3027
  const { images, missed } = await fetchImages(a.attachments, { log });
2692
3028
  const paths = await saveImages(
2693
3029
  images,
2694
- join7(dirname3(this.file), "attachments", a.work_id)
3030
+ join8(dirname4(this.file), "attachments", a.work_id)
2695
3031
  ).catch((err) => {
2696
3032
  log(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
2697
3033
  return [];
@@ -2762,7 +3098,7 @@ ${RESULT_INSTRUCTION}`, images));
2762
3098
  child.stderr?.on("data", (chunk) => {
2763
3099
  live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
2764
3100
  });
2765
- const lines = createInterface({ input: child.stdout });
3101
+ const lines = createInterface2({ input: child.stdout });
2766
3102
  lines.on("line", (line) => {
2767
3103
  for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
2768
3104
  });
@@ -3030,7 +3366,7 @@ ${RESULT_INSTRUCTION}`, images));
3030
3366
  return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
3031
3367
  }
3032
3368
  save() {
3033
- mkdirSync3(dirname3(this.file), { recursive: true, mode: 448 });
3369
+ mkdirSync3(dirname4(this.file), { recursive: true, mode: 448 });
3034
3370
  const tmp = `${this.file}.tmp`;
3035
3371
  writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
3036
3372
  `, { mode: 384 });
@@ -3080,16 +3416,17 @@ export {
3080
3416
  otherThreadsChoice,
3081
3417
  readRunnerConfig,
3082
3418
  writeBoxConfig,
3419
+ IMAGE_TYPES,
3083
3420
  runLogDir,
3084
3421
  runLogPath,
3085
3422
  redactSecrets,
3086
3423
  STOPPED_SUMMARY,
3087
3424
  isEndLogLine,
3425
+ listOutsideSessions,
3088
3426
  commandFor,
3089
3427
  quoteWindowsArg,
3090
3428
  windowsExecutable,
3091
3429
  windowsPowerShellEnv,
3092
- IMAGE_TYPES,
3093
3430
  parseAttachments,
3094
3431
  fetchImages,
3095
3432
  delivery,
@@ -2,17 +2,17 @@
2
2
  import {
3
3
  findRun,
4
4
  ownHarness
5
- } from "./chunk-6N6FIYOS.js";
5
+ } from "./chunk-ZE7NJCLG.js";
6
6
  import {
7
7
  lockThreadsFile,
8
8
  threadsFilePath
9
- } from "./chunk-7BLD64A4.js";
9
+ } from "./chunk-5WUAG7OI.js";
10
10
  import {
11
11
  localRunsFilePath,
12
12
  readRunRecords,
13
13
  runHarness,
14
14
  takeoverSummary
15
- } from "./chunk-WE5HZZLE.js";
15
+ } from "./chunk-S52SLN25.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-FAHTEHXP.js";
5
+ } from "./chunk-6Y3ILQDO.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,