@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.
- package/CHANGELOG.md +103 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +370 -73
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +120 -9
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +111 -27
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +95 -42
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +243 -82
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +27 -11
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +118 -6
- package/src/guard.mjs +239 -86
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +33 -9
- package/src/measure.mjs +42 -11
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +19 -0
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +1 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +139 -20
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1078 -133
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +353 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/recap.mjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// dibs recap: what happened while the person was away, in one place. Tasks agents closed, tasks
|
|
2
|
+
// they say are stuck, runs that failed and stayed failed, how many finished fine, what agents
|
|
3
|
+
// decided without asking, the reviews agents gave each other's changes, who left the person notes, what agents spent (src/spend.mjs), and agents
|
|
4
|
+
// that stopped mid-task (their session ended with work open, src/carry.mjs) and what came of that
|
|
5
|
+
// work. The page, the apps and the terminal all
|
|
6
|
+
// read this one summary (src/web.mjs serves it as /api/recap), so "while you were away" means the
|
|
7
|
+
// same thing everywhere.
|
|
8
|
+
//
|
|
9
|
+
// Agents read it too: `dibs recap --since 2h` is how a new session learns what the others did.
|
|
10
|
+
//
|
|
11
|
+
// Without --since, the person's recap starts where their last one ended (recap.json), and an
|
|
12
|
+
// agent's covers RECENT. Read without any lock: every source is appended to or read whole.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { HOME, loadConfig } from './config.mjs';
|
|
16
|
+
import { readEvents } from './events.mjs';
|
|
17
|
+
import { read as readPosts, tasks } from './progress.mjs';
|
|
18
|
+
import { questionsJson } from './questions.mjs';
|
|
19
|
+
import { threadsJson } from './talk.mjs';
|
|
20
|
+
import { trailNow, summary } from './trail.mjs';
|
|
21
|
+
import { handoffsAll } from './handoffs.mjs';
|
|
22
|
+
import { answeredSince } from './reviews.mjs';
|
|
23
|
+
import { actor } from './owner.mjs';
|
|
24
|
+
import { load as loadItems } from './handoffs.mjs';
|
|
25
|
+
import { runProof, proofView } from './proof.mjs';
|
|
26
|
+
import { spentBetween, money, capName } from './spend.mjs';
|
|
27
|
+
import { now, dur, clock, die, deadline } from './util.mjs';
|
|
28
|
+
import { bold, dim, red } from './style.mjs';
|
|
29
|
+
import { described } from './declare.mjs';
|
|
30
|
+
|
|
31
|
+
const FILE = path.join(HOME, 'recap.json');
|
|
32
|
+
// With no last look on record: about a working day.
|
|
33
|
+
const RECENT = 12 * 36e5;
|
|
34
|
+
// A last look older than this is a fresh start; a week of recap is a log, not a catch-up.
|
|
35
|
+
const LONGEST = 3 * 864e5;
|
|
36
|
+
// How many of each list the terminal prints; --json has them all.
|
|
37
|
+
const SHOWN = 6;
|
|
38
|
+
|
|
39
|
+
// What happened between since and t. Pure over its inputs, so tests hand them in. items: the
|
|
40
|
+
// work items as stored (src/work.mjs); posts under an item's id (w3) count as that item's.
|
|
41
|
+
// me: with two or more people, the person reading. Every item then names its agent's owner, and
|
|
42
|
+
// the reader's own come first in each list; everyone's stay in it.
|
|
43
|
+
// handoffs: as handoffsAll() shows them, for work sessions left unfinished (src/carry.mjs).
|
|
44
|
+
// spend: what was spent meanwhile and the caps near or past ({ total, byProject, byAgent, near }), or none.
|
|
45
|
+
export function recapOf({ since, t = now(), posts, events, questions, threads, trail = [], items = [], me = null, spend = null, handoffs = [], reviews = [] }) {
|
|
46
|
+
const ks = tasks(posts.filter(p => p.at <= t), t).filter(k => !/^[wh]\d+$/i.test(k.task || ''));
|
|
47
|
+
const name = k => k.task || k.project || 'untitled';
|
|
48
|
+
const owners = new Map(threads.filter(th => th.owner).map(th => [th.to, th.owner]));
|
|
49
|
+
const own = (who, o) => { const x = o || owners.get(who); return x ? { owner: x } : {}; };
|
|
50
|
+
// Each done thing carries its proof (src/proof.mjs): what dibs checked, or "no proof".
|
|
51
|
+
const done = [
|
|
52
|
+
...ks.filter(k => k.state === 'done' && k.doneAt > since)
|
|
53
|
+
.map(k => ({ who: k.who, task: name(k), text: k.text, at: k.doneAt, proof: proofView(runProof({ who: k.who, since: k.started, t: k.doneAt, events })), ...own(k.who, k.owner) })),
|
|
54
|
+
...items.filter(x => x.state === 'done' && x.closedAt > since && x.closedAt <= t)
|
|
55
|
+
.map(x => ({ who: x.doneBy || x.taker?.name || 'the person', task: x.title, id: `w${x.id}`, text: x.note || '', at: x.closedAt, proof: proofView(x.proof) })),
|
|
56
|
+
];
|
|
57
|
+
const stuck = [
|
|
58
|
+
...ks.filter(k => k.state === 'blocked' && k.last > since).map(k => ({ who: k.who, task: name(k), text: k.text, at: k.last, ...own(k.who, k.owner) })),
|
|
59
|
+
...items.filter(x => (x.state === 'open' || x.state === 'taken') && x.blocked && x.blocked.at > since && x.blocked.at <= t)
|
|
60
|
+
.map(x => ({ who: x.taker?.name || x.blocked.by, task: x.title, id: `w${x.id}`, text: x.blocked.why, at: x.blocked.at })),
|
|
61
|
+
];
|
|
62
|
+
// A run that failed and then passed is fixed: only the ones still failing are news. One stopped
|
|
63
|
+
// by a signal (128 and up: someone's kill, a timeout) was stopped, not failed.
|
|
64
|
+
const ends = events.filter(e => e.kind === 'end' && e.type === 'run' && e.at > since && e.at <= t);
|
|
65
|
+
const lastOf = new Map();
|
|
66
|
+
for (const e of ends) lastOf.set(e.key || `${e.id}`, e);
|
|
67
|
+
const failing = [...lastOf.values()].filter(e => e.code != null && e.code !== 0 && e.code < 128);
|
|
68
|
+
// An agent fixes its own failed runs; one with a deadline (--by) was promised to the person.
|
|
69
|
+
const failed = failing.filter(e => e.due)
|
|
70
|
+
.map(e => ({ who: e.who, what: described(e), res: e.res || [], code: e.code, at: e.at, due: e.due, ...own(e.who) }));
|
|
71
|
+
const ran = ends.filter(e => e.code === 0).length;
|
|
72
|
+
const decided = questions.filter(q => q.state === 'decided' && (q.answeredAt || q.asked) > since && (q.answeredAt || q.asked) <= t)
|
|
73
|
+
.map(q => ({ who: q.agent || q.who, text: q.text, answer: q.answer, id: q.id, at: q.answeredAt || q.asked, ...(q.rule && { rule: q.rule }), ...own(q.agent || q.who, q.owner) }));
|
|
74
|
+
const notes = [];
|
|
75
|
+
for (const th of threads) {
|
|
76
|
+
const n = th.messages.filter(m => m.from === 'agent' && m.kind === 'note' && m.at > since && m.at <= t).length;
|
|
77
|
+
if (n) notes.push({ who: th.to, n, at: th.last, ...own(th.to, th.owner) });
|
|
78
|
+
}
|
|
79
|
+
// One agent's approval or changes on another's work: the check the person didn't have to make.
|
|
80
|
+
const reviewed = reviews.filter(x => x.answeredAt > since && x.answeredAt <= t && (x.state === 'approved' || x.state === 'changes'))
|
|
81
|
+
.map(x => ({ id: x.id, who: x.by, author: x.from, verdict: x.state, what: x.branch || `${x.base.slice(0, 7)}..${x.head.slice(0, 7)}`, project: x.project,
|
|
82
|
+
head: x.head, note: x.verdict, at: x.answeredAt }));
|
|
83
|
+
// Work a session left unfinished, made into a handoff since the last look, and where it is now.
|
|
84
|
+
const stopped = handoffs.filter(x => x.carry && x.carry.at > since && x.carry.at <= t)
|
|
85
|
+
.map(x => ({ who: x.carry.who, task: x.title, id: x.id, at: x.carry.at, state: x.state, taker: x.taker || null, to: x.to || null, offered: x.carry.offered || null }));
|
|
86
|
+
// What dibs saw them do (src/trail.mjs), whether or not they said so: the big things on their own,
|
|
87
|
+
// and per agent, one line of everything.
|
|
88
|
+
const seen = trail.filter(x => x.at > since && x.at <= t);
|
|
89
|
+
const shipped = seen.filter(x => x.ships);
|
|
90
|
+
const others = x => (me && x.owner !== me ? 1 : 0);
|
|
91
|
+
const newest = (a, b) => others(a) - others(b) || b.at - a.at;
|
|
92
|
+
// Caps near their limit come with what was spent meanwhile; on their own they are no news.
|
|
93
|
+
const spent = spend?.total ? spend : null;
|
|
94
|
+
return {
|
|
95
|
+
since, until: t, done: done.sort(newest), stuck: stuck.sort(newest), failed: failed.sort(newest), failing: failing.length, ran,
|
|
96
|
+
decided: decided.sort(newest), reviewed: reviewed.sort(newest), notes: notes.sort(newest), spent, stopped: stopped.sort(newest),
|
|
97
|
+
shipped: shipped.sort(newest), trail: summary(seen),
|
|
98
|
+
empty: !done.length && !stuck.length && !failing.length && !ran && !decided.length && !reviewed.length && !notes.length && !seen.length && !spent && !stopped.length,
|
|
99
|
+
...(me && { you: me }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The recap from what's on disk now.
|
|
104
|
+
export function recapNow(since, t = now(), me = null) {
|
|
105
|
+
// From a day earlier: a task done since may have passed its suite before.
|
|
106
|
+
const events = readEvents(t).filter(e => e.at > since - 864e5);
|
|
107
|
+
return recapOf({
|
|
108
|
+
since, t, me, events,
|
|
109
|
+
trail: trailNow({ since, t, events: events.filter(e => e.at > since) }),
|
|
110
|
+
posts: readPosts({ since: since - 864e5 }),
|
|
111
|
+
items: loadItems().handoffs,
|
|
112
|
+
questions: questionsJson(loadConfig(), t).questions,
|
|
113
|
+
threads: threadsJson(t).threads,
|
|
114
|
+
spend: spentBetween(since, t),
|
|
115
|
+
handoffs: handoffsAll(t),
|
|
116
|
+
reviews: answeredSince(since, t),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Where a recap starts: the last look, unless there's none or it's too old to catch up from.
|
|
121
|
+
export const sinceOf = (seen, t = now()) => Number.isFinite(seen) && seen > 0 && seen < t && t - seen < LONGEST ? seen : t - RECENT;
|
|
122
|
+
|
|
123
|
+
// Each named person keeps their own last look (people), beside the one person's (seen).
|
|
124
|
+
const readLooks = () => { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { return {}; } };
|
|
125
|
+
function lastLook(me) {
|
|
126
|
+
const j = readLooks();
|
|
127
|
+
const v = me ? j.people?.[me] : j.seen;
|
|
128
|
+
return typeof v === 'number' ? v : null;
|
|
129
|
+
}
|
|
130
|
+
function saveLook(t, me) {
|
|
131
|
+
const j = readLooks();
|
|
132
|
+
const next = me ? { ...j, people: { ...(j.people || {}), [me]: t } } : { ...j, seen: t };
|
|
133
|
+
const tmp = `${FILE}.${process.pid}`;
|
|
134
|
+
try { fs.writeFileSync(tmp, JSON.stringify(next)); fs.renameSync(tmp, FILE); } catch {}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
138
|
+
// What came of work an agent left unfinished, as of now.
|
|
139
|
+
export const fate = x => (x.state === 'taken' ? `${x.taker} took it` : x.state === 'done' ? `${x.taker || 'another agent'} finished it`
|
|
140
|
+
: x.state === 'cancelled' ? 'dropped' : x.state === 'expired' ? 'nobody took it' : x.to ? `given to ${x.to}, not taken yet`
|
|
141
|
+
: x.offered ? `offered to ${x.offered}, not taken yet` : `nobody has it: dibs handoff give ${x.id} <agent>`);
|
|
142
|
+
const cut = (s, n = 110) => { const x = String(s ?? '').replace(/\s+/g, ' ').trim(); return x.length > n ? `${x.slice(0, n - 3)}...` : x; };
|
|
143
|
+
|
|
144
|
+
export function lines(r, t = now()) {
|
|
145
|
+
const out = [bold(`Since ${clock(r.since)} (${dur(t - r.since)} ago):`)];
|
|
146
|
+
if (r.empty) return [...out, ' Nothing happened: no tasks closed, no runs, no decisions, no reviews, no notes.'];
|
|
147
|
+
const section = (title, list, line) => {
|
|
148
|
+
if (!list.length) return;
|
|
149
|
+
out.push('', ` ${title}`);
|
|
150
|
+
for (const x of list.slice(0, SHOWN)) out.push(` ${line(x)}`);
|
|
151
|
+
if (list.length > SHOWN) out.push(dim(` and ${list.length - SHOWN} more (dibs recap --json)`));
|
|
152
|
+
};
|
|
153
|
+
// Another person's agent says whose it is; the reader's own and everyone's with one person say nothing.
|
|
154
|
+
const by = x => (x.owner && x.owner !== r.you ? `${x.who} (${x.owner}'s)` : x.who);
|
|
155
|
+
section(red(`Stuck (${r.stuck.length})`), r.stuck, x => `${by(x)}, ${x.task}: ${cut(x.text)}`);
|
|
156
|
+
section(red(`Stopped mid-task (${r.stopped.length})`), r.stopped, x => `${by(x)}, ${cut(x.task, 70)}: ${fate(x)}`);
|
|
157
|
+
section(red(`Missed a deadline (${r.failed.length})`), r.failed, x => `${by(x)}: ${cut(x.what, 80)} (exit ${x.code}, ${clock(x.at)})`);
|
|
158
|
+
section(bold(`Done (${r.done.length})`), r.done, x => `${by(x)}, ${x.id ? `${x.id} ` : ''}${x.task}${x.text ? `: ${cut(x.text)}` : ''} (${x.proof.proved ? x.proof.line : red(x.proof.line)})`);
|
|
159
|
+
section(bold(`Shipped (${r.shipped.length})`), r.shipped, x => `${by(x)}: ${cut(x.text)}${x.repo ? ` in ${x.repo}` : ''}`);
|
|
160
|
+
section(`Seen by dibs, not in their words (${r.trail.length} ${r.trail.length === 1 ? 'agent' : 'agents'})`, r.trail, x => `${by(x)}: ${cut(x.text, 160)}`);
|
|
161
|
+
section(`Decided without you (${r.decided.length})`, r.decided, x => `#${x.id} ${by(x)}: ${cut(x.text, 70)} -> ${x.answer}${x.rule ? ` (your rule ${x.rule})` : ''}`);
|
|
162
|
+
section(`Reviewed (${r.reviewed.length})`, r.reviewed, x => `${x.id} ${x.who} ${x.verdict === 'approved' ? 'approved' : 'asked for changes to'} ${x.author}'s ${x.what} in ${x.project}${x.note ? `: ${cut(x.note, 70)}` : ''}`);
|
|
163
|
+
if (r.spent) {
|
|
164
|
+
const by = list => list.slice(0, 3).map(x => `${x.name ?? '(no project)'} ${money(x.amount)}`).join(', ');
|
|
165
|
+
out.push('', ` ${bold(`Spent ${money(r.spent.total)}`)}${r.spent.total ? `: ${by(r.spent.byProject)}; by ${by(r.spent.byAgent)}` : ''}`);
|
|
166
|
+
for (const c of r.spent.near) out.push(red(` ${capName(c)} ${c.per === 'day' ? 'today' : 'this month'}: ${money(c.used)} of its ${money(c.limit)} cap (${Math.round(c.pct * 100)}%)`));
|
|
167
|
+
}
|
|
168
|
+
if (r.ran || r.failing || r.notes.length) out.push('');
|
|
169
|
+
if (r.ran) out.push(` ${plural(r.ran, 'run')} finished fine.`);
|
|
170
|
+
if (r.failing) out.push(` ${plural(r.failing, 'run')} failed and ${r.failing === 1 ? "hasn't" : "haven't"} passed since.`);
|
|
171
|
+
if (r.notes.length) {
|
|
172
|
+
const n = r.notes.reduce((k, x) => k + x.n, 0);
|
|
173
|
+
out.push(` ${plural(n, 'note')} for you from ${r.notes.slice(0, 3).map(x => x.who).join(', ')}${r.notes.length > 3 ? ` and ${r.notes.length - 3} more` : ''}: dibs threads`);
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function recap(args) {
|
|
179
|
+
let since = null, json = false;
|
|
180
|
+
for (let i = 0; i < args.length; i++) {
|
|
181
|
+
const a = args[i];
|
|
182
|
+
if (a === '--json') json = true;
|
|
183
|
+
else if (a === '--since') {
|
|
184
|
+
const v = args[++i] ?? die('--since needs a value: how long ago (2h, 30m) or a clock time (09:00)');
|
|
185
|
+
const m = String(v).match(/^(\d+(?:\.\d+)?)([mhd])$/);
|
|
186
|
+
if (m) since = now() - parseFloat(m[1]) * { m: 6e4, h: 36e5, d: 864e5 }[m[2]];
|
|
187
|
+
else {
|
|
188
|
+
// A clock time means the last time it was that o'clock, not the next.
|
|
189
|
+
const at = deadline(v);
|
|
190
|
+
if (!at) die(`--since takes how long ago (2h, 30m) or a clock time (09:00), not ${v}`);
|
|
191
|
+
since = at > now() ? at - 864e5 : at;
|
|
192
|
+
}
|
|
193
|
+
} else die(`dibs recap takes --since and --json, not ${a}`);
|
|
194
|
+
}
|
|
195
|
+
const t = now();
|
|
196
|
+
const who = actor();
|
|
197
|
+
const person = !who.agent;
|
|
198
|
+
const me = person && who.person ? who.person : null;
|
|
199
|
+
if (since == null) since = sinceOf(person ? lastLook(me) : null, t);
|
|
200
|
+
const r = recapNow(since, t, me);
|
|
201
|
+
// The person's next recap starts here. An agent's look, or a --json reader's, moves nothing.
|
|
202
|
+
if (person && !json) saveLook(t, me);
|
|
203
|
+
if (json) return console.log(JSON.stringify(r));
|
|
204
|
+
console.log(lines(r, t).join('\n'));
|
|
205
|
+
}
|
package/src/relay.mjs
CHANGED
|
@@ -33,9 +33,13 @@ import { makeAlive, singleInstance } from './proc.mjs';
|
|
|
33
33
|
import { underLock, commit } from './lock.mjs';
|
|
34
34
|
import { qr, render } from './qr.mjs';
|
|
35
35
|
import { logChange } from './owner.mjs';
|
|
36
|
-
import { remoteAccess, LOCAL_ONLY_TEXT, lookOnlyText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
|
|
36
|
+
import { remoteAccess, talkRoute, LOCAL_ONLY_TEXT, lookOnlyText, talkText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
|
|
37
|
+
import { pusher } from './push.mjs';
|
|
38
|
+
import { giveDevice } from './people.mjs';
|
|
39
|
+
import { readJSON } from './durable.mjs';
|
|
40
|
+
import { PAGE, p256, bodyBytes, signatureOk, proofOf } from './signed.mjs';
|
|
37
41
|
|
|
38
|
-
export
|
|
42
|
+
export { PAGE, bodyBytes, talkDigest } from './signed.mjs';
|
|
39
43
|
export const RELAY = process.env.DIBS_RELAY_URL || 'wss://app.dibs.cc';
|
|
40
44
|
const KEYS = path.join(HOME, 'relay-keys.json');
|
|
41
45
|
const FILE = path.join(HOME, 'relay.json');
|
|
@@ -169,6 +173,64 @@ function openBox(key, box) {
|
|
|
169
173
|
return { name: names.subarray(0, n < 0 ? NAME_PAD : n).toString('utf8'), rt: p.subarray(NAME_PAD) };
|
|
170
174
|
} catch { return null; }
|
|
171
175
|
}
|
|
176
|
+
// Talking from a phone (dibs pair --remote --allow-talk). Messages to agents and answers to their
|
|
177
|
+
// questions reach agents as the person's words, and agents act on them, shell commands included,
|
|
178
|
+
// so a phone that can talk is remote control of this Mac. Each such phone registers, sealed in its
|
|
179
|
+
// pairing message, a second key that signs only after Face ID (or the device passcode): a P-256 key
|
|
180
|
+
// in the Secure Enclave with biometry access control (kind raw), or a WebAuthn credential that
|
|
181
|
+
// requires user verification (kind webauthn). Every talk call then carries a fresh signature over
|
|
182
|
+
// the device, the call, its body and the time, checked here before api() runs it. docs/relay.md,
|
|
183
|
+
// "Talking from a phone", is the protocol.
|
|
184
|
+
const TALK_AAD = utf8('dibs-pair-talk-v1');
|
|
185
|
+
// The sealed key is a few hundred bytes; a WebAuthn credential id is at most 1023.
|
|
186
|
+
const TALK_BOX_MAX = 2048;
|
|
187
|
+
const CRED_MAX = 1023;
|
|
188
|
+
// How far a signature's time may be from this Mac's clock, either way. Phones set their clocks from
|
|
189
|
+
// the network, so two minutes covers drift and a slow relay; a replay inside it is caught by the
|
|
190
|
+
// time having to go up from the last one this device used.
|
|
191
|
+
export const UV_WINDOW = 120e3;
|
|
192
|
+
// { kind, pub, cred? } as kept on the device, or null for anything else.
|
|
193
|
+
export function talkKeyOf(j) {
|
|
194
|
+
if (!j || (j.kind !== 'raw' && j.kind !== 'webauthn')) return null;
|
|
195
|
+
const pub = unb64u(j.pub, 65);
|
|
196
|
+
if (!pub || pub[0] !== 4 || !p256(pub)) return null;
|
|
197
|
+
if (j.kind === 'raw') return { kind: 'raw', pub: j.pub };
|
|
198
|
+
const cred = unb64u(j.cred);
|
|
199
|
+
return cred && cred.length && cred.length <= CRED_MAX ? { kind: 'webauthn', pub: j.pub, cred: j.cred } : null;
|
|
200
|
+
}
|
|
201
|
+
function openTalkKey(key, box) {
|
|
202
|
+
if (box.length < 12 + 16) return null;
|
|
203
|
+
try {
|
|
204
|
+
const d = crypto.createDecipheriv('aes-256-gcm', key, box.subarray(0, 12));
|
|
205
|
+
d.setAAD(TALK_AAD);
|
|
206
|
+
d.setAuthTag(box.subarray(box.length - 16));
|
|
207
|
+
return talkKeyOf(JSON.parse(Buffer.concat([d.update(box.subarray(12, box.length - 16)), d.final()]).toString('utf8')));
|
|
208
|
+
} catch { return null; }
|
|
209
|
+
}
|
|
210
|
+
const UV_MISSING = 'Sending that from this phone needs Face ID each time, and this request came without it. Reload the page (or update the app) and try again.';
|
|
211
|
+
const UV_BAD = 'The Face ID signature on that didn\'t check out, so nothing was sent.';
|
|
212
|
+
const UV_STALE = 'That was signed more than 2 minutes ago, or this phone\'s clock is off, so nothing was sent. Try again.';
|
|
213
|
+
const UV_REPLAY = 'That signature was already used, so nothing was sent again.';
|
|
214
|
+
// One talk call from a talk device: { body, proof } (body without the signature) when it checks out, else { error }.
|
|
215
|
+
// The time must also beat the last one this device used, checked and recorded under one lock.
|
|
216
|
+
export function checkTalk(did, tk, m, clock = now) {
|
|
217
|
+
const body = m.body ?? {}, uv = body && typeof body === 'object' ? body.uv : null;
|
|
218
|
+
if (!uv || typeof uv !== 'object' || !Number.isSafeInteger(uv.t)) return { error: UV_MISSING };
|
|
219
|
+
if (Math.abs(clock() - uv.t) > UV_WINDOW) return { error: UV_STALE };
|
|
220
|
+
const bytes = bodyBytes(body);
|
|
221
|
+
if (!bytes || typeof m.path !== 'string' || !signatureOk(did, tk, m.method, m.path, bytes, uv)) return { error: UV_BAD };
|
|
222
|
+
const fresh = locked(w => {
|
|
223
|
+
const d = w.devices[did];
|
|
224
|
+
if (d?.tk?.pub !== tk.pub || (d.tlast || 0) >= uv.t) return false;
|
|
225
|
+
d.tlast = uv.t;
|
|
226
|
+
return true;
|
|
227
|
+
});
|
|
228
|
+
if (!fresh) return { error: UV_REPLAY };
|
|
229
|
+
const { uv: _, ...rest } = body;
|
|
230
|
+
// proof goes with what the call queues, so the agent it reaches can be shown it was signed (src/signed.mjs).
|
|
231
|
+
return { body: rest, proof: proofOf(did, m.method, m.path, bytes, uv) };
|
|
232
|
+
}
|
|
233
|
+
|
|
172
234
|
const hmac = (k, ...parts) => crypto.createHmac('sha256', k).update(Buffer.concat(parts)).digest();
|
|
173
235
|
const sameBytes = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
174
236
|
const ZERO = Buffer.alloc(32);
|
|
@@ -195,9 +257,12 @@ function parseKeys(s) {
|
|
|
195
257
|
// relay.json: { devices: {id: {pub, name, created, seen, act}}, pairs: [{pid, key, nk, exp, fails, act}], mcp }
|
|
196
258
|
// mcp: the person turned on remote MCP (dibs relay mcp on). Off unless they did.
|
|
197
259
|
// act: the device may change things (any call but GET). Absent means look only.
|
|
260
|
+
// talk, tk, tlast: the device may also message agents and answer them, signing each call with its
|
|
261
|
+
// talking key tk ({ kind, pub, cred? }); tlast is the time of the last signature it used.
|
|
262
|
+
// push: the dibs app on that phone asked for notifications ({ tok, key, at }, registerPush).
|
|
198
263
|
export function load() {
|
|
199
264
|
try {
|
|
200
|
-
const j =
|
|
265
|
+
const j = readJSON(FILE);
|
|
201
266
|
const obj = k => (j[k] && typeof j[k] === 'object' && !Array.isArray(j[k]) ? j[k] : {});
|
|
202
267
|
return { devices: obj('devices'), pairs: Array.isArray(j.pairs) ? j.pairs : [], mcp: j.mcp === true, accounts: obj('accounts'), approvals: obj('approvals'), pins: obj('pins'), conn: typeof j.conn === 'string' ? j.conn : null };
|
|
203
268
|
} catch { return { devices: {}, pairs: [], mcp: false, accounts: {}, approvals: {}, pins: {}, conn: null }; }
|
|
@@ -219,20 +284,24 @@ function locked(fn) {
|
|
|
219
284
|
// A one-time pairing link. The secret is shown once and only its derived pieces are kept.
|
|
220
285
|
// act: the device it pairs may change things, not only look. account: it pairs a dibs account
|
|
221
286
|
// (the page at /account opens it), which may then give this Mac its account key (join, below).
|
|
222
|
-
|
|
287
|
+
// talk: it may also message agents and answer them, with Face ID each time (it implies act). The
|
|
288
|
+
// link ends in .t so the phone knows to make its talking key before it pairs.
|
|
289
|
+
// person: whose phone it is (dibs people), given the device as it pairs.
|
|
290
|
+
export function newPairing({ act = false, account = false, talk = false, person = null } = {}) {
|
|
223
291
|
const k = keys();
|
|
224
292
|
const secret = crypto.randomBytes(32);
|
|
225
|
-
|
|
293
|
+
if (talk) act = true;
|
|
294
|
+
const frag = `${k.mid}.${b64u(secret)}.${k.fp}${talk ? '.t' : ''}`;
|
|
226
295
|
// A browser link gets a code to type as well. The account link opens on /account, which has
|
|
227
296
|
// its own sign-in, so it has none.
|
|
228
297
|
const code = account ? null : freshCode();
|
|
229
298
|
const box = code && sealCode(frag, code.slice(0, 4), code.slice(4));
|
|
230
299
|
const pid = b64u(pairId(secret));
|
|
231
300
|
locked(w => {
|
|
232
|
-
w.pairs.push({ pid, key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(account ? { acct: true } : {}), ...(code ? { cr: code.slice(0, 4), cb: box } : {}) });
|
|
301
|
+
w.pairs.push({ pid, key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(talk ? { talk: true } : {}), ...(account ? { acct: true } : {}), ...(code ? { cr: code.slice(0, 4), cb: box } : {}), ...(person ? { person } : {}) });
|
|
233
302
|
w.pairs = w.pairs.slice(-MAX_PAIRS);
|
|
234
303
|
});
|
|
235
|
-
return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, ...(code ? { code: showCode(code) } : {}), pid, frag, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act };
|
|
304
|
+
return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, ...(code ? { code: showCode(code) } : {}), pid, frag, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act, talk };
|
|
236
305
|
}
|
|
237
306
|
|
|
238
307
|
// A new code for an open link whose drop name another Mac holds at the relay: the same link,
|
|
@@ -277,6 +346,33 @@ async function codeAck(pid, code) {
|
|
|
277
346
|
|
|
278
347
|
export const devices = () => Object.entries(load().devices).map(([id, d]) => ({ id, ...d }));
|
|
279
348
|
|
|
349
|
+
// Notifications (src/push.mjs). The dibs app gives its APNs token and a push key it made, over its
|
|
350
|
+
// own session, so only that phone can set either on its own device record: never another device's,
|
|
351
|
+
// and never from the Mac's own page. { off: true } turns them off.
|
|
352
|
+
const APNS_TOKEN = /^[0-9a-f]{64,200}$/;
|
|
353
|
+
export function registerPush(did, b, clock = now) {
|
|
354
|
+
const off = b?.off === true;
|
|
355
|
+
const key = unb64u(b?.key, 32);
|
|
356
|
+
if (!off && (typeof b?.token !== 'string' || !APNS_TOKEN.test(b.token) || !key))
|
|
357
|
+
return { status: 400, json: { error: 'a notification sign-up is {token: the APNs token in hex, key: 32 bytes in base64url}, or {off: true}' } };
|
|
358
|
+
const done = locked(w => {
|
|
359
|
+
const d = w.devices[did];
|
|
360
|
+
if (!d) return false;
|
|
361
|
+
if (off) delete d.push;
|
|
362
|
+
else d.push = { tok: b.token, key: b.key, at: clock() };
|
|
363
|
+
return true;
|
|
364
|
+
});
|
|
365
|
+
return done ? { status: 200, json: { ok: true, push: !off } } : { status: 403, json: { error: 'this device is not paired' } };
|
|
366
|
+
}
|
|
367
|
+
// Paired phones with notifications on, for the notifier.
|
|
368
|
+
export const pushPhones = () => Object.entries(load().devices).filter(([, d]) => typeof d.rth === 'string' && typeof d.push?.tok === 'string' && unb64u(d.push.key, 32))
|
|
369
|
+
.map(([did, d]) => ({ did, rth: d.rth, tok: d.push.tok, key: d.push.key }));
|
|
370
|
+
// Apple says that token is dead (the app was deleted, or notifications reset): the phone signs up
|
|
371
|
+
// again with a new one the next time it opens.
|
|
372
|
+
export function forgetPush(rth, tok) {
|
|
373
|
+
locked(w => { for (const d of Object.values(w.devices)) if (d.rth === rth && d.push?.tok === tok) delete d.push; });
|
|
374
|
+
}
|
|
375
|
+
|
|
280
376
|
// Removes every device whose id starts with `which` (or all). Live sessions end on their next frame.
|
|
281
377
|
export function revoke(which) {
|
|
282
378
|
return locked(w => {
|
|
@@ -502,8 +598,10 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
502
598
|
|
|
503
599
|
function pair1(ch, m) {
|
|
504
600
|
const pid = unb64u(m.pid, 16), d = unb64u(m.d, 32), nb = unb64u(m.nb, 32), sig = unb64u(m.sig, 64), mac = unb64u(m.mac, 32), box = unb64u(m.name, BOX_LEN);
|
|
505
|
-
|
|
506
|
-
const
|
|
601
|
+
// tk: a phone's talking key, sealed. When it's there the transcript covers it too.
|
|
602
|
+
const tkBox = m.tk == null ? null : unb64u(m.tk);
|
|
603
|
+
if (!pid || !d || !nb || !sig || !mac || !box || (m.tk != null && (!tkBox || tkBox.length > TALK_BOX_MAX))) return refuse(ch, 'bad-pair');
|
|
604
|
+
const t1 = tkBox ? tx('dibs-pair1-v1', k.mid, pid, d, nb, box, tkBox) : tx('dibs-pair1-v1', k.mid, pid, d, nb, box);
|
|
507
605
|
let name, rth;
|
|
508
606
|
// Look up, check and spend under one lock, so a link can't pair twice.
|
|
509
607
|
const r = locked(w => {
|
|
@@ -518,14 +616,19 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
518
616
|
if (!crypto.verify(null, t1, devKey, sig)) return { err: 'bad-pair' };
|
|
519
617
|
const opened = openBox(unb64u(p.nk, 32), box);
|
|
520
618
|
if (!opened) return { err: 'bad-pair' };
|
|
619
|
+
// Only a link made with --allow-talk lets its key talk; a key sent with any other is ignored.
|
|
620
|
+
// A talk link paired without a key pairs a device that can act but not talk.
|
|
621
|
+
const tk = p.talk === true && tkBox ? openTalkKey(unb64u(p.nk, 32), tkBox) : null;
|
|
622
|
+
if (p.talk === true && tkBox && !tk) return { err: 'bad-pair' };
|
|
521
623
|
name = cleanName(opened.name);
|
|
522
624
|
rth = tokenHash(opened.rt);
|
|
523
625
|
w.pairs = w.pairs.filter(x => x !== p);
|
|
524
626
|
const did = b64u(crypto.randomBytes(16));
|
|
525
|
-
w.devices[did] = { pub: b64u(d), name, rth, created: clock(), ...(p.act === true ? { act: true } : {}), ...(p.acct === true ? { acct: true } : {}) };
|
|
526
|
-
return { did, key: unb64u(p.key, 32) };
|
|
627
|
+
w.devices[did] = { pub: b64u(d), name, rth, created: clock(), ...(p.act === true ? { act: true } : {}), ...(tk ? { talk: true, tk } : {}), ...(p.acct === true ? { acct: true } : {}) };
|
|
628
|
+
return { did, key: unb64u(p.key, 32), person: typeof p.person === 'string' ? p.person : null };
|
|
527
629
|
});
|
|
528
630
|
if (r.err) return refuse(ch, r.err);
|
|
631
|
+
if (r.person) { try { giveDevice(r.person, r.did); } catch (e) { log(`relay: couldn't give ${r.did.slice(0, 8)} to ${r.person}: ${e.message}`); } }
|
|
529
632
|
const nm = crypto.randomBytes(32);
|
|
530
633
|
const t2 = tx('dibs-pair2-v1', k.mid, pid, d, nb, box, k.idPub, nm, utf8(r.did));
|
|
531
634
|
const s2 = crypto.sign(null, t2, k.identity);
|
|
@@ -589,17 +692,23 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
589
692
|
// The route as api() will see it (src/web.mjs parses it the same way), so /api/x/../hook is /api/hook here too.
|
|
590
693
|
let route = null;
|
|
591
694
|
try { if (typeof m.path === 'string' && m.path.startsWith('/api/') && m.path.length <= 512) route = new URL(m.path, 'http://dibs').pathname; } catch {}
|
|
592
|
-
const
|
|
695
|
+
const talks = dev.talk === true && !!dev.tk;
|
|
696
|
+
// A talk call from a phone that may talk runs only with a fresh signature from its talking key.
|
|
697
|
+
const signed = route && talks && talkRoute(m.method, route) ? checkTalk(c.did, dev.tk, m, clock) : null;
|
|
698
|
+
const refused = route && remoteAccess(m.method, route, dev.act === true, !!signed?.body);
|
|
593
699
|
// An account paired through dibs connect --account gives this Mac its account key, so it can
|
|
594
700
|
// hand that key on to the account's new browsers (approve, below). Only such a device may.
|
|
595
701
|
if (route === '/api/account/join' && m.method === 'POST') res = joinAccount(dev, c.did, m.body);
|
|
596
702
|
else if (!METHODS.includes(m.method) || !route?.startsWith('/api/')) res = { status: 400, json: { error: 'not an API call' } };
|
|
597
|
-
else if (
|
|
703
|
+
else if (signed?.error) res = { status: 403, json: { error: signed.error, uv: true } };
|
|
704
|
+
else if (refused) res = { status: 403, json: { error: refused === 'look' ? lookOnlyText(c.did) : refused === 'talk' ? talkText(c.did) : LOCAL_ONLY_TEXT } };
|
|
705
|
+
// Only for the device this session belongs to, whatever the body says.
|
|
706
|
+
else if (route === '/api/push') res = registerPush(c.did, m.body, clock);
|
|
598
707
|
else {
|
|
599
708
|
let timer;
|
|
600
709
|
try {
|
|
601
710
|
res = await Promise.race([
|
|
602
|
-
call({ method: m.method, path: m.path, body: m.body ?? null, session: { kind: 'remote', device: c.did, name: dev.name, act: dev.act === true } }),
|
|
711
|
+
call({ method: m.method, path: m.path, body: signed ? signed.body : m.body ?? null, session: { kind: 'remote', device: c.did, name: dev.name, act: dev.act === true, talk: talks, ...(signed && { uv: true, proof: signed.proof }) } }),
|
|
603
712
|
new Promise(r => { timer = setTimeout(() => r({ status: 504, json: { error: 'dibs took too long to answer' } }), CALL_TIME); }),
|
|
604
713
|
]);
|
|
605
714
|
} catch (e) { res = { status: e.status || 500, json: { error: e.status ? e.message : 'dibs hit a bug answering that' } }; }
|
|
@@ -768,7 +877,13 @@ export function connectOnce(base, k, call) {
|
|
|
768
877
|
ws.send(t);
|
|
769
878
|
peer.sweep();
|
|
770
879
|
};
|
|
771
|
-
|
|
880
|
+
// What reaches the person goes to their phones as notifications (src/push.mjs).
|
|
881
|
+
const notifier = pusher({ mid: k.mid, phones: pushPhones, forget: forgetPush, send: text => (authed && ws.readyState === 1 ? (ws.send(text), true) : false) });
|
|
882
|
+
let pushFailed = false;
|
|
883
|
+
const notify = () => {
|
|
884
|
+
try { notifier.tick(); pushFailed = false; } catch (e) { if (!pushFailed) log(`relay: notifications: ${e.message}`); pushFailed = true; }
|
|
885
|
+
};
|
|
886
|
+
const watch = setInterval(() => { syncTokens(); notify(); }, TOKEN_SYNC);
|
|
772
887
|
// Browsers of this Mac's accounts waiting for its key: asked for every few seconds, only
|
|
773
888
|
// while this Mac belongs to an account.
|
|
774
889
|
// eph.conn names this connection in relay.json, so dibs connect --approve can tell when the
|
|
@@ -810,6 +925,7 @@ export function connectOnce(base, k, call) {
|
|
|
810
925
|
if (m.t === 'http' && typeof m.id === 'string') {
|
|
811
926
|
return mcpAnswer(m, k).catch(() => offJson(500)).then(r => { if (ws.readyState === 1) ws.send(httpRes(m.id, r)); });
|
|
812
927
|
}
|
|
928
|
+
if (m.t === 'push-res') { try { notifier.answer(m); } catch (e) { log(`relay: couldn't forget a dead notification token: ${e.message}`); } return; }
|
|
813
929
|
if (m.t === 'drops-res') { try { dropsAck(m); } catch (e) { log(`relay: couldn't note which codes the relay took: ${e.message}`); } return; }
|
|
814
930
|
if (m.t === 'open' && unb64u(m.ch, 16)) return peer.open(m.ch);
|
|
815
931
|
if (m.t === 'gone' && unb64u(m.ch, 16)) return peer.gone(m.ch);
|
|
@@ -828,9 +944,9 @@ export function connectOnce(base, k, call) {
|
|
|
828
944
|
const ago = t => (t ? `${dur(now() - t)} ago` : 'never');
|
|
829
945
|
|
|
830
946
|
// The remote half of `dibs pair`: --remote [--allow-actions], and its rows in --list and --revoke.
|
|
831
|
-
export async function pairRemote({ act = false } = {}) {
|
|
832
|
-
const p = newPairing({ act });
|
|
833
|
-
logChange('pair remote', { actions: act });
|
|
947
|
+
export async function pairRemote({ act = false, talk = false, person = null } = {}) {
|
|
948
|
+
const p = newPairing({ act, talk, person });
|
|
949
|
+
logChange('pair remote', { actions: p.act, ...(talk && { talk: true }), ...(person && { person }) });
|
|
834
950
|
// The code is shown only once the relay has taken it, so the one printed works. Another Mac
|
|
835
951
|
// holding the same drop name gets a fresh code for the same link; no answer from the relay
|
|
836
952
|
// (it's slow, or the connector isn't running) prints the code with a warning.
|
|
@@ -852,8 +968,10 @@ export async function pairRemote({ act = false } = {}) {
|
|
|
852
968
|
}
|
|
853
969
|
console.log(`It works once, until ${clockOf(p.exp)} (${p.life / MIN} minutes). That browser checks it reached this Mac by its fingerprint ${p.fp.slice(0, 16)}...`);
|
|
854
970
|
console.log(`The QR code as a link:\n${p.link}\n`);
|
|
855
|
-
console.log(
|
|
971
|
+
console.log(talk ? 'It can talk: message agents and answer their questions, asking for Face ID (or the passcode) on that phone every time. Agents read those as from you, via that phone. It can also act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never change the hook or your hours. Revoke it at once if the phone is lost.'
|
|
972
|
+
: act ? 'It can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never message agents, answer their questions, or change the hook or your hours. Revoke it if the device is lost.'
|
|
856
973
|
: 'It can only look. To let a browser change things too: dibs pair --remote --allow-actions');
|
|
974
|
+
if (person) console.log(`\nIt's ${person}'s phone: it hears about ${person}'s agents and what's everyone's (dibs people).`);
|
|
857
975
|
if (!s || s.startsWith('not running')) console.log(`\nThis Mac isn't connected to the relay yet. Turn it on: dibs service install relay`);
|
|
858
976
|
}
|
|
859
977
|
// dibs connect --account: a link a browser signed in to a dibs account opens, to add this Mac to
|
|
@@ -872,10 +990,11 @@ export function pairAccount({ act = false } = {}) {
|
|
|
872
990
|
}
|
|
873
991
|
const clockOf = t => new Date(t).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
|
874
992
|
|
|
993
|
+
export const level = d => (d.talk === true && d.tk ? 'can talk (Face ID each time) and act' : d.act === true ? 'can act' : 'look only');
|
|
875
994
|
export function listRemote() {
|
|
876
995
|
const ds = devices();
|
|
877
996
|
if (load().mcp) console.log(`(${mcpLine()})`);
|
|
878
|
-
for (const d of ds) console.log(`${d.id.slice(0, 8)} ${d.acct ? 'account' : 'remote'}: ${d.name}, ${d
|
|
997
|
+
for (const d of ds) console.log(`${d.id.slice(0, 8)} ${d.acct ? 'account' : 'remote'}: ${d.name}, ${level(d)} paired ${new Date(d.created).toLocaleString()}, last connected ${ago(d.seen)}`);
|
|
879
998
|
const accts = Object.entries(load().accounts);
|
|
880
999
|
for (const [aid, a] of accts) console.log(`${aid.slice(0, 8)} dibs account${a.label && a.label !== 'a browser' ? ` ${a.label}` : ''}: this Mac holds its key and approves its new browsers (dibs connect --approve) joined ${new Date(a.joined).toLocaleString()}`);
|
|
881
1000
|
const wait = waitingApprovals();
|
package/src/remote.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import path from 'node:path';
|
|
|
8
8
|
import crypto from 'node:crypto';
|
|
9
9
|
import dgram from 'node:dgram';
|
|
10
10
|
import { execFileSync } from 'node:child_process';
|
|
11
|
-
import { HOME, resCfg } from './config.mjs';
|
|
11
|
+
import { HOME, resCfg, isEnv } from './config.mjs';
|
|
12
12
|
import { identity } from './proc.mjs';
|
|
13
13
|
import { OS } from './platform.mjs';
|
|
14
14
|
import { run } from './commands.mjs';
|
|
@@ -19,8 +19,9 @@ import { rulesAbove, readRules, ruleAllows, isRuleFile, isCode, normCode, codeKe
|
|
|
19
19
|
import { projectKey } from './files.mjs';
|
|
20
20
|
import { jobSize } from './simpool.mjs';
|
|
21
21
|
import { defaultMaxWait } from './acquire.mjs';
|
|
22
|
-
import { logChange } from './owner.mjs';
|
|
22
|
+
import { logChange, AGENT_ENV } from './owner.mjs';
|
|
23
23
|
import { ondemandOf } from './ondemand.mjs';
|
|
24
|
+
import { described } from './declare.mjs';
|
|
24
25
|
|
|
25
26
|
export const REMOTE = path.join(HOME, 'remote.json');
|
|
26
27
|
export const DEFAULT_PORT = 7420;
|
|
@@ -167,7 +168,8 @@ export function macOnly(cmd, cwd) {
|
|
|
167
168
|
// machine that isn't the coordinator doesn't list them, so only the
|
|
168
169
|
// coordinator's own waiters ship on their own.
|
|
169
170
|
export function mayShip(me, cfg, cwd) {
|
|
170
|
-
|
|
171
|
+
// An environment's lease and memory live on this machine: run anywhere else, two agents could hold it at once.
|
|
172
|
+
if (me.kind !== 'run' || !me.cmd || me.res.some(r => r.startsWith('files:') || isEnv(r))) return false;
|
|
171
173
|
try { if (!ondemandOf(cfg).length) return false; } catch { return false; }
|
|
172
174
|
try { if (needsOs(cfg, me.res) === 'macos') return false; } catch { return false; }
|
|
173
175
|
if (macOnly(me.cmd, cwd) || !remoteConf(() => null) || namesPaths(me.cmd)) return false;
|
|
@@ -281,9 +283,19 @@ export async function remoteRun(o, cfg) {
|
|
|
281
283
|
say('not connected to a coordinator (dibs join), so running here');
|
|
282
284
|
return run(o, cfg);
|
|
283
285
|
}
|
|
284
|
-
if (!o.cmd || !o.cmd.length) die('nothing to run. Use: dibs run <resource> --anywhere -- <command>');
|
|
286
|
+
if (!o.cmd || !o.cmd.length) die('nothing to run. Use: dibs run <resource> --anywhere -m "..." -- <command>');
|
|
287
|
+
// A credential never leaves this machine: not in the command's text, and not in the $NAME
|
|
288
|
+
// dibs secret run set for it (a job elsewhere runs without this process's environment).
|
|
289
|
+
const inCmd = (await import('./prints.mjs')).find(o.cmd.join(' '));
|
|
290
|
+
if (inCmd.length) die(`this command has the value of the secret ${inCmd[0].name} in it, and dibs won't send that to another machine. Nothing was sent.`);
|
|
291
|
+
if (process.env.DIBS_SECRET_NAMES) {
|
|
292
|
+
const msg = `it runs with the secret ${process.env.DIBS_SECRET_NAMES} (dibs secret run), which never leaves this machine`;
|
|
293
|
+
if (o.on && o.on !== rc.name) die(`${msg}, so it can't go to ${o.on}. Nothing was sent.`);
|
|
294
|
+
say(`${msg}; running here`);
|
|
295
|
+
return run(o, cfg);
|
|
296
|
+
}
|
|
285
297
|
const res = [...new Set(o.res)];
|
|
286
|
-
if (!res.length) die('name a resource, e.g. dibs run test --anywhere -- npm test');
|
|
298
|
+
if (!res.length) die('name a resource, e.g. dibs run test --anywhere -m "run the unit tests" -- npm test');
|
|
287
299
|
const id = identity(o);
|
|
288
300
|
// The project's .dibs.json decides before anything is sent: --on a machine it
|
|
289
301
|
// doesn't allow is refused, and --anywhere stays here rather than go there.
|
|
@@ -340,7 +352,8 @@ export async function remoteRun(o, cfg) {
|
|
|
340
352
|
|
|
341
353
|
const job = await call(rc, 'POST', '/jobs', {
|
|
342
354
|
...need, machine: place.machine, cmd: o.cmd, cwdRel: wc.cwdRel, files: wc.files, bring,
|
|
343
|
-
who: id.who, agent: id.agent, label: id.label, purpose: o.purpose || '', prio: o.prio, by: o.by, est: o.est,
|
|
355
|
+
who: id.who, agent: id.agent, label: id.label, purpose: o.purpose || '', prio: o.prio, by: o.by, est: o.est, timeLimit: o.timeLimit,
|
|
356
|
+
...((AGENT_ENV.some(k => process.env[k]) || id.spid) && { byAgent: true }), // the worker runs it as an agent's, never the person's
|
|
344
357
|
disk: o.disk, ports: o.ports, repo: projectKey(process.cwd()), // its project, which one-per-project resources go by there
|
|
345
358
|
// Decided here: the worker isn't in a Claude Code session, but this end, which waits for it, may be.
|
|
346
359
|
...((o.maxWait ?? defaultMaxWait()) === Infinity ? { wait: true } : { maxWait: o.maxWait }),
|
|
@@ -503,7 +516,7 @@ async function joinWithCode(o, code) {
|
|
|
503
516
|
logChange('join', { url: found.url, code: true }); // never the code or the token
|
|
504
517
|
console.log(`joined ${found.name || 'the coordinator'} at ${found.url} as ${r.name} (coordinator dibs ${r.version})`);
|
|
505
518
|
console.log(` take jobs on this machine: dibs service install worker (or run dibs worker in a terminal)`);
|
|
506
|
-
console.log(` send a job: dibs run test --anywhere -- npm test`);
|
|
519
|
+
console.log(` send a job: dibs run test --anywhere -m "run the unit tests" -- npm test`);
|
|
507
520
|
}
|
|
508
521
|
|
|
509
522
|
// dibs join <url> <token>, or dibs join <code>: connect this machine to a coordinator.
|
|
@@ -523,7 +536,7 @@ export async function join(o) {
|
|
|
523
536
|
saveRemote(rc);
|
|
524
537
|
console.log(`joined ${rc.url} as ${rc.name} (coordinator dibs ${hello.version}, ${hello.machines.length} machine${hello.machines.length === 1 ? '' : 's'} online${hello.machines.length ? `: ${hello.machines.join(', ')}` : ''})`);
|
|
525
538
|
console.log(` take jobs on this machine: dibs service install worker (or run dibs worker in a terminal)`);
|
|
526
|
-
console.log(` send a job: dibs run test --anywhere -- npm test`);
|
|
539
|
+
console.log(` send a job: dibs run test --anywhere -m "run the unit tests" -- npm test`);
|
|
527
540
|
}
|
|
528
541
|
|
|
529
542
|
const sendsNote = (r, name) => { const s = r.sends?.[name]; return !s ? '' : s.length ? `sends only ${s.join(',')}` : 'sends nothing'; };
|
|
@@ -582,7 +595,7 @@ export async function machines(o) {
|
|
|
582
595
|
console.log(`\n${bold('Jobs sent between machines')}`);
|
|
583
596
|
for (const j of jobs)
|
|
584
597
|
console.log(` #${String(j.id).padEnd(3)} ${(j.agent || j.who).padEnd(20)} ${`${j.from} -> ${j.machine}`.padEnd(22)} ${(j.state === 'done' ? `done, exit ${j.code}` : j.state).padEnd(12)}`
|
|
585
|
-
+ ` ${dur(t - j.created).padStart(6)} ${j.res.join(',')}
|
|
598
|
+
+ ` ${dur(t - j.created).padStart(6)} ${j.res.join(',')} "${described(j)}" ${dim(j.cmd.join(' ').slice(0, 40))}`);
|
|
586
599
|
}
|
|
587
|
-
console.log(`\n${dim(`Coordinator: ${rc.url}, dibs ${r.version}. Send a job: dibs run <resource> --anywhere -- <command>`)}`);
|
|
600
|
+
console.log(`\n${dim(`Coordinator: ${rc.url}, dibs ${r.version}. Send a job: dibs run <resource> --anywhere -m "..." -- <command>`)}`);
|
|
588
601
|
}
|