@dibssoftware/dibs 0.0.181 → 0.0.195

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 (105) hide show
  1. package/CHANGELOG.md +103 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +370 -73
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +120 -9
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/package.json +1 -1
  19. package/skills/dibs/SKILL.md +79 -149
  20. package/src/about.mjs +341 -0
  21. package/src/acquire.mjs +111 -27
  22. package/src/after.mjs +127 -0
  23. package/src/agents.mjs +2 -1
  24. package/src/alerts.mjs +95 -42
  25. package/src/answers.mjs +2 -2
  26. package/src/board.mjs +21 -16
  27. package/src/broker.mjs +23 -7
  28. package/src/carry.mjs +287 -0
  29. package/src/codex.mjs +132 -0
  30. package/src/commands.mjs +243 -82
  31. package/src/config.mjs +85 -14
  32. package/src/connect.mjs +4 -2
  33. package/src/cool.mjs +27 -11
  34. package/src/council.mjs +482 -0
  35. package/src/cwd.mjs +9 -0
  36. package/src/decisions.mjs +250 -0
  37. package/src/declare.mjs +96 -0
  38. package/src/diskreport.mjs +306 -0
  39. package/src/diskuse.mjs +420 -0
  40. package/src/diskwarn.mjs +68 -13
  41. package/src/doctor.mjs +149 -0
  42. package/src/doors.mjs +547 -0
  43. package/src/durable.mjs +143 -0
  44. package/src/envs.mjs +372 -0
  45. package/src/events.mjs +7 -2
  46. package/src/files.mjs +118 -6
  47. package/src/guard.mjs +239 -86
  48. package/src/guardd.mjs +8 -1
  49. package/src/halt.mjs +63 -0
  50. package/src/handoffs.mjs +362 -0
  51. package/src/history.mjs +34 -4
  52. package/src/hogs.mjs +36 -8
  53. package/src/jobprogress.mjs +283 -0
  54. package/src/later.mjs +21 -10
  55. package/src/lock.mjs +33 -9
  56. package/src/measure.mjs +42 -11
  57. package/src/media.mjs +240 -0
  58. package/src/news.mjs +31 -0
  59. package/src/notes.mjs +49 -8
  60. package/src/notices.mjs +126 -43
  61. package/src/ondemand.mjs +25 -2
  62. package/src/outcome.mjs +163 -0
  63. package/src/overlap.mjs +2 -2
  64. package/src/override.mjs +149 -79
  65. package/src/owner.mjs +15 -2
  66. package/src/people.mjs +236 -0
  67. package/src/pickup.mjs +72 -0
  68. package/src/picture.mjs +321 -0
  69. package/src/plain.mjs +84 -18
  70. package/src/platform.mjs +19 -0
  71. package/src/preempt.mjs +123 -15
  72. package/src/primer.mjs +91 -20
  73. package/src/prints.mjs +99 -0
  74. package/src/proc.mjs +1 -1
  75. package/src/progress.mjs +49 -3
  76. package/src/proof.mjs +102 -0
  77. package/src/push.mjs +271 -0
  78. package/src/questions.mjs +328 -57
  79. package/src/quota.mjs +1 -1
  80. package/src/recap.mjs +205 -0
  81. package/src/relay.mjs +139 -20
  82. package/src/remote.mjs +23 -10
  83. package/src/reviewgate.mjs +268 -0
  84. package/src/reviews.mjs +377 -0
  85. package/src/route.mjs +263 -0
  86. package/src/rules.mjs +216 -0
  87. package/src/schedule.mjs +238 -44
  88. package/src/schema.mjs +62 -0
  89. package/src/scratch.mjs +2 -2
  90. package/src/serve.mjs +3 -2
  91. package/src/signed.mjs +97 -0
  92. package/src/simpool.mjs +46 -1
  93. package/src/spend.mjs +375 -0
  94. package/src/state.mjs +43 -17
  95. package/src/talk.mjs +1078 -133
  96. package/src/thin.sh +2 -0
  97. package/src/trail.mjs +290 -0
  98. package/src/trailnote.mjs +209 -0
  99. package/src/util.mjs +7 -0
  100. package/src/vault.mjs +435 -0
  101. package/src/vendors.mjs +327 -0
  102. package/src/version.mjs +1 -1
  103. package/src/web.mjs +353 -60
  104. package/src/work.mjs +487 -0
  105. package/src/worker.mjs +7 -1
package/src/ondemand.mjs CHANGED
@@ -31,6 +31,7 @@ import { fileURLToPath } from 'node:url';
31
31
  import { HOME } from './config.mjs';
32
32
  import { event } from './events.mjs';
33
33
  import { ms, now, log } from './util.mjs';
34
+ import { recordFor } from './spend.mjs';
34
35
  import { VERSION } from './version.mjs';
35
36
 
36
37
  const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -73,11 +74,25 @@ export function ondemandOf(cfg) {
73
74
  if (typeof m.registry !== 'string' || !m.registry) throw new Error(`${at}: registry is the file that says who owns which VM, like "~/boat/VMS.md"`);
74
75
  if (typeof m.match !== 'string' || !m.match.trim()) throw new Error(`${at}: match is a word in the Use column of this VM's row, like "dibs"`);
75
76
  if (m.create != null && !SIZES[m.create?.max]) throw new Error(`${at}: create is { "max": "small" }, "default" or "large": the biggest VM dibs may make for a job bigger than this one`);
77
+ if (m.perHour != null && !perHourOk(m.perHour)) throw new Error(`${at}: perHour is what an hour of it costs, like 0.12, or one price per size: { "small": 0.06, "default": 0.12, "large": 0.24 }`);
76
78
  return { name: m.name, provider: m.provider, registry: m.registry.replace(/^~(?=\/)/, os.homedir()), match: m.match.trim(), owner: m.owner || null,
77
- idleStop: idleStopOf(m.idleStop, at), cores: m.cores ?? 4, memTotal: m.mem ? Number(m.mem) : 8 * 1024 ** 3, create: m.create ? { max: m.create.max } : null };
79
+ idleStop: idleStopOf(m.idleStop, at), cores: m.cores ?? 4, memTotal: m.mem ? Number(m.mem) : 8 * 1024 ** 3, create: m.create ? { max: m.create.max } : null,
80
+ ...(m.perHour != null && { perHour: m.perHour }) };
78
81
  });
79
82
  }
80
83
 
84
+ // What an hour costs, from config: one price, or one per boat size. Prices are dollars.
85
+ const perHourOk = p => (typeof p === 'number' ? p >= 0 : p && typeof p === 'object' && Object.entries(p).every(([k, v]) => SIZES[k] && typeof v === 'number' && v >= 0));
86
+ // The price of an hour of this VM, or null when config doesn't say. A temporary VM is the size it
87
+ // was made in; the dedicated one, the size its cores say.
88
+ export function hourly(vm) {
89
+ const p = vm.perHour;
90
+ if (typeof p === 'number') return p;
91
+ if (!p) return null;
92
+ const size = vm.type || Object.keys(SIZES).find(k => SIZES[k].cores === vm.cores);
93
+ return p[size] ?? null;
94
+ }
95
+
81
96
  // How long it may sit idle before it's stopped. Every idle second is billed:
82
97
  // 30s by default (enough for a script's next job to follow its last), 3m at most.
83
98
  const IDLE_DEFAULT = 30e3, IDLE_MAX = 3 * 6e4;
@@ -346,6 +361,7 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
346
361
  notes: `Created ${hhmm()} by dibs (${type}); dibs deletes it, and this row, when its jobs end` });
347
362
  Object.assign(w, { cores: SIZES[type].cores, memTotal: SIZES[type].mem });
348
363
  vm.cantWake = null;
364
+ vm.type = type;
349
365
  event({ kind: 'ondemand', act: 'create', name: vm.name, id, type, ms: vm.resumeMs });
350
366
  return { id };
351
367
  };
@@ -434,7 +450,14 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
434
450
  if (r.code) say(`${vm.name}: boat stop failed (${r.err}). Its own auto-stop still ends it within the hour.`);
435
451
  else noteVm(vm, vm.id, `Stopped ${hhmm()} by dibs (${why})`);
436
452
  }
437
- event({ kind: 'ondemand', act: vm.temp ? 'delete' : 'stop', name: vm.name, id: vm.id, why, billed: vm.upSince ? Math.round((now() - vm.upSince) / 1000) : null, ok: !r.code });
453
+ const billed = vm.upSince ? Math.round((now() - vm.upSince) / 1000) : null;
454
+ event({ kind: 'ondemand', act: vm.temp ? 'delete' : 'stop', name: vm.name, id: vm.id, why, billed, ok: !r.code });
455
+ // Every second it ran was billed: into the spend ledger, when config says what an hour costs.
456
+ const rate = hourly(vm);
457
+ if (billed && rate != null) {
458
+ const amount = Math.round(billed / 3600 * rate * 100);
459
+ if (amount > 0) recordFor('dibs', { amount, on: 'boat', note: `${vm.name}${vm.type ? ` (${vm.type})` : ''} up ${Math.round(billed / 60)}m${vm.id ? `, ${vm.id}` : ''}` });
460
+ }
438
461
  const w = workers.get(vm.name);
439
462
  if (w) Object.assign(w, { running: [], busy: {}, seen: 0, lost: false }, vm.temp ? { cores: vm.cores, memTotal: vm.memTotal } : {});
440
463
  Object.assign(vm, { upSince: null, idleSince: null, waitingSince: null, extended: 0 }, vm.temp ? { id: null } : {});
@@ -0,0 +1,163 @@
1
+ // What a finished run meant, in one sentence the person reads instead of a command line:
2
+ // "Tests pass, 212 of 212", "Build failed in Login.swift: cannot find 'Session' in scope".
3
+ // Plain parsers over the end of a run's output, as its agent's transcript kept it (dibs run
4
+ // leaves stdout and stderr to the agent, so dibs never stores output itself). Nothing here
5
+ // guesses: an output no parser knows gives null, and the caller falls back to the agent's own
6
+ // words or the run's -m.
7
+ import path from 'node:path';
8
+ import { masked } from './util.mjs';
9
+
10
+ // The end of the output holds every summary line these tools print; a 2 MB log's start never matters.
11
+ export const OUTPUT_READ = 64 * 1024;
12
+ // An error message as it reaches a phone: the compiler's line, cut.
13
+ const ERROR_SHOWN = 120;
14
+ // A failing test's name, cut.
15
+ const NAME_SHOWN = 60;
16
+
17
+ const cut = (s, n) => { const x = String(s).replace(/\s+/g, ' ').trim(); return x.length > n ? `${x.slice(0, n - 3).trimEnd()}...` : x; };
18
+ // Token-shaped words never leave the Mac, in a sentence any more than in a command.
19
+ const clean = (s, n) => cut(masked(String(s)).replace(/\b[A-Za-z0-9_-]{32,}\b/g, '***'), n);
20
+ const ESC = /\u001b\[[0-9;?]*[A-Za-z]/g;
21
+ const last = (text, re) => { let m = null; for (const x of text.matchAll(re)) m = x; return m; };
22
+ const num = x => Number(String(x).replace(/,/g, ''));
23
+
24
+ // "3 of 212 tests fail: expired token login, and 2 more"
25
+ function failing(failed, total, names, noun = 'tests') {
26
+ const first = names.find(Boolean);
27
+ const verb = failed === 1 ? `${noun.replace(/s$/, '')} fails` : `${noun} fail`;
28
+ const more = failed > 1 ? `, and ${failed - 1} more` : '';
29
+ return `${failed} of ${total} ${verb}${first ? `: ${clean(first, NAME_SHOWN)}${more}` : ''}`;
30
+ }
31
+ const passing = (n, noun = 'Tests') => `${noun} pass, ${n} of ${n}`;
32
+
33
+ // The first compiler error: "path:12:5: error: message".
34
+ function compileError(text) {
35
+ const m = /^(\S[^\n:]*?\.[A-Za-z]+):\d+(?::\d+)?:\s*(?:fatal )?error:\s*(.+)$/m.exec(text);
36
+ return m && { file: path.basename(m[1]), msg: m[2] };
37
+ }
38
+
39
+ // Each parser takes the output (colours stripped) and the exit code; returns { text, ok } or null.
40
+ const PARSERS = [
41
+ // node:test, TAP ("# pass 212") or the spec reporter ("ℹ pass 212").
42
+ t => {
43
+ const pass = last(t, /^(?:#|ℹ) pass (\d+)\s*$/gm), fail = last(t, /^(?:#|ℹ) fail (\d+)\s*$/gm);
44
+ if (!pass || !fail) return null;
45
+ const p = num(pass[1]), f = num(fail[1]);
46
+ if (!f) return { text: passing(p), ok: true };
47
+ const names = [...t.matchAll(/^\s*not ok \d+ - (.+?)\s*(?:#.*)?$/gm)].map(m => m[1])
48
+ .concat([...t.matchAll(/^\s*✖ (.+?)(?: \([\d.]+m?s\))?\s*$/gm)].map(m => m[1]).filter(n => !/^failing tests:?$/.test(n)));
49
+ return { text: failing(f, p + f, names), ok: false };
50
+ },
51
+ // Jest: "Tests: 2 failed, 210 passed, 212 total"
52
+ t => {
53
+ const m = last(t, /^Tests:\s+(.*?)(\d+) total\s*$/gm);
54
+ if (!m) return null;
55
+ const f = num(/(\d+) failed/.exec(m[1])?.[1] || 0), total = num(m[2]);
56
+ if (!f) return { text: passing(num(/(\d+) passed/.exec(m[1])?.[1] || total)), ok: true };
57
+ const names = [...t.matchAll(/^\s*● (.+?)\s*$/gm)].map(x => x[1].split(' › ').at(-1));
58
+ return { text: failing(f, total, names), ok: false };
59
+ },
60
+ // Vitest: " Tests 2 failed | 210 passed (212)"
61
+ t => {
62
+ const m = last(t, /^\s*Tests\s+(.*?)\((\d+)\)\s*$/gm);
63
+ if (!m || !/passed|failed/.test(m[1])) return null;
64
+ const f = num(/(\d+) failed/.exec(m[1])?.[1] || 0), total = num(m[2]);
65
+ if (!f) return { text: passing(total), ok: true };
66
+ const names = [...t.matchAll(/^\s*(?:FAIL|×|✗)\s+\S+\s+>\s+(.+?)\s*$/gm)].map(x => x[1].split(' > ').at(-1));
67
+ return { text: failing(f, total, names), ok: false };
68
+ },
69
+ // pytest: "==== 2 failed, 210 passed, 1 skipped in 3.20s ===="
70
+ t => {
71
+ const m = last(t, /^=+ (.*?\b(?:passed|failed)\b.*?) in [\d.]+s(?: \([^)]*\))? =+\s*$/gm);
72
+ if (!m) return null;
73
+ const p = num(/(\d+) passed/.exec(m[1])?.[1] || 0), f = num(/(\d+) failed/.exec(m[1])?.[1] || 0) + num(/(\d+) errors?/.exec(m[1])?.[1] || 0);
74
+ if (!f) return { text: passing(p), ok: true };
75
+ const names = [...t.matchAll(/^(?:FAILED|ERROR) \S+?::(\S+)/gm)].map(x => x[1]);
76
+ return { text: failing(f, p + f, names), ok: false };
77
+ },
78
+ // Playwright: " 12 passed (41s)" and " 2 failed"
79
+ t => {
80
+ const p = last(t, /^\s+(\d+) passed \([\d.]+m?s\)\s*$/gm);
81
+ const f = last(t, /^\s+(\d+) failed\s*$/gm);
82
+ if (!p && !f) return null;
83
+ const pn = p ? num(p[1]) : 0, fn = f ? num(f[1]) : 0;
84
+ if (!fn) return { text: passing(pn, 'Browser tests'), ok: true };
85
+ const names = [...t.matchAll(/^\s+\d+\) \[[^\]]+\] › .*? › (.+?)\s*(?:─|$)/gm)].map(x => x[1]);
86
+ return { text: `Browser tests: ${failing(fn, pn + fn, names)}`, ok: false };
87
+ },
88
+ // cargo: "test result: ok. 31 passed; 0 failed; ..." (one per test binary)
89
+ t => {
90
+ const rs = [...t.matchAll(/^test result: (ok|FAILED)\. (\d+) passed; (\d+) failed;/gm)];
91
+ if (!rs.length) return null;
92
+ const p = rs.reduce((n, m) => n + num(m[2]), 0), f = rs.reduce((n, m) => n + num(m[3]), 0);
93
+ if (!f) return { text: passing(p), ok: true };
94
+ const names = [...t.matchAll(/^test (\S+) \.\.\. FAILED$/gm)].map(x => x[1]);
95
+ return { text: failing(f, p + f, names), ok: false };
96
+ },
97
+ // go test: "--- FAIL: TestLogin", "ok example.com/pkg 0.3s", "FAIL example.com/pkg"
98
+ t => {
99
+ const fails = [...t.matchAll(/^\s*--- FAIL: (\S+)/gm)].map(x => x[1]);
100
+ const oks = [...t.matchAll(/^ok\s+\S+\s+(?:[\d.]+s|\(cached\))/gm)].length;
101
+ const failedPkgs = [...t.matchAll(/^FAIL\s+\S+\s+[\d.]+s/gm)].length;
102
+ if (!fails.length && !oks && !failedPkgs) return null;
103
+ if (!fails.length && !failedPkgs) return { text: `Tests pass in ${oks} package${oks === 1 ? '' : 's'}`, ok: true };
104
+ const n = fails.length || failedPkgs;
105
+ return { text: `${n} ${fails.length ? `test${n === 1 ? '' : 's'}` : `package${n === 1 ? '' : 's'}`} fail${n === 1 ? 's' : ''}${fails[0] ? `: ${clean(fails[0], NAME_SHOWN)}${n > 1 ? `, and ${n - 1} more` : ''}` : ''}`, ok: false };
106
+ },
107
+ // XCTest: "Executed 48 tests, with 0 failures (0 unexpected) in 2.1 (2.2) seconds"
108
+ t => {
109
+ const m = last(t, /Executed (\d+) tests?, with (\d+) failures?/g);
110
+ if (!m) return null;
111
+ const total = num(m[1]), f = num(m[2]);
112
+ if (!f) return { text: passing(total), ok: true };
113
+ const names = [...t.matchAll(/Test Case '-\[\S+ (\w+)\]' failed/g)].map(x => x[1]);
114
+ return { text: failing(f, total, names), ok: false };
115
+ },
116
+ // Swift Testing: "Test run with 12 tests passed after 0.5 seconds." / "... failed after ... with 2 issues."
117
+ t => {
118
+ const m = last(t, /Test run with (\d+) tests?(?: in \d+ suites?)? (passed|failed) after [\d.]+ seconds(?: with (\d+) issues?)?/g);
119
+ if (!m) return null;
120
+ if (m[2] === 'passed') return { text: passing(num(m[1])), ok: true };
121
+ const names = [...t.matchAll(/Test (\w+)\(\) (?:recorded an issue|failed)/g)].map(x => x[1]);
122
+ return { text: `Tests fail${m[3] ? ` with ${m[3]} issue${m[3] === '1' ? '' : 's'}` : ''}${names[0] ? `: ${clean(names[0], NAME_SHOWN)}` : ''}`, ok: false };
123
+ },
124
+ // tsc: "Found 3 errors in 2 files." and the first "api.ts(12,5): error TS2304: ..." or "api.ts:12:5 - error TS2304: ..."
125
+ t => {
126
+ const found = last(t, /^Found (\d+) errors?\b/gm);
127
+ const first = /^(\S+?)(?:\(\d+,\d+\)|:\d+:\d+)\s*[-:]\s*error TS\d+:\s*(.+)$/m.exec(t);
128
+ if (!found && !first) return null;
129
+ const n = found ? num(found[1]) : 1;
130
+ return { text: `Type check failed${first ? ` in ${path.basename(first[1])}` : ''}: ${n} error${n === 1 ? '' : 's'}${first ? `, first: ${clean(first[2], ERROR_SHOWN)}` : ''}`, ok: false };
131
+ },
132
+ // xcodebuild's own verdict, and the first compiler error behind a failed one.
133
+ (t, code) => {
134
+ const won = last(t, /\*\* (BUILD|ARCHIVE|TEST) (SUCCEEDED|FAILED) \*\*/g);
135
+ const err = code !== 0 ? compileError(t) : null;
136
+ if (!won && !err) return null;
137
+ const what = won?.[1] === 'ARCHIVE' ? 'Archive' : won?.[1] === 'TEST' ? 'Tests' : 'Build';
138
+ if (won && won[2] === 'SUCCEEDED' && code === 0) return { text: what === 'Tests' ? 'Tests pass' : `${what} worked`, ok: true };
139
+ return { text: `${what === 'Tests' ? 'Tests failed' : `${what} failed`}${err ? ` in ${err.file}: ${clean(err.msg, ERROR_SHOWN)}` : ''}`, ok: false };
140
+ },
141
+ ];
142
+
143
+ // The sentence for one run's output, or null when no parser knows it. code: the run's exit code.
144
+ export function outcomeOf(output, code = null) {
145
+ if (typeof output !== 'string' || !output) return null;
146
+ const t = output.slice(-OUTPUT_READ).replace(ESC, '').replace(/\r/g, '');
147
+ for (const p of PARSERS) {
148
+ const r = p(t, code);
149
+ if (r) return r;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ // The first sentence of something an agent wrote, if it's one line a person can read at a
155
+ // glance: under max characters, ending in a period (or ! or ?). Markdown marks go.
156
+ export function firstSentence(text, max = 140) {
157
+ // Its first line: a list or a second paragraph after it is more than a glance.
158
+ const first = String(text || '').replace(/```[\s\S]*?```/g, '\n').split('\n').map(x => x.trim()).find(Boolean) || '';
159
+ const plain = first.replace(/[*_`#>]+/g, '').replace(/\s+/g, ' ').trim();
160
+ const m = /^(.+?[.!?])(?:\s|$)/.exec(plain);
161
+ if (!m || m[1].length >= max || m[1].length < 3) return null;
162
+ return m[1];
163
+ }
package/src/overlap.mjs CHANGED
@@ -25,7 +25,7 @@
25
25
  //
26
26
  // config.overlap: off, fit or squeeze. loadConfig sets it from the pace when
27
27
  // the file doesn't (quiet off, normal fit, max squeeze; no pace, off).
28
- import { resCfg, machine, hardware } from './config.mjs';
28
+ import { resCfg, machine, hardware, isEnv } from './config.mjs';
29
29
  import { tag } from './proc.mjs';
30
30
  import { isFiles } from './files.mjs';
31
31
  import { isQuota } from './quota.mjs';
@@ -75,7 +75,7 @@ export const overlapMode = cfg => cfg.overlap || 'off';
75
75
  // One at a time, whatever the machine has free. A name dibs doesn't know is
76
76
  // one unless the config's unknown says exclusive: false.
77
77
  export function exclusive(cfg, r) {
78
- if (isFiles(r) || isQuota(r)) return true;
78
+ if (isFiles(r) || isQuota(r) || isEnv(r)) return true;
79
79
  const c = resCfg(cfg, r);
80
80
  if (c.pool || c.onRelease) return true;
81
81
  // resCfg fills a configured resource's gaps from unknown, so read its own config here.
package/src/override.mjs CHANGED
@@ -22,17 +22,19 @@ import { withState, history } from './state.mjs';
22
22
  import { ownerPause, pauseLabel } from './preempt.mjs';
23
23
  import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank, roomFor } from './schedule.mjs';
24
24
  import { actor } from './owner.mjs';
25
- import { event } from './events.mjs';
26
- import { die, now, say, sleepSync, unpolled } from './util.mjs';
25
+ import { event, readEvents } from './events.mjs';
26
+ import { die, now, say, sleepSync, unpolled, dur, clock } from './util.mjs';
27
27
  import { takeAgent, callKey } from './files.mjs';
28
28
  import { quoted } from './style.mjs';
29
+ import { described } from './declare.mjs';
30
+ import { notify } from './talk.mjs';
29
31
 
30
32
  const rankOf = p => PRIORITIES.indexOf(p || 'normal');
31
33
  const USAGE = {
32
- boost: 'dibs boost <id or agent> <urgent|high|normal|low|idle> [-m "why"] [--owner <session>]',
33
- pause: 'dibs pause <id> [--force] [-m "why"] [--owner <session>]',
34
- resume: 'dibs resume <id> [-m "why"] [--owner <session>]',
35
- stop: 'dibs stop <id> [-m "why"] [--owner <session>]',
34
+ boost: 'dibs boost <id or agent> <urgent|high|normal|low|idle> [-m "why"]',
35
+ pause: 'dibs pause <id> [--force] [-m "why"]',
36
+ resume: 'dibs resume <id> [-m "why"]',
37
+ stop: 'dibs stop [<id> ...|<words>|mine] [-m "why"]',
36
38
  cap: 'dibs cap <agent> <urgent|high|normal|low|idle|off>',
37
39
  };
38
40
  const IDS = 'Ids are the #numbers on the board (dibs), or "id" in dibs --json.';
@@ -45,18 +47,12 @@ const recordAll = (act, changes, who, reason = '') => {
45
47
  // What goes on the job: the agent's name, the person's paired browser, or nothing for the person here.
46
48
  const byOf = who => (who.agent || who.via ? { by: who.name } : {});
47
49
 
50
+ // --owner <session> was once needed on another agent's job. It guarded nothing (any agent
51
+ // could pass what dibs printed), so it's gone (2026-11-29); old callers still pass it, and
52
+ // it's taken and ignored.
48
53
  function argsOf(verb, args, flags = []) {
49
54
  const o = args.indexOf('--owner');
50
- let owner = null;
51
- if (o >= 0) {
52
- if (!args[o + 1] || args[o + 1].startsWith('-')) die(`--owner needs the job's owner: its session, or session/agent, as the board shows it. Use: ${USAGE[verb] || verb}`);
53
- owner = args[o + 1];
54
- args = [...args.slice(0, o), ...args.slice(o + 2)];
55
- }
56
- const parsed = argsOf1(verb, args, flags);
57
- return { ...parsed, owner };
58
- }
59
- function argsOf1(verb, args, flags = []) {
55
+ if (o >= 0) args = [...args.slice(0, o), ...args.slice(args[o + 1] && !args[o + 1].startsWith('-') ? o + 2 : o + 1)];
60
56
  const m = args.findIndex(a => a === '-m' || a === '--msg');
61
57
  let reason = '';
62
58
  if (m >= 0) {
@@ -77,7 +73,7 @@ function prioArg(verb, p) {
77
73
 
78
74
  const byName = name => x => x.agent === name || x.who === name;
79
75
 
80
- // Whose a job is, as --owner names it: its session, then /agent for a subagent's.
76
+ // Whose a job is, as the board names it: its session, then /agent for a subagent's.
81
77
  export const ownerOf = x => `${x.agent || x.who}${x.label ? `/${x.label}` : ''}`;
82
78
  // The calling agent: its session, and the subagent the guard hook saw make this
83
79
  // call (src/files.mjs takeAgent), so siblings in one session aren't each other.
@@ -86,20 +82,12 @@ function caller(verb) {
86
82
  return { ...identity({ as: a?.agentType || undefined }), agentId: a?.agentId || null };
87
83
  }
88
84
  // Its own: the same session, and the same subagent when either side was stamped
89
- // (else the same label). An unstamped job of an older dibs needs --owner from
90
- // a stamped caller: refusing too often is the safe side of this.
85
+ // (else the same label). For what dibs stop's words and mine pick from, and
86
+ // whose agent to tell. Nothing is refused for being someone else's: an id typed
87
+ // from memory can be (on 2026-10-19 an agent boosted #10167 and only learned
88
+ // whose it was afterwards), so every answer names whose job it is first, the
89
+ // history keeps who did it, and a stopped job's agent is told.
91
90
  const own = (x, me) => isMine(x, me) && (x.agentId || me.agentId ? x.agentId === me.agentId : (x.label || '') === (me.label || ''));
92
- // A job that isn't the calling agent's own takes --owner naming it, or nothing
93
- // changes (exit 2). An id typed from memory or a board can be someone else's:
94
- // on 2026-10-19 an agent boosted #10167 and only learned from the output whose
95
- // it was, and crews sharing a session stopped each other's jobs. The person is
96
- // never asked.
97
- function notYours(verb, x, who, me, want) {
98
- if (!who.agent || own(x, me)) return null;
99
- if (want && (want === ownerOf(x) || want === (x.agent || x.who))) return null;
100
- return `#${x.id} is ${ownerOf(x)}'s ${x.res.join(',')} job${x.purpose ? ` ("${x.purpose}")` : ''}${want ? `, not ${want}'s` : ', not yours'}. Nothing changed.`
101
- + ` If you meant it: dibs ${quoted([verb, ...process.argv.slice(3).filter((a, i, all) => a !== '--owner' && all[i - 1] !== '--owner')])} --owner ${ownerOf(x)}`;
102
- }
103
91
  // The first line names whose job it is, before anything else is said about it.
104
92
  const naming = (verbing, x) => `${verbing} #${x.id}: ${ownerOf(x)} ${x.res.join(',')}${x.purpose ? ` '${x.purpose}'` : ''}`;
105
93
  const what = (s, x) => (s.queue.includes(x) ? 'wait' : x.kind === 'hold' ? 'hold' : 'run');
@@ -142,10 +130,9 @@ function requeue(l, from) {
142
130
  // only low and idle runs) and background QoS follow the new priority.
143
131
  export function boost(args) {
144
132
  const who = actor();
145
- const me = caller('boost');
146
133
  const parsed = argsOf('boost', args);
147
134
  let { words: [target, p] } = parsed;
148
- const { reason, owner } = parsed;
135
+ const { reason } = parsed;
149
136
  // The priority before the id (dibs boost high 17727) reads the same.
150
137
  if (target && p && !/^\d+$/.test(target) && PRIORITIES.includes(target) && /^\d+$/.test(p)) [target, p] = [p, target];
151
138
  if (!target) die(`boost which job? Use: ${USAGE.boost}. ${IDS}`);
@@ -158,7 +145,6 @@ export function boost(args) {
158
145
  const hist = history();
159
146
  const r = withState(s => {
160
147
  const items = /^\d+$/.test(target) ? [...s.leases, ...s.queue].filter(x => String(x.id) === target) : [...s.leases, ...s.queue].filter(byName(target));
161
- for (const x of items) { const no = notYours('boost', x, who, me, owner); if (no) return { refused: no }; }
162
148
  const changes = [];
163
149
  for (const x of items) {
164
150
  const from = x.prio || 'normal';
@@ -170,7 +156,6 @@ export function boost(args) {
170
156
  for (const c of changes) if (c.kind === 'wait') c.place = order.findIndex(q => q.id === c.id) + 1;
171
157
  return changes;
172
158
  });
173
- if (r.refused) die(r.refused, 2);
174
159
  if (!r.length) die(`nothing matched ${target}: no lease or waiter with that id or agent name. ${IDS}`, 1);
175
160
  for (const c of r) {
176
161
  out(naming('boosting', c.x));
@@ -180,7 +165,8 @@ export function boost(args) {
180
165
  if (c.place) line += `, now #${c.place} in the queue`;
181
166
  if (c.qos) {
182
167
  // One that exited meanwhile has nothing left to move, a zombie its parent hasn't reaped included.
183
- const gone = pid => !/^[^Z]/.test(spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' }).stdout.trim());
168
+ // Where ps can't run, the move counts as failed.
169
+ const gone = pid => { const r = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' }); return r.stdout != null && !/^[^Z]/.test(r.stdout.trim()); };
184
170
  const move = pid => (c.qos.bg ? lower(pid) : raise(pid)) || gone(pid);
185
171
  // Whether each process was moved, the last time it was tried.
186
172
  const done = new Map(c.qos.pids.map(pid => [pid, move(pid)]));
@@ -214,6 +200,9 @@ export function inversions(s, cfg) {
214
200
  if (l.kind !== 'run' || !l.pgid || !(l.background ?? BACKGROUND.has(l.prio))) continue;
215
201
  const stuck = s.queue.find(q => q.pid && !BACKGROUND.has(q.prio || 'normal') && q.res.some(r => l.res.includes(r) && roomFor(s, q, r, cfg).open <= 0));
216
202
  if (stuck && !l.lifted) { l.lifted = stuck.id; moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: false, for: stuck.id }); }
203
+ // Paused, it stays up until it resumes: lowered now, a stop that hasn't landed yet waits on a core
204
+ // it may not get for 45 s (preempt.test, 2026-11-26). The resume lowers it (src/preempt.mjs sync).
205
+ else if (!stuck && l.lifted && l.pausedAt) { l.raisedToStop = true; delete l.lifted; }
217
206
  else if (!stuck && l.lifted) { moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: true, for: l.lifted }); delete l.lifted; }
218
207
  }
219
208
  return moves;
@@ -250,7 +239,7 @@ function unpausable(l, cfg, force) {
250
239
  function leaseArg(verb, args, flags) {
251
240
  const a = argsOf(verb, args, flags);
252
241
  if (a.words.length !== 1 || !/^\d+$/.test(a.words[0])) die(`Use: ${USAGE[verb]}. ${IDS}`);
253
- return { id: a.words[0], flags: a.flags, reason: a.reason, owner: a.owner };
242
+ return { id: a.words[0], flags: a.flags, reason: a.reason };
254
243
  }
255
244
  const missing = (s, id) => `no lease #${id}${s.queue.some(q => String(q.id) === id) ? ' (it\'s waiting, not running)' : ''}. ${IDS}`;
256
245
 
@@ -258,13 +247,10 @@ const missing = (s, id) => `no lease #${id}${s.queue.some(q => String(q.id) ===
258
247
  // lease and its slot until dibs resume, or until it ends.
259
248
  export function pause(args, cfg) {
260
249
  const who = actor();
261
- const me = caller('pause');
262
- const { id, flags, reason, owner } = leaseArg('pause', args, ['--force']);
250
+ const { id, flags, reason } = leaseArg('pause', args, ['--force']);
263
251
  const r = withState(s => {
264
252
  const l = s.leases.find(x => String(x.id) === id);
265
253
  if (!l) return { err: s.queue.some(q => String(q.id) === id) ? `#${id} is waiting, not running: there's nothing to pause yet. To hold it back, lower it: dibs boost ${id} idle` : missing(s, id), code: 1 };
266
- const no = notYours('pause', l, who, me, owner);
267
- if (no) return { err: no, code: 2 };
268
254
  out(naming('pausing', l));
269
255
  const why = unpausable(l, cfg, flags.has('--force'));
270
256
  if (why) return { err: why, code: 2 };
@@ -283,13 +269,10 @@ export function pause(args, cfg) {
283
269
  // urgent job, for memory) stay until their reason ends.
284
270
  export function resume(args) {
285
271
  const who = actor();
286
- const me = caller('resume');
287
- const { id, reason, owner } = leaseArg('resume', args);
272
+ const { id, reason } = leaseArg('resume', args);
288
273
  const r = withState(s => {
289
274
  const l = s.leases.find(x => String(x.id) === id);
290
275
  if (!l) return { err: missing(s, id) };
291
- const no = notYours('resume', l, who, me, owner);
292
- if (no) return { err: no, code: 2 };
293
276
  out(naming('resuming', l));
294
277
  if (!l.pauses?.some(p => p.owner))
295
278
  return { err: `#${id} isn't paused by you${l.pausedAt ? ` (it's ${pauseLabel(l)}, which dibs undoes by itself)` : ''}. Nothing changed.` };
@@ -304,48 +287,135 @@ export function resume(args) {
304
287
  recordAll('resume', [{ id: c.id, res: c.res, who: c.who }], who, reason);
305
288
  }
306
289
 
307
- // dibs stop <id>: the owner's kill switch. A run's tree is killed as a crash
308
- // would kill it, and its dibs process says "stopped by the owner" and gives
309
- // the lease back. A waiter's dibs process leaves the line and exits. A hold is
310
- // released.
290
+ // dibs stop: the kill switch, for the person and every agent alike. A run's
291
+ // tree is killed as a crash would kill it, and its dibs process says who
292
+ // stopped it and gives the lease back. A waiter's dibs process leaves the line
293
+ // and exits. A hold is released. Anyone's job: the first line names whose it
294
+ // is, the history keeps who stopped it, and its agent is told (src/talk.mjs notify).
295
+ // dibs stop your running and waiting jobs, with their numbers
296
+ // dibs stop 42 [43 ...] those jobs, anyone's
297
+ // dibs stop login tests your job whose -m or command has those words
298
+ // dibs stop mine every job of yours (--all-mine says the same)
299
+ // Words match only your own jobs (a session's main agent: its subagents' too):
300
+ // words are vaguer than a number, and a phrase that happens to fit another
301
+ // agent's job shouldn't end it. A number is said on purpose.
311
302
  export function stop(args) {
312
303
  const who = actor();
313
304
  const me = caller('stop');
314
- const { id, reason, owner } = leaseArg('stop', args);
305
+ const { words, reason, flags } = argsOf('stop', args, ['--all-mine']);
306
+ const all = flags.has('--all-mine') || (words.length === 1 && words[0] === 'mine');
307
+ const ids = words.length && words.every(w => /^#?\d+$/.test(w)) ? words.map(w => w.replace(/^#/, '')) : null;
308
+ // An agent's own jobs, its subagents' included when it's the session's main agent; the person's,
309
+ // by name. A bare dibs stop from the person lists every job: any of them is theirs to stop.
310
+ const mineOf = s => liveOf(s).filter(x => (who.agent ? yours(x, me) : isMine(x, me)));
311
+ if (!words.length && !all) return listJobs(peekState(), who.agent ? mineOf : liveOf, who);
315
312
  const r = withState(s => {
316
- const x = [...s.leases, ...s.queue].find(y => String(y.id) === id);
317
- if (!x) return null;
318
- const no = notYours('stop', x, who, me, owner);
319
- if (no) return { refused: no };
320
- out(naming('stopping', x));
321
- const c = brief(s, x);
322
- if (c.kind === 'hold') s.leases = s.leases.filter(l => l !== x);
323
- else if (c.kind === 'wait' && !x.pid) s.queue = s.queue.filter(q => q !== x); // a kept place: nobody is waiting on it
313
+ let targets;
314
+ if (ids) targets = ids.map(id => jobsOf(s).find(y => String(y.id) === id) || { missing: id });
315
+ else if (all) targets = mineOf(s);
324
316
  else {
325
- x.ownerStop = now();
326
- if (who.agent || who.via) x.stopBy = who.name;
327
- if (reason) x.stopReason = reason;
328
- if (c.kind === 'wait') {
329
- // Recorded apart from the place, so its waiter can say why once the place is gone. A place
330
- // its dibs is still deciding for stays until that dibs sees the stop (its waiter says so and
331
- // leaves; src/state.mjs reap takes it after STOP_GRACE); one nothing decides for goes now.
332
- // On 2026-11-04 "took #19783 out of line" left #19783 at the head of heavy, twice.
333
- (s.stopped ||= {})[x.id] = { at: x.ownerStop, by: x.stopBy, reason: x.stopReason };
334
- if (unpolled(x, now())) s.queue = s.queue.filter(q => q !== x);
335
- }
336
- // SIGKILL ends stopped processes too, so a paused run needs no SIGCONT first.
337
- // The lock is still held, so the run's own dibs can't remove the lease
338
- // (and its group number can't be handed out again) in between.
339
- if (c.kind === 'run') for (const g of groupsOf(x)) stopTree(g, 'SIGKILL');
317
+ const want = words.join(' ').toLowerCase();
318
+ targets = mineOf(s).filter(x => `${x.purpose || ''}\n${x.cmd || ''}`.toLowerCase().includes(want));
319
+ if (targets.length > 1) return { many: targets.map(x => ({ ...brief(s, x), x: { ...x } })), want };
320
+ if (!targets.length) return { none: want, theirs: liveOf(s).filter(x => `${x.purpose || ''}\n${x.cmd || ''}`.toLowerCase().includes(want)).map(x => ({ ...brief(s, x), x: { ...x } })) };
340
321
  }
341
- return c;
322
+ return { done: targets.map(x => (x.missing ? x : stopOne(s, x, who, reason, !own(x, me)))) };
342
323
  });
343
- if (!r) die(`no lease or waiter #${id}. ${IDS}`, 1);
344
- if (r.refused) die(r.refused, 2);
345
- out(r.kind === 'hold' ? `released #${id} ${r.who}'s hold on ${r.res.join(',')}. A hold has no process to kill; the agent finds out when it next asks.`
346
- : r.kind === 'wait' ? `took #${id} ${r.who} out of line for ${r.res.join(',')}. Its command never started.`
347
- : `stopped #${id} ${r.who}'s ${r.res.join(',')} run and killed its processes. Its dibs tells the agent it was stopped by ${who.agent || who.via ? who.name : 'the owner'}.`);
348
- recordAll('stop', [{ id: r.id, res: r.res, who: r.who }], who, reason);
324
+ if (r.many) {
325
+ out(`${r.many.length} of your jobs match "${r.want}". Say which by number:`);
326
+ for (const c of r.many) out(jobLine(c));
327
+ return die(`nothing stopped. dibs stop <number> stops one; dibs stop mine stops all of yours.`, 2);
328
+ }
329
+ if (r.none != null) {
330
+ if (!r.theirs.length) return die(`none of your running or waiting jobs match "${r.none}". dibs stop with nothing after it lists yours.`, 1);
331
+ out(`none of your jobs match "${r.none}", but other agents' do:`);
332
+ for (const c of r.theirs) out(jobLine(c));
333
+ return die(`nothing stopped: words only pick from your own jobs. To stop one of these, give its number: dibs stop ${r.theirs[0].id}`, 1);
334
+ }
335
+ if (all && !r.done.length) return out("you have no running or waiting jobs. Nothing to stop.");
336
+ let missed = 0;
337
+ for (const c of r.done) {
338
+ if (c.missing) { missed++; console.error(`dibs: ${endedText(c.missing) || `no running or waiting job #${c.missing}, and none by that number in the history. dibs stop with nothing after it lists yours. ${IDS}`}`); continue; }
339
+ out(naming('stopping', c.x));
340
+ out(c.kind === 'hold' ? `released #${c.id} ${c.who}'s hold on ${c.res.join(',')}. A hold has no process to kill.${c.theirs ? ' Its agent is told.' : ''}`
341
+ : c.kind === 'wait' ? `took #${c.id} ${c.who} out of line for ${c.res.join(',')}. Its command never started.${c.theirs ? ' Its agent is told.' : ''}`
342
+ : `stopped #${c.id} ${c.who}'s ${c.res.join(',')} run and killed its processes. Its dibs tells the agent it was stopped by ${who.agent || who.via ? who.name : 'the owner'}.`);
343
+ if (c.theirs) tellOwner(c, who, reason);
344
+ }
345
+ const done = r.done.filter(c => !c.missing);
346
+ recordAll('stop', done.map(c => ({ id: c.id, res: c.res, who: c.who })), who, reason);
347
+ if (missed) process.exitCode = 1;
348
+ }
349
+
350
+ // Every job a number can name, and the running and waiting ones (a kept place has nobody on it).
351
+ const jobsOf = s => [...s.leases, ...s.queue];
352
+ const liveOf = s => [...s.leases, ...s.queue.filter(q => q.pid)];
353
+ // A session's main agent owns its subagents' jobs too (a stamped subagent, or one --as names, owns its own).
354
+ // The guard stamps the main agent's calls 'main'; without the guard, none.
355
+ const yours = (x, me) => own(x, me) || (isMine(x, me) && (!me.agentId || me.agentId === 'main') && !me.label);
356
+
357
+ // A number that names no job now: how and when it ended, from the history, or null.
358
+ const ENDS = new Set(['end', 'left', 'timeout', 'requeue']);
359
+ function endedText(id) {
360
+ const n = Number(id), t = now();
361
+ const evs = readEvents(t).filter(e => e.id === n);
362
+ const e = evs.filter(x => ENDS.has(x.kind)).pop();
363
+ if (!e) return null;
364
+ const stopped = evs.find(x => x.kind === 'override' && x.act === 'stop');
365
+ const how = e.kind === 'timeout' ? 'it gave up waiting (exit 75) and never ran'
366
+ : e.kind === 'left' ? `it left the line (${e.why}) and never ran`
367
+ : e.kind === 'requeue' ? 'it was stopped and put back in line under a new number (dibs stop lists yours)'
368
+ : e.code == null ? 'it was stopped and put back in line under a new number (dibs stop lists yours)'
369
+ : e.code === 0 ? 'it finished (exit 0)' : `it ended with exit ${e.code}`;
370
+ const whose = `${e.who || 'someone'}'s${e.purpose ? ` "${e.purpose}"` : ''}`;
371
+ return `#${id} (${whose}) already ended ${dur(t - e.at)} ago, at ${clock(e.at)}: ${how}${stopped ? `, after ${stopped.by} stopped it` : ''}. Nothing to stop.`;
372
+ }
373
+ const peekState = () => withState(s => ({ leases: s.leases.map(l => ({ ...l })), queue: s.queue.map(q => ({ ...q })) }));
374
+ const jobLine = c => ` #${c.id} ${c.kind === 'wait' ? 'waiting' : c.kind === 'hold' ? 'holding' : 'running'} ${c.res.join(',')} ${c.who} "${described(c.x)}"${c.x.cmd ? ` (${c.x.cmd.slice(0, 60)})` : ''}`;
375
+
376
+ // Bare dibs stop: what there is to stop, so nobody digs a number out of the board's JSON.
377
+ function listJobs(s, mineOf, who) {
378
+ const mine = mineOf(s).map(x => ({ ...brief(s, x), x }));
379
+ if (!mine.length) return out(`${who.agent ? 'You have' : 'There are'} no running or waiting jobs. Nothing to stop.`);
380
+ out(`${who.agent ? 'Your' : 'Every'} running and waiting job${mine.length > 1 ? (who.agent ? 's' : '') : ''}:`);
381
+ for (const c of mine) out(jobLine(c));
382
+ const words = quoted([described(mine[0].x).split(/\s+/).slice(0, 3).join(' ')]);
383
+ out(`Stop one: dibs stop ${mine[0].id}${who.agent ? `${mine.length > 1 ? '; all of yours: dibs stop mine' : ''}; or by its words: dibs stop ${words}` : ''}`);
384
+ }
385
+
386
+ // One job stopped under the lock. theirs: another agent's, whose agent is told after.
387
+ function stopOne(s, x, who, reason, theirs) {
388
+ const c = { ...brief(s, x), x: { ...x }, theirs: theirs && (!!x.sessionId || !!x.who) };
389
+ if (c.kind === 'hold') s.leases = s.leases.filter(l => l !== x);
390
+ else if (c.kind === 'wait' && !x.pid) s.queue = s.queue.filter(q => q !== x); // a kept place: nobody is waiting on it
391
+ else {
392
+ x.ownerStop = now();
393
+ if (who.agent || who.via) x.stopBy = who.name;
394
+ if (reason) x.stopReason = reason;
395
+ if (c.kind === 'wait') {
396
+ // Recorded apart from the place, so its waiter can say why once the place is gone. A place
397
+ // its dibs is still deciding for stays until that dibs sees the stop (its waiter says so and
398
+ // leaves; src/state.mjs reap takes it after STOP_GRACE); one nothing decides for goes now.
399
+ // On 2026-11-04 "took #19783 out of line" left #19783 at the head of heavy, twice.
400
+ (s.stopped ||= {})[x.id] = { at: x.ownerStop, by: x.stopBy, reason: x.stopReason };
401
+ if (unpolled(x, now())) s.queue = s.queue.filter(q => q !== x);
402
+ }
403
+ // SIGKILL ends stopped processes too, so a paused run needs no SIGCONT first.
404
+ // The lock is still held, so the run's own dibs can't remove the lease
405
+ // (and its group number can't be handed out again) in between.
406
+ if (c.kind === 'run') for (const g of groupsOf(x)) stopTree(g, 'SIGKILL');
407
+ }
408
+ return c;
409
+ }
410
+
411
+ // The stopped job's agent hears it beside its next tool call, even when the call that
412
+ // ran the job went to the background, and for a hold, which has no dibs of its own to say it.
413
+ function tellOwner(c, who, reason) {
414
+ const x = c.x;
415
+ const by = who.agent || who.via ? who.name : 'the person at this machine';
416
+ const what = c.kind === 'hold' ? `released your hold #${x.id} on ${x.res.join(',')}` : c.kind === 'wait' ? `took your job #${x.id} out of line` : `stopped your job #${x.id} and killed its processes`;
417
+ notify({ sessionId: x.sessionId, who: x.who, agentId: x.agentId }, `stop:#${x.id}`,
418
+ `${by} ${what} ("${described(x)}") with dibs stop${reason ? `: "${reason}"` : ''}.${c.kind === 'hold' ? '' : ' It did not finish.'} Ask ${who.agent ? by : 'them'} before running it again.`);
349
419
  }
350
420
 
351
421
  // Lower a waiter to its agent's cap, or back up toward what it asked for when
package/src/owner.mjs CHANGED
@@ -4,21 +4,34 @@
4
4
  // event log and on the board, so the person can see which agent did what.
5
5
  import { identity } from './proc.mjs';
6
6
  import { event } from './events.mjs';
7
+ import { readPeople, several, personOf } from './people.mjs';
7
8
 
8
9
  // Set in the environment of an agent's tool calls: Claude Code, Codex, Cursor,
9
10
  // Gemini CLI, opencode, and the AI_AGENT convention several of them share.
10
11
  export const AGENT_ENV = ['CLAUDECODE', 'CLAUDE_CODE_CHILD_SESSION', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT',
11
12
  'CODEX_SANDBOX', 'CODEX_THREAD_ID', 'CURSOR_AGENT', 'GEMINI_CLI', 'OPENCODE'];
12
13
 
13
- // The caller: { name, agent, via }. An agent goes by its session name (the one the
14
+ // The caller: { name, agent, via, person, proof }. An agent goes by its session name (the one the
14
15
  // board and SendMessage use); anyone else is the person. DIBS_VIA names the paired
15
16
  // browser a page action came through (src/web.mjs sets it for relay calls), so the
16
17
  // record says "the person via Safari on iPhone (remote ...)". An agent can't borrow it.
18
+ // With two or more people (src/people.mjs), a person goes by their name ("sam via ..."), and
19
+ // person is that name, or '' when dibs can't tell which of them is typing.
17
20
  export function actor(env = process.env) {
18
21
  const id = identity();
19
22
  const agent = AGENT_ENV.some(k => env[k]) || !!id.spid;
20
23
  const via = !agent && typeof env.DIBS_VIA === 'string' && env.DIBS_VIA ? env.DIBS_VIA : null;
21
- return { agent, name: agent ? id.agent || id.who : via ? `the person via ${via}` : 'the person', ...(via && { via }) };
24
+ const p = agent ? {} : readPeople();
25
+ const person = several(p) ? personOf({ env, p })?.name || '' : null;
26
+ const as = person ? person : person === '' ? 'a person here' : 'the person';
27
+ return { agent, name: agent ? id.agent || id.who : via ? `${as} via ${via}` : as, ...(via && { via }), ...(person != null && { person }), ...(!agent && proofIn(env)) };
28
+ }
29
+
30
+ // DIBS_PROOF: the phone's signature on the call that runs this command (src/web.mjs sets it for a
31
+ // call src/relay.mjs checked). It's kept with the message or answer, and checked again where it's
32
+ // read (src/signed.mjs), so anyone can set it and only a real one counts.
33
+ function proofIn(env) {
34
+ try { const x = JSON.parse(env.DIBS_PROOF || 'null'); return x && typeof x === 'object' && !Array.isArray(x) ? { proof: x } : {}; } catch { return {}; }
22
35
  }
23
36
 
24
37
  // One line in the event log for a change to the person's settings or the