@rfany/rf 0.9.0 → 0.11.0

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 (3) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/rf.mjs +347 -88
package/README.md CHANGED
@@ -6,4 +6,4 @@ People's command line for [rollforward](https://github.com/spoj/rollforward): wh
6
6
  rf login https://rollforward.example.com
7
7
 
8
8
  rf opens the page, which asks you to allow it if it shows the same code as rf; or make a token on the page, under Tokens, and
9
- `rf login URL TOKEN`. `rf` alone lists the commands; `rf help` is the guide for an agent, read before it first uses rf.
9
+ `rf login URL TOKEN`. `rf` alone lists the commands and `rf help COMMAND` gives one's usage; `rf help` is the guide for an agent, read before it first uses rf.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfany/rf",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "rollforward's command line for people: what its page does, from a shell or a desktop agent, as you",
5
5
  "license": "MIT",
6
6
  "repository": { "type": "git", "url": "git+https://github.com/spoj/rollforward.git", "directory": "cli" },
package/rf.mjs CHANGED
@@ -6,14 +6,59 @@ import { spawn } from 'node:child_process';
6
6
  import { homedir, hostname } from 'node:os';
7
7
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
8
8
 
9
- const USAGE = `rf login URL [TOKEN] without a TOKEN, through the browser: allow it on the page, where it shows rf's code
10
- rf ls
11
- rf pull PATH DIR [--delete] [-n|--dry-run] [--exclude PATTERN]...
9
+ // A failure is one line, rf's own or the server's, never a stack.
10
+ process.on('uncaughtException', e => {
11
+ console.error(`rf: ${e.message}${e.cause instanceof Error ? `: ${e.cause.message}` : ''}`);
12
+ process.exit(1);
13
+ });
14
+
15
+ const USAGE = `rf login URL [TOKEN] without a TOKEN, through the browser: type rf's code on the page, and allow it
16
+ rf ls [--json] every workspace, series and instance you see, with its status, runner, asks waiting and wakes
17
+ rf waiting [--json] what waits on you: asks, sign-offs and notes, requests to start an instance, proposals,
18
+ expired logins, and hosts a run's browser on a website of your own was refused
19
+ rf show PATH [--json] an instance: its items, the threads that wait on someone, by id, and its last run
20
+ rf log PATH [--since SEQ] [--follow] [--json] its log, a line an entry, after SEQ; --follow prints more as they come;
21
+ --json prints the entries as they are, a line each
22
+ rf cat PATH/FILE one file, to stdout
23
+ rf pull PATH DIR [--delete] [-n|--dry-run] [--exclude PATTERN]... [--max-size SIZE]
12
24
  PATH's files into DIR as rsync copies them, whole, if their size or time differ: PATH/ fills DIR,
13
- PATH makes DIR/<its name>, / is all you see; --delete removes what the server no longer has
14
- rf help how rollforward works and how to use rf, for an agent
25
+ PATH makes DIR/<its name>, / is all you see; --delete removes what the server no longer has;
26
+ --max-size skips files bigger than SIZE, such as 50M
27
+ rf help [COMMAND] how rollforward works and how to use rf, for an agent, or COMMAND's usage
28
+ rf --version rf's own version, to tell whether it's older than what the guide names
15
29
  rf comment PATH TEXT [--item ID] [--ref REF] [--thread T] [--wait] a new thread, or a reply in T, as to an agent's ask
16
30
  rf upload PATH FILE [--onto ITEM] [--output]
31
+ rf resolve PATH THREAD [TEXT] resolves a thread, with TEXT as a last word; nothing wakes
32
+ rf signoff PATH THREAD approve|reject [TEXT] the runner's answer to a sign-off the agent asks for, which commits the folder
33
+ rf close PATH [--as-series NAME] the runner stands by it: closed, it's an example; a task closes as a one-off, or as the first
34
+ instance of the series NAME it becomes
35
+ rf abandon PATH the runner leaves it as it is, neither an example nor a starting point
36
+ rf interrupt PATH stops its run
37
+ rf takeover PATH [--creds OFFER,...] you run it from now on, with those offers of your logins ticked
38
+ rf creds PATH [--set OFFER,...|--clear] what its runs may use: its runner's ticks, and the offers of your logins; --set
39
+ ticks anew, as its runner
40
+ rf rename PATH NAME an instance, a series or a workspace, by its path
41
+ rf new task WORKSPACE [LABEL] [--creds OFFER,...] [--comment TEXT] a one-off task, Untitled until LABEL or its first
42
+ comment names it; --comment starts its run
43
+ rf new instance SERIES LABEL [--creds OFFER,...] the series' next instance, which runs at once
44
+ rf new series PATH NAME the task at PATH becomes the series NAME, itself its first instance
45
+ rf new workspace NAME yours to own, for admins and those they grant create
46
+ rf copy PATH LABEL [--creds OFFER,...] a closed or abandoned instance, copied into a new open one without its agent session
47
+ rf share PATH on|off [--creds OFFER,...] the series' people, and their agents, wake it as you, with those offers ticked;
48
+ off stops it, for its sharer or its workspace's owners
49
+ rf archive PATH [--undo] a workspace or a series leaves the sidebar as it is, until --undo brings it back
50
+ rf request start|drop ID [--creds OFFER,...] a request to start an instance, by the ID rf waiting and rf wakes print
51
+ rf logins [--json] your logins, each with its state, keepalive and offers; you sign in to them on the page
52
+ rf logins offer|unoffer LOGIN SOURCE|OFFER what a login offers runs: Microsoft 365's (m365) mailboxes, sites, folders and
53
+ files, by address or link, a Databricks login's SQL warehouses, by link; unoffer takes the
54
+ OFFER rf logins lists
55
+ rf logins allow SITE HOST a host the pages of SITE, your own website or, for admins, another, need
56
+ rf logins signout LOGIN
57
+ rf site add NAME URL a website of your own, for those granted sites, whose sign-in starts at URL; you sign in to it
58
+ on the page
59
+ rf site remove NAME a website of yours, with your login to it
60
+ rf correct PATH TEXT [--item ID] [--ref REF] [--superseded] [--see LABEL] a closed instance, or its item ID at REF, is
61
+ wrong, or superseded, as LABEL, another instance of its series, shows; it can't be withdrawn
17
62
  rf wake PATH AT [--label LABEL] [--days DAYS] | rf wake --cancel ID
18
63
  AT now, +<n>m|h|d or a date; PATH an open instance, or a series with LABEL; DAYS, such as
19
64
  mon-fri, repeats it weekly at AT's time; rf ls shows each wake's ID
@@ -27,8 +72,14 @@ rf status [--long MIN] [--json] what goes on and what's stuck: runs going, fla
27
72
  rf indexes [--json] each index of a source you index, all for admins: its kind, items and size, and per person
28
73
  its phase, crawl or follow, pages read, when last caught up, and its error and next try
29
74
  rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] [--json]
30
- a line per run: start, path, run, outcome, time, cost, what started it, summary or error
31
- rf costs [PATH] [--since DATE] [--by workspace|series|person|day] [--json] totals, runs and cost per run; person is the runner
75
+ a line per run: start, path, run, outcome, time, cost, what started it, summary or error;
76
+ the outcome is done, interrupted by a person, cut by a restart, running, or failed, for
77
+ credits, policy, time limit or other
78
+ rf costs [PATH] [--since DATE] [--by workspace|series|person|day|outcome] [--json] totals, runs and cost per run; person
79
+ is the runner; runs leave out those a restart cut, as the next run carries each on
80
+ rf activity [PATH] [--since DATE] [--json] per instance, what people said, uploaded and closed, and each run's report
81
+ rf wakes [PATH] [--json] each series' pending wakes and requests to start an instance, and when a wake of it last
82
+ fired, and each instance's pending wakes
32
83
  rf people WORKSPACE [--set FILE|-] [-n] [--force] its owners and admins: its people as lines of owner|member EMAIL-OR-GROUP,
33
84
  each with a comment; --set replaces them, -n shows the changes, --force hides open instances
34
85
  from their runners
@@ -42,25 +93,29 @@ rf people [--set FILE|-] [-n] [--force] everyone as lines of ROLE EMAIL, each
42
93
  listed and adds new ones, removing no one
43
94
  rf user add EMAIL [admin] | role EMAIL admin|user [--force] | disable EMAIL | enable EMAIL | signout EMAIL | remove EMAIL
44
95
  rf connection set NAME TYPE [--SETTING VALUE]... an outside system runs reach as their runner, by a login each person makes:
45
- graph, Microsoft 365, with no settings; databricks, --host HOST --warehouse ID, a workspace
46
- and its SQL warehouse; website, --url URL [--hosts HOST,...] [--title TITLE] [--writeback
47
- false] [--header NAME] [--keepalive PAGE --every 10m [--hours 08:00-19:00]] [--people
48
- EMAIL|GROUP,...], where people sign in, the other hosts its pages need, such as
96
+ graph, Microsoft 365, and databricks, Azure Databricks, each with no settings, as each
97
+ person adds what their login offers; website, --url URL [--hosts HOST,...] [--title TITLE]
98
+ [--writeback false] [--header NAME] [--keepalive PAGE] [--every 10m]
99
+ [--people EMAIL|GROUP,...], where people sign in, the other hosts its pages need, such as
49
100
  *.example.com, whether a run's browser writes its state back, a header its sign-in needs
50
- that its pages never send, such as x-bot-token, whose value each person gives, a page, by
51
- its address or path, such as https://patriarch.patrina.net/PatriArchMVC/, to load in each
52
- live login's browser every so often, in office hours on weekdays if given, so idle sessions
53
- stay alive, and who alone may use it, by email or Entra group id
101
+ that its pages never send, such as x-bot-token, whose value each person gives, the page a
102
+ login kept alive loads, by its address or path, such as
103
+ https://patriarch.patrina.net/PatriArchMVC/, else the address, and how often, 10m unless
104
+ given, and who alone may use it, by email or Entra group id
54
105
  rf connection remove NAME
106
+ rf connection off|on NAME a website switched off, for no one to use, such as a person's own, or on again
55
107
  rf brand [--text TEXT] [--logo FILE] [--clear] the deployment's text and logo, a .png, .jpg, .gif, .webp or .svg, which top
56
108
  the sidebar and are the page's title and icon; --clear goes back to the plain look, and with
57
109
  no option it prints them
58
- rf can [CAP [EMAIL|GROUP,...] [--clear]] what users may do beyond the rest, as admins may: publish, push skills, and
59
- create, make workspaces; a list grants CAP to those emails and Entra group ids in place of
60
- whom it had, --clear to no one, and with neither it prints whom each is granted to`;
110
+ rf can [CAP [EMAIL|GROUP,...] [--clear]] what users may do beyond the rest, as admins may: publish, push skills;
111
+ create, make workspaces; sites, add websites of their own; and keepalive, keep their
112
+ website logins alive for up to a week as they sign in; a list grants CAP to those
113
+ emails and Entra group ids in place of whom it had, --clear to no one, and with neither it
114
+ prints whom each is granted to`;
61
115
 
62
116
  const GUIDE = `rollforward runs a team's recurring work, such as a weekly borrowing base or a month-end reconciliation, with an agent
63
- that does each period's work and people who check it. rf does what its page does, as you.
117
+ that does each period's work and people who check it. rf does what its page does, as you: rf alone lists its commands, rf help
118
+ COMMAND gives one's usage, every read takes --json, and a failure is one line on stderr, with exit code 1.
64
119
 
65
120
  What there is
66
121
  - A workspace holds series, and its people. A series is one recurring job; an instance is one period of it, labelled such as
@@ -84,25 +139,28 @@ What rf pull copies, the folders as the agent sees them
84
139
  error), close, and the rest
85
140
  upload/ what people uploaded, their comments' attachments in upload/attachments/
86
141
  working/ what the agent made, its scripts, and process.md, how it does this series
87
- session/ each run's session: every message and tool call of it
142
+ session/ each session's transcript, which may carry several runs: every message and tool call
88
143
  browser/ each run's browser requests, and its screenshots
89
- skills/ the skills the latest run loaded
90
144
  names.tsv each instance in the latest run's reach, id<TAB>/work/<workspace>/<series>/<label>: names can
91
145
  change, so where a path in a file doesn't match, look its id up in the names.tsv of the commit
92
146
  that last changed the file (git log -1 -- FILE, then git show H:names.tsv), and its name now in
93
147
  rf ls
94
- The copy is read-only, and only rf changes what's on the server: comment, upload and wake.
148
+ The copy is read-only: only rf's commands change what's on the server.
95
149
 
96
150
  Usual work
97
- - What waits on me: rf ls, then the asks in that instance's log.jsonl, ask true, whose thread has nothing after them.
98
- - Answer an ask: rf comment PATH TEXT --thread T --wait, which prints what the agent says back.
151
+ - What waits on me: rf waiting, then rf show PATH, which names each thread that waits by its id.
152
+ - Answer an ask: rf comment PATH TEXT --thread T --wait, which prints what the agent says back; a sign-off, as its runner:
153
+ rf signoff PATH T approve|reject [TEXT]. Close an instance you stand by: rf close PATH.
154
+ - Take an instance over: rf creds PATH lists the offers of your logins, and rf takeover PATH --creds OFFER,... ticks them.
155
+ - Your logins: rf logins lists them, with what each offers, and an expired one's link to sign in again on the page.
99
156
  - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output].
100
- - Start an instance: rf wake SERIES now --label LABEL, which starts it as whoever shares the series, else asks on the page for
101
- someone to start it; take one you run up later: rf wake PATH +2h.
102
- - Read what a run did: rf pull PATH/ DIR, then its report and done entries in log.jsonl, the files in working/, and session/ for
103
- every step.
157
+ - Start an instance: rf new instance SERIES LABEL, as you, or rf wake SERIES now --label LABEL, which starts it as whoever
158
+ shares the series, else asks on the page for someone to start it; take one you run up later: rf wake PATH +2h. A one-off:
159
+ rf new task WORKSPACE --comment TEXT, which becomes a series with rf new series PATH NAME.
160
+ - Read what a run did: rf show PATH for its last run, rf log PATH for every entry, --follow as they come, and rf cat PATH/FILE
161
+ for a file; rf pull PATH/ DIR copies the folder, with session/ for every step.
104
162
 
105
- Watching over it, for admins and power users; each sees what the caller sees, and takes --json
163
+ Watching over it, for admins and power users; each sees what the caller sees
106
164
  - What's stuck: rf status lists runs going, flagging those past --long MIN (30); queued runs, since when and why: their series is
107
165
  running, the RF_MAX_RUNS cap, or memory; what waits on whom since when: asks, notes for runners, expired logins and the instances
108
166
  they hold, and requests to start; open instances whose last run failed; and indexes crawling or failing.
@@ -118,27 +176,30 @@ Watching over it, for admins and power users; each sees what the caller sees, an
118
176
  does); for a workspace it replaces its people. A change that would hide an open instance from the person who runs it is refused,
119
177
  naming them, unless --force: have someone who stays take those over first.`;
120
178
 
179
+ // A command's usage, as USAGE gives it; with none known, every command's.
180
+ const usage = (c ) => (c && USAGE.split(/\n(?=\S)/).map(e => e.trimEnd()).filter(e => e.split(/\s/)[1] === c).join('\n')) || USAGE;
181
+
121
182
  const config = join(homedir(), '.config', 'rollforward.json');
122
183
  const [cmd, ...argv] = process.argv.slice(2);
123
184
  const flags = {}, excludes = [], args = [];
124
185
  for (let i = 0; i < argv.length; i++) {
125
186
  const flag = argv[i] === '-n' ? 'dry-run' : argv[i].match(/^--(.+)$/)?.[1];
126
187
  if (!flag) args.push(argv[i]);
127
- else if (['wait', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear'].includes(flag)) flags[flag] = true;
128
- else if (argv[i + 1] === undefined) {
129
- console.error(`--${flag} takes a value\n\n${USAGE}`);
130
- process.exit(2);
131
- } else if (flag === 'exclude') excludes.push(argv[++i]);
188
+ else if (['wait', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo'].includes(flag)) flags[flag] = true;
189
+ else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
190
+ else if (flag === 'exclude') excludes.push(argv[++i]);
132
191
  else flags[flag] = argv[++i];
133
192
  }
134
- if (cmd === 'help') {
135
- console.log(GUIDE);
193
+ if (cmd === '--version') {
194
+ // Its package's: cli/ in the repo, beside rf.mjs once published.
195
+ console.log(JSON.parse(readFileSync(new URL(import.meta.url.endsWith('.ts') ? '../cli/package.json' : 'package.json', import.meta.url), 'utf8')).version);
136
196
  process.exit();
137
197
  }
138
- if (cmd !== 'login' && !existsSync(config)) {
139
- console.error(`Sign in first: rf login URL\n\n${USAGE}`);
140
- process.exit(2);
198
+ if (!cmd || cmd === 'help') {
199
+ console.log(!cmd ? USAGE : args[0] ? usage(args[0]) : GUIDE);
200
+ process.exit();
141
201
  }
202
+ if (cmd !== 'login' && !existsSync(config)) throw new Error('sign in first: rf login URL');
142
203
  let { url, token } = cmd === 'login' ? { url: args[0]?.replace(/\/$/, ''), token: args[1] } : JSON.parse(readFileSync(config, 'utf8'));
143
204
 
144
205
  async function api(path , init = {}) {
@@ -155,6 +216,26 @@ async function find(path ) {
155
216
  if (!series || (l !== undefined && !inst)) throw new Error(`nothing you can see at ${path}`);
156
217
  return { series, inst, at: inst ? `/api/instances/${inst.id}` : '' };
157
218
  }
219
+ async function instanceAt(path ) {
220
+ const { series, inst, at } = await find(path);
221
+ if (!inst) throw new Error(`${path} is a series: name one of its instances, as rf ls lists them`);
222
+ return { series, inst, at };
223
+ }
224
+ async function seriesAt(path ) {
225
+ const { series, inst } = await find(path);
226
+ if (inst) throw new Error(`${path} is an instance: name its series`);
227
+ return series;
228
+ }
229
+ async function workspaceNamed(name ) {
230
+ const ws = (await get('/api')).find(w => w.name === name);
231
+ if (!ws) throw new Error(`no workspace ${name}`);
232
+ return ws;
233
+ }
234
+ // An instance's path as rf ls prints it, by its id.
235
+ const pathOf = async (id ) => (await get('/api')).flatMap(w => w.series.flatMap(s => s.instances.filter(i => i.id === id).map(i => `${w.name}/${s.name}/${i.label}`)))[0];
236
+ // The offers of your logins that --creds or --set name, ticked for an instance, and what ticking them agrees to.
237
+ const ticks = () => flags.clear ? [] : String(flags.creds ?? flags.set ?? '').split(',').map(o => o.trim()).filter(Boolean);
238
+ const consent = (offers ) => offers.length ? `, ticking ${offers.join(', ')}: you agree that agents carry these credentials while acting as you` : ', with no logins ticked';
158
239
 
159
240
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
160
241
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
@@ -190,11 +271,15 @@ const excluded = (rel ) => globs.some(([whole, re]) => rel.split('/').som
190
271
  // fetched, and given the server's time, so the next pull compares against it. Nothing is kept besides the files.
191
272
  async function pull(path , dir ) {
192
273
  const at = path.replace(/^\/+/, ''), from = at.replace(/\/+$/, ''), dry = !!flags['dry-run'];
274
+ const size = /^(\d+)([KMG]?)$/i.exec(String(flags['max-size'] ?? '0'));
275
+ if (!size) throw new Error(`--max-size: a size such as 500K, 50M or 2G, not ${flags['max-size']}`);
276
+ const max = flags['max-size'] === undefined ? Infinity : Number(size[1]) * 1024 ** ' KMG'.indexOf(size[2].toUpperCase() || ' ');
193
277
  const list = await get(`/api/files?path=${encodeURIComponent(from)}`);
194
278
  if (!list.length) throw new Error(`nothing you can see at ${path}`);
195
279
  const into = !from || at.endsWith('/') ? resolve(dir) : under(resolve(dir), from.slice(from.lastIndexOf('/') + 1)), rel = (f ) => f.path.slice(from ? from.length + 1 : 0);
196
280
  if (!into) throw new Error(`${from} can't be a name here: pull ${from}/ into a folder of your choosing`);
197
- let fetched = 0, same = 0, deleted = 0, failed = 0;
281
+ let fetched = 0, same = 0, deleted = 0, failed = 0, big = 0;
282
+ const fetches = [];
198
283
  for (const f of list.filter(f => !excluded(rel(f)))) {
199
284
  const local = rel(f) ? under(into, rel(f)) : into, st = local && existsSync(local) ? statSync(local) : undefined;
200
285
  if (!local) {
@@ -205,15 +290,26 @@ async function pull(path , dir ) {
205
290
  same++;
206
291
  continue;
207
292
  }
208
- console.log(`${st ? 'changed' : 'new'} ${f.path}`);
209
- try {
210
- if (!dry) write(local, f.text ?? new Uint8Array(await (await api(f.url )).arrayBuffer()), f.mtime);
211
- fetched++;
212
- } catch (e) {
213
- failed++;
214
- console.error(`${f.path}: ${(e ).message}`);
293
+ if (f.size > max) {
294
+ console.log(`skipped ${f.path}: ${f.size} bytes, over --max-size`);
295
+ big++;
296
+ continue;
215
297
  }
298
+ fetches.push(async () => {
299
+ console.log(`${st ? 'changed' : 'new'} ${f.path}`);
300
+ try {
301
+ if (!dry) write(local, f.text ?? new Uint8Array(await (await api(f.url )).arrayBuffer()), f.mtime);
302
+ fetched++;
303
+ } catch (e) {
304
+ failed++;
305
+ console.error(`${f.path}: ${(e ).message}`);
306
+ }
307
+ });
216
308
  }
309
+ // Up to 8 files are fetched at once, each started in the list's order.
310
+ await Promise.all(Array.from({ length: 8 }, async () => {
311
+ for (let next; (next = fetches.shift());) await next();
312
+ }));
217
313
  if (flags.delete && list.some(rel) && existsSync(into)) {
218
314
  const keep = new Set(list.map(rel)), mine = (d ) => readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? mine(join(d, e.name)) : [join(d, e.name)]);
219
315
  for (const p of mine(into)) {
@@ -226,15 +322,15 @@ async function pull(path , dir ) {
226
322
  const prune = (d ) => { for (const e of readdirSync(d, { withFileTypes: true })) if (e.isDirectory()) prune(join(d, e.name)); if (d !== into && !readdirSync(d).length) rmdirSync(d); };
227
323
  if (!dry) prune(into);
228
324
  }
229
- console.log(`${dry ? 'would fetch' : 'fetched'} ${fetched}, ${same} up to date${flags.delete ? `, ${dry ? 'would delete' : 'deleted'} ${deleted}` : ''}${failed ? `, ${failed} failed` : ''}, in ${into}`);
325
+ console.log(`${dry ? 'would fetch' : 'fetched'} ${fetched}, ${same} up to date${big ? `, ${big} over ${flags['max-size']}` : ''}${flags.delete ? `, ${dry ? 'would delete' : 'deleted'} ${deleted}` : ''}${failed ? `, ${failed} failed` : ''}, in ${into}`);
230
326
  if (failed) process.exitCode = 1;
231
327
  }
232
328
 
233
329
  // The browser's sign-in: the server makes a request, the person allows it on the page, which shows its code, and rf collects the token.
234
330
  async function browserToken() {
235
331
  const { id, code } = await (await fetch(`${url}/auth/cli`, { method: 'POST', body: JSON.stringify({ name: `rf on ${hostname()}` }) })).json();
236
- const link = `${url}/cli?code=${code}`;
237
- console.log(`Open ${link}\nand allow rf there if the page shows the code ${code}.`);
332
+ const link = `${url}/cli`;
333
+ console.log(`Open ${link}\nand type the code ${code} there.`);
238
334
  spawn(process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open', [link], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
239
335
  for (;;) {
240
336
  await new Promise(ok => setTimeout(ok, 2000));
@@ -250,21 +346,63 @@ if (cmd === 'login' && url) {
250
346
  mkdirSync(dirname(config), { recursive: true });
251
347
  writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
252
348
  console.log(`signed in as ${me.email}`);
253
- } else if (cmd === 'ls') {
254
- const wakes = (list ) => {
255
- for (const k of list) console.log(` wake ${k.id} ${k.at}${k.label ? ` starts ${k.label}` : ''}${k.days ? `, then each ${k.days.join(', ')}` : ''}`);
256
- };
257
- for (const w of await get('/api')) for (const s of w.series) {
258
- console.log(`${w.name}/${s.name}${s.requests.length ? ` ${s.requests.length} asking to start` : ''}`);
259
- wakes(s.wakes);
260
- for (const i of s.instances) {
261
- console.log(`${w.name}/${s.name}/${i.label} ${i.status}${i.running ? ', running' : ''}${i.asks.length ? `, ${i.asks.length} asks waiting` : ''}, runner ${i.runner}`);
262
- wakes(i.wakes);
349
+ } else if (cmd === 'ls' && !args.length) {
350
+ const rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
351
+ { path: `${w.name}/${s.name}`, id: s.id, requests: s.requests.length, wakes: s.wakes },
352
+ ...s.instances.map(i => ({ path: `${w.name}/${s.name}/${i.label}`, id: i.id, status: i.status, running: i.running, asks: i.asks.length, runner: i.runner, wakes: i.wakes })),
353
+ ]));
354
+ if (flags.json) console.log(JSON.stringify(rows, null, 1));
355
+ else for (const r of rows) {
356
+ console.log(r.status ? `${r.path} ${r.status}${r.running ? ', running' : ''}${r.asks ? `, ${r.asks} asks waiting` : ''}, runner ${r.runner}` : `${r.path}${r.requests ? ` ${r.requests} asking to start` : ''}`);
357
+ for (const k of r.wakes) console.log(` wake ${k.id} ${k.at}${k.label ? ` starts ${k.label}` : ''}${k.days ? `, then each ${k.days.join(', ')}` : ''}`);
358
+ }
359
+ } else if (cmd === 'waiting' && !args.length) {
360
+ const [me, s, all] = await Promise.all([get('/me'), get('/api/status'), get('/api')]), mine = (who ) => (who ?? me.email) === me.email;
361
+ const series = all.flatMap(w => w.series.map(x => ({ ...x, path: `${w.name}/${x.name}` })));
362
+ const rows = [
363
+ ...s.asks.filter(a => a.who === me.email).map(a => ({ kind: a.signoff ? 'sign-off' : a.note ? 'note' : 'ask', path: a.path, since: a.since, text: a.text })),
364
+ ...series.flatMap(x => x.requests.filter(r => mine(r.who)).map(r => ({ kind: 'request', path: x.path, since: r.at, id: r.id, text: `${r.from} asks to start ${r.label}` }))),
365
+ ...all.filter(w => w.manage && w.proposal?.into === w.id).map(({ proposal: p }) => ({ kind: 'proposal', path: p.to, since: p.at, text: `${p.by} proposes to ${p.kind === 'merge' ? `merge ${p.from} into it` : `move ${p.from}/${p.series} to it`}` })),
366
+ ...s.expired.filter(e => e.who === me.email).map(e => ({ kind: 'expired', login: e.login, holding: e.holding, text: `your ${e.login} login expired` })),
367
+ ...series.flatMap(x => x.instances.flatMap(i => i.refused.map(r => ({ kind: 'refused', path: `${x.path}/${i.label}`, since: r.at, site: r.site, hosts: r.hosts, text: `run ${r.run}'s browser on ${r.site} was refused ${r.hosts.join(', ')}` })))),
368
+ ];
369
+ if (flags.json) console.log(JSON.stringify(rows, null, 1));
370
+ else console.log(rows.map(r => `${r.kind} ${r.path ?? r.login}${r.since ? ` since ${when(r.since)}` : ''}${r.id ? `, request ${r.id}` : ''}: ${r.text.split('\n')[0].slice(0, 120)}`).join('\n') || 'Nothing waits on you.');
371
+ } else if (cmd === 'show' && args.length === 1) {
372
+ const { inst, at } = await instanceAt(args[0]), { doc, log, run, queued, runner } = await get(at);
373
+ const threads = Map.groupBy(log.filter(e => ['comment', 'resolve', 'signoff'].includes(e.op)), e => e.thread);
374
+ const waiting = doc.status !== 'open' ? [] : [...threads.values()].flatMap(t => {
375
+ const e = t.at(-1);
376
+ return e.op === 'comment' && ((e.by === 'agent' && e.ask) || e.note)
377
+ ? [{ thread: e.thread, kind: e.signoff ? 'sign-off' : e.ask ? 'ask' : 'note', for: e.to ?? runner.by, by: e.by, seq: e.seq, item: t[0].item, ref: t[0].ref, text: e.text }] : [];
378
+ });
379
+ const done = log.findLast(e => e.op === 'done'), report = done && log.findLast(e => e.op === 'report' && e.run === done.run);
380
+ const last = done ? { run: done.run, cost: done.cost, summary: done.summary ?? null, error: done.error ?? null, report: report?.text ?? null } : null;
381
+ if (flags.json) console.log(JSON.stringify({ path: args[0], id: inst.id, status: doc.status, runner: runner.by, running: run, queued, items: doc.items, waiting, last_run: last }, null, 1));
382
+ else {
383
+ console.log(`${args[0]} ${doc.status}, runner ${runner.by}${run ? `, run ${run.n} going, ${usd(run.cost)}` : queued ? ', queued' : ''}`);
384
+ for (const i of doc.items) console.log(` ${i.kind.padEnd(6)} ${i.id} ${i.name} ${i.file ?? 'no file yet'}${i.from?.length ? ` from ${i.from.join(', ')}` : ''}${i.headline ? ` ${i.headline}` : ''}`);
385
+ for (const w of waiting) console.log(`${w.thread} ${w.kind} for ${w.for}${w.item ? `, on ${w.item}${w.ref ? ` at ${w.ref}` : ''}` : ''}, seq ${w.seq}: ${w.text.split('\n')[0].slice(0, 160)}`);
386
+ if (last) console.log(`last run ${last.run} ${usd(last.cost ?? 0)} ${last.error ?? last.summary ?? 'no report'}`);
387
+ }
388
+ } else if (cmd === 'log' && args.length === 1) {
389
+ const { at } = await instanceAt(args[0]);
390
+ for (let since = Number(flags.since ?? 0); ; await new Promise(ok => setTimeout(ok, 3000))) {
391
+ const fresh = (await get(at)).log.filter(e => e.seq > since);
392
+ for (const e of fresh) {
393
+ const { seq, at, by, op, text, ...rest } = e;
394
+ console.log(flags.json ? JSON.stringify(e) : `${seq} ${when(at)} ${by} ${op}${Object.keys(rest).length ? ` ${JSON.stringify(rest)}` : ''}${text ? ` ${String(text).split('\n')[0].slice(0, 200)}` : ''}`);
263
395
  }
396
+ since = fresh.at(-1)?.seq ?? since;
397
+ if (!flags.follow) break;
264
398
  }
399
+ } else if (cmd === 'cat' && args.length === 1) {
400
+ const path = args[0].replace(/^\/+|\/+$/g, ''), [f, ...more] = await get(`/api/files?path=${encodeURIComponent(path)}`);
401
+ if (!f || f.path !== path || more.length) throw new Error(f ? `${args[0]} is a folder: rf pull it` : `nothing you can see at ${args[0]}`);
402
+ process.stdout.write(f.text ?? Buffer.from(await (await api(f.url)).arrayBuffer()));
265
403
  } else if (cmd === 'pull' && args.length === 2) await pull(args[0], args[1]);
266
404
  else if (cmd === 'comment' && args.length === 2) {
267
- const { at } = await find(args[0]);
405
+ const { at } = await instanceAt(args[0]);
268
406
  await post(`${at}/comment`, { text: args[1], item: flags.item, ref: flags.ref, thread: flags.thread });
269
407
  const { log, runner } = await get(at), { seq, note } = log.at(-1);
270
408
  if (note) console.log(`a note for the runner, ${runner.by}, seq ${seq}: it starts no run until they act`);
@@ -279,9 +417,93 @@ else if (cmd === 'comment' && args.length === 2) {
279
417
  if (done.error) console.log(`The run failed: ${done.error}`);
280
418
  break;
281
419
  }
420
+ } else if (cmd === 'resolve' && [2, 3].includes(args.length)) {
421
+ console.log(await (await post(`${(await instanceAt(args[0])).at}/resolve`, { thread: args[1], text: args[2] })).text());
422
+ } else if (cmd === 'signoff' && ['approve', 'reject'].includes(args[2]) && args.length <= 4) {
423
+ await post(`${(await instanceAt(args[0])).at}/signoff`, { thread: args[1], approved: args[2] === 'approve', text: args[3] });
424
+ console.log(`${args[2] === 'approve' ? 'approved' : 'rejected'} ${args[1]}`);
425
+ } else if (['close', 'abandon', 'interrupt'].includes(cmd) && args.length === 1) {
426
+ const { series, at } = await instanceAt(args[0]);
427
+ if (cmd === 'close' && typeof flags['as-series'] === 'string') await post(`/api/series/${series.id}/promote`, { name: flags['as-series'] });
428
+ await post(`${at}/${cmd}`, {});
429
+ console.log(`${cmd === 'close' ? 'closed' : `${cmd}ed`} ${args[0]}`);
430
+ } else if (cmd === 'takeover' && args.length === 1) {
431
+ await post(`${(await instanceAt(args[0])).at}/takeover`, { logins: ticks() });
432
+ console.log(`you run ${args[0]} now${consent(ticks())}`);
433
+ } else if (cmd === 'creds' && args.length === 1) {
434
+ const { at } = await instanceAt(args[0]);
435
+ if (flags.set !== undefined || flags.clear) {
436
+ await post(`${at}/logins`, { logins: ticks() });
437
+ console.log(`saved${consent(ticks())}`);
438
+ } else {
439
+ const [{ runner }, mine] = await Promise.all([get(at), get('/logins')]);
440
+ const out = { runner: runner.by, ticked: runner.logins.map((id, k) => ({ id, name: runner.ticked[k] })), yours: mine.flatMap(l => l.offers.map(o => ({ ...o, ...(l.expired && { expired: true }) }))) };
441
+ if (flags.json) console.log(JSON.stringify(out, null, 1));
442
+ else console.log([`${out.runner} ticks:`, ...out.ticked.map(o => ` ${o.id} ${o.name}`), 'yours:', ...out.yours.map(o => ` ${o.id} ${o.name}${o.expired ? ' expired' : ''}`)].join('\n'));
443
+ }
444
+ } else if (cmd === 'rename' && args.length === 2) {
445
+ const [w, s, l] = args[0].replace(/\/+$/, '').split('/');
446
+ if (l !== undefined) await post(`${(await instanceAt(args[0])).at}/rename?as=${encodeURIComponent(args[1])}`, {});
447
+ else if (s !== undefined) await post(`/api/series/${(await find(args[0])).series.id}`, { name: args[1] }, 'PUT');
448
+ else await post(`/api/workspaces/${(await workspaceNamed(w)).id}`, { name: args[1] }, 'PUT');
449
+ console.log(`renamed ${args[0]} ${args[1]}`);
450
+ } else if (cmd === 'new' && args[0] === 'task' && [2, 3].includes(args.length)) {
451
+ const { instance } = await (await post('/api/series', { workspace: (await workspaceNamed(args[1])).id, single: true, logins: ticks() })).json();
452
+ if (args[2]) await post(`/api/instances/${instance}/rename?as=${encodeURIComponent(args[2])}`, {});
453
+ if (typeof flags.comment === 'string') await post(`/api/instances/${instance}/comment`, { text: flags.comment });
454
+ console.log(`made ${await pathOf(instance)}${consent(ticks())}`);
455
+ } else if (cmd === 'new' && args[0] === 'instance' && args.length === 3) {
456
+ const { id } = await (await post(`/api/series/${(await seriesAt(args[1])).id}`, { label: args[2], logins: ticks() })).json();
457
+ console.log(`made ${await pathOf(id)}${consent(ticks())}`);
458
+ } else if (cmd === 'new' && args[0] === 'series' && args.length === 3) {
459
+ await post(`/api/series/${(await find(args[1])).series.id}/promote`, { name: args[2] });
460
+ console.log(`made the series ${args[1].split('/')[0]}/${args[2]}`);
461
+ } else if (cmd === 'new' && args[0] === 'workspace' && args.length === 2) {
462
+ await post('/api/workspaces', { name: args[1] });
463
+ console.log(`made ${args[1]}`);
464
+ } else if (cmd === 'copy' && args.length === 2) {
465
+ const { id } = await (await post(`${(await instanceAt(args[0])).at}/duplicate?as=${encodeURIComponent(args[1])}`, { logins: ticks() })).json();
466
+ console.log(`made ${await pathOf(id)}${consent(ticks())}`);
467
+ } else if (cmd === 'share' && ['on', 'off'].includes(args[1]) && args.length === 2) {
468
+ await post(`/api/series/${(await seriesAt(args[0])).id}`, { share: args[1] === 'on', logins: ticks() }, 'PUT');
469
+ console.log(args[1] === 'on' ? `shared ${args[0]}${consent(ticks())}` : `stopped sharing ${args[0]}`);
470
+ } else if (cmd === 'archive' && args.length === 1) {
471
+ const [w, s] = args[0].replace(/\/+$/, '').split('/');
472
+ await post(s === undefined ? `/api/workspaces/${(await workspaceNamed(w)).id}` : `/api/series/${(await seriesAt(args[0])).id}`, { archived: !flags.undo }, 'PUT');
473
+ console.log(`${flags.undo ? 'brought back' : 'archived'} ${args[0]}`);
474
+ } else if (cmd === 'request' && ['start', 'drop'].includes(args[0]) && args.length === 2) {
475
+ if (args[0] === 'drop') await api(`/api/requests/${args[1]}`, { method: 'DELETE' });
476
+ console.log(args[0] === 'drop' ? `dropped request ${args[1]}` : `made ${await pathOf((await (await post(`/api/requests/${args[1]}`, { logins: ticks() })).json()).id)}${consent(ticks())}`);
477
+ } else if (cmd === 'logins' && !args.length) {
478
+ const all = await get('/logins');
479
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
480
+ else for (const l of all) {
481
+ console.log(`${l.id} ${l.name} ${l.expired ? `expired: sign in again at ${url}/#logins` : `${l.kind === 'key' ? 'saved' : 'signed in'} since ${when(l.since)}`}${l.kind === 'key' ? (l.enabled ? ', in use' : ', not in use') : ''}${l.keepalive > new Date().toISOString() ? `, kept alive until ${when(l.keepalive)}` : ''}${l.missing.length ? `, missing ${l.missing.join(', ')}` : ''}`);
482
+ // A website's login offers itself alone.
483
+ for (const o of l.offers.filter(o => o.id !== l.id)) console.log(` offers ${o.id} ${o.name}`);
484
+ }
485
+ } else if (cmd === 'logins' && ['offer', 'unoffer', 'allow'].includes(args[0]) && args.length === 3) {
486
+ const [what, login, x] = args, at = `/logins/${encodeURIComponent(login)}`;
487
+ if (what === 'offer') await post(`${at}/offers`, { add: x });
488
+ else if (what === 'unoffer') await api(`${at}/offers/${encodeURIComponent(x)}`, { method: 'DELETE' });
489
+ else await post(`/logins/web/${encodeURIComponent(login)}/hosts`, { host: x });
490
+ console.log(`${login} ${{ offer: 'offers', unoffer: 'no longer offers', allow: 'reaches' }[what]} ${x}`);
491
+ } else if (cmd === 'site' && args[0] === 'add' && args.length === 3) {
492
+ await post('/logins/sites', { name: args[1], url: args[2] });
493
+ console.log(`added ${args[1]}: sign in to it at ${url}/#logins`);
494
+ } else if (cmd === 'site' && args[0] === 'remove' && args.length === 2) {
495
+ await api(`/logins/sites/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
496
+ console.log(`removed ${args[1]}`);
497
+ } else if (cmd === 'logins' && args[0] === 'signout' && args.length === 2) {
498
+ await api(`/logins/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
499
+ console.log(`signed out of ${args[1]}`);
500
+ } else if (cmd === 'correct' && args.length === 2) {
501
+ const { series, at } = await instanceAt(args[0]), see = flags.see === undefined ? undefined : series.instances.find(i => i.label === flags.see);
502
+ if (flags.see !== undefined && !see) throw new Error(`no instance ${flags.see} in its series`);
503
+ console.log(await (await post(`${at}/correct`, { kind: flags.superseded ? 'superseded' : 'wrong', text: args[1], item: flags.item, ref: flags.ref, see: see?.id })).text());
282
504
  } else if (cmd === 'upload' && args.length === 2) {
283
505
  const q = new URLSearchParams({ name: basename(args[1]), pane: flags.output ? 'out' : 'in', ...(typeof flags.onto === 'string' && { onto: flags.onto }) });
284
- await api(`${(await find(args[0])).at}/upload?${q}`, { method: 'POST', body: readFileSync(args[1]) });
506
+ await api(`${(await instanceAt(args[0])).at}/upload?${q}`, { method: 'POST', body: readFileSync(args[1]) });
285
507
  console.log('uploaded');
286
508
  } else if (cmd === 'wake' && typeof flags.cancel === 'string' && !args.length) {
287
509
  await api(`/api/wakes/${flags.cancel}`, { method: 'DELETE' });
@@ -292,8 +514,7 @@ else if (cmd === 'comment' && args.length === 2) {
292
514
  const w = await (await post(`/api/wakes/${inst?.id ?? series.id}`, { at: new Date(at).toISOString(), label: flags.label, days: flags.days }, 'PUT')).json();
293
515
  console.log(`wake ${w.id} at ${w.at}${w.days ? `, then each ${w.days.join(', ')}` : ''}`);
294
516
  } else if (cmd === 'agents' && args.length <= 1) {
295
- const ws = args[0] === undefined ? undefined : (await get('/api')).find(w => w.name === args[0]);
296
- if (args[0] !== undefined && !ws) throw new Error(`no workspace ${args[0]}`);
517
+ const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
297
518
  if (typeof flags.set !== 'string') console.log(ws ? ws.agents : (await get('/agents')).text);
298
519
  else {
299
520
  const text = readFileSync(flags.set === '-' ? 0 : flags.set, 'utf8');
@@ -316,16 +537,25 @@ else if (cmd === 'comment' && args.length === 2) {
316
537
  }
317
538
  console.log(`pulled ${args[1]} version ${n} into ${dir}`);
318
539
  } else if (cmd === 'skill' && args[0] === 'versions' && args[1]) {
319
- for (const v of await get(`/skills/${encodeURIComponent(args[1])}/versions`)) console.log(`${v.version} ${v.at} ${v.by}`);
540
+ const versions = await get(`/skills/${encodeURIComponent(args[1])}/versions`);
541
+ if (flags.json) console.log(JSON.stringify(versions, null, 1));
542
+ else for (const v of versions) console.log(`${v.version} ${v.at} ${v.by}`);
320
543
  } else if (cmd === 'skill' && args[0] === 'rollback' && args.length === 3) {
321
544
  console.log(await (await post(`/skills/${encodeURIComponent(args[1])}/versions`, { from: Number(args[2]) })).text());
322
545
  } else if (cmd === 'skills') {
323
- for (const s of await get('/skills')) console.log(`${s.id} v${s.pushed.version} by ${s.pushed.by} ${s.pushed.at} ${s.description}`);
546
+ const skills = await get('/skills');
547
+ if (flags.json) console.log(JSON.stringify(skills, null, 1));
548
+ else for (const s of skills) console.log(`${s.id} v${s.pushed.version} by ${s.pushed.by} ${s.pushed.at} ${s.description}`);
324
549
  } else if (cmd === 'connections') {
325
- for (const { name, type, login, updated_by, updated_at, ...settings } of await get('/connections')) console.log(`${name} ${type} ${JSON.stringify(settings)}`);
550
+ const all = await get('/connections');
551
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
552
+ else for (const { name, type, login, updated_by, updated_at, ...settings } of all) console.log(`${name} ${type} ${JSON.stringify(settings)}`);
326
553
  } else if (cmd === 'connection' && args[0] === 'set' && args.length === 3) {
327
554
  await post(`/connections/${encodeURIComponent(args[1])}`, { type: args[2], ...flags }, 'PUT');
328
555
  console.log('saved');
556
+ } else if (cmd === 'connection' && ['off', 'on'].includes(args[0]) && args[1]) {
557
+ await post(`/connections/${encodeURIComponent(args[1])}`, { off: args[0] === 'off' }, 'PATCH');
558
+ console.log(args[0]);
329
559
  } else if (cmd === 'connection' && args[0] === 'remove' && args[1]) {
330
560
  await api(`/connections/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
331
561
  console.log('removed');
@@ -337,9 +567,10 @@ else if (cmd === 'comment' && args.length === 2) {
337
567
  [`Running`, s.running.map(r => `${r.path} run ${r.run} for ${took((Date.now() - Date.parse(r.at)) / 1000)} ${usd(r.cost)}${Date.now() - Date.parse(r.at) > long * 60e3 ? ` LONG, past ${long}m` : ''}`)],
338
568
  [`Queued`, s.queued.map(q => `${q.path} since ${when(q.since)}: ${q.why}`)],
339
569
  [`Waiting`, [
340
- ...s.asks.sort((a, b) => a.who.localeCompare(b.who) || a.since.localeCompare(b.since)).map(a => `${a.who} ${a.signoff ? 'a sign-off' : a.note ? 'a note' : 'an ask'} in ${a.path} since ${when(a.since)}: ${a.text.split('\n')[0].slice(0, 80)}`),
570
+ ...[...s.asks, ...s.requests.map(r => ({ ...r, who: r.who ?? 'anyone', since: r.at, text: `${r.from} asks to start ${r.label}`, request: true })),
571
+ ...s.proposals.map(p => ({ who: `${p.to}'s owners`, path: p.to, since: p.at, text: `${p.by} proposes to ${p.kind === 'merge' ? `merge ${p.from} into it` : `move ${p.from}/${p.series} to it`}`, proposal: true }))]
572
+ .sort((a, b) => a.who.localeCompare(b.who) || a.since.localeCompare(b.since)).map(a => `${a.who} ${a.proposal ? 'a proposal' : a.request ? 'a request' : a.signoff ? 'a sign-off' : a.note ? 'a note' : 'an ask'} in ${a.path} since ${when(a.since)}: ${a.text.split('\n')[0].slice(0, 80)}`),
341
573
  ...s.expired.map(e => `${e.who} their ${e.login} login expired${e.holding.length ? `, holding ${e.holding.join(', ')}` : ''}`),
342
- ...s.requests.map(r => `${r.path} ${r.from} asks to start ${r.label}, since ${when(r.at)}`),
343
574
  ]],
344
575
  [`Last run failed`, s.failed.map(f => `${f.path} run ${f.run} at ${when(f.at)}: ${f.error}`)],
345
576
  [`Indexes crawling or failing`, ix.filter(x => x.people.some(p => p.phase === 'crawl' || p.error)).map(x => `${x.name} ${x.people.filter(p => p.phase === 'crawl' || p.error)
@@ -355,27 +586,51 @@ else if (cmd === 'comment' && args.length === 2) {
355
586
  } else if (cmd === 'runs' && args.length <= 1) {
356
587
  const rows = (await runsIn(args[0])).filter(r => (!flags.failed || r.outcome === 'failed') && (!flags.running || r.outcome === 'running') && (!flags.long || r.seconds >= Number(flags.long) * 60));
357
588
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
358
- else for (const r of rows) console.log(`${when(r.at)} ${r.path} run ${r.run} ${r.outcome} ${took(r.seconds)} ${usd(r.cost)} ${r.started ? `${r.started.op} by ${r.started.by}` : '-'} ${r.error ?? r.summary ?? ''}`);
589
+ else for (const r of rows) console.log(`${when(r.at)} ${r.path} run ${r.run} ${r.outcome}${r.failure ? ` (${r.failure})` : ''} ${took(r.seconds)} ${usd(r.cost)} ${r.started ? `${r.started.op} by ${r.started.by}` : '-'} ${r.error ?? r.summary ?? ''}`);
359
590
  } else if (cmd === 'costs' && args.length <= 1) {
360
- const by = String(flags.by ?? 'series'), key = { workspace: r => r.path.split('/')[0], series: r => r.path.split('/').slice(0, 2).join('/'), person: r => r.runner, day: r => when(r.at).slice(0, 10) }[by];
361
- if (!key) throw new Error(USAGE);
362
- const sums = new Map (), rows = await runsIn(args[0]);
363
- for (const r of rows) sums.set(key(r), { runs: (sums.get(key(r))?.runs ?? 0) + 1, cost: (sums.get(key(r))?.cost ?? 0) + r.cost });
364
- const out = [...sums].map(([k, v]) => ({ [by]: k, runs: v.runs, cost: +v.cost.toFixed(4), per_run: +(v.cost / v.runs).toFixed(4) }))
591
+ const by = String(flags.by ?? 'series'), key = {
592
+ workspace: r => r.path.split('/')[0], series: r => r.path.split('/').slice(0, 2).join('/'), person: r => r.runner, day: r => when(r.at).slice(0, 10),
593
+ outcome: r => r.failure ? `failed, ${r.failure}` : r.outcome,
594
+ }[by];
595
+ if (!key) throw new Error('--by: workspace, series, person, day or outcome');
596
+ // A run a restart cut is carried on by the next, so it adds its cost, not a run.
597
+ const sums = new Map (), rows = await runsIn(args[0]), counted = (r ) => r.outcome === 'cut' ? 0 : 1;
598
+ for (const r of rows) sums.set(key(r), { runs: (sums.get(key(r))?.runs ?? 0) + counted(r), cost: (sums.get(key(r))?.cost ?? 0) + r.cost });
599
+ const out = [...sums].map(([k, v]) => ({ [by]: k, runs: v.runs, cost: +v.cost.toFixed(4), per_run: v.runs ? +(v.cost / v.runs).toFixed(4) : null }))
365
600
  .sort((a, b) => by === 'day' ? a.day.localeCompare(b.day) : b.cost - a.cost);
366
601
  if (flags.json) console.log(JSON.stringify(out, null, 1));
367
602
  else {
368
- for (const o of out) console.log(`${usd(o.cost).padStart(10)} ${String(o.runs).padStart(5)} runs ${usd(o.per_run).padStart(8)} a run ${o[by]}`);
369
- console.log(`${usd(rows.reduce((t, r) => t + r.cost, 0)).padStart(10)} ${String(rows.length).padStart(5)} runs in all`);
603
+ for (const o of out) console.log(`${usd(o.cost).padStart(10)} ${String(o.runs).padStart(5)} runs ${(o.per_run === null ? '-' : usd(o.per_run)).padStart(8)} a run ${o[by]}`);
604
+ console.log(`${usd(rows.reduce((t, r) => t + r.cost, 0)).padStart(10)} ${String(rows.reduce((n, r) => n + counted(r), 0)).padStart(5)} runs in all`);
605
+ }
606
+ } else if (cmd === 'wakes' && args.length <= 1) {
607
+ const at = (args[0] ?? '').replace(/\/+$/, ''), rows = (await get('/api')).flatMap(w => w.series.filter(s => !s.archived).flatMap(s => [
608
+ ...(s.single ? [] : [{ path: `${w.name}/${s.name}`, fired: s.fired, wakes: s.wakes, requests: s.requests }]),
609
+ ...s.instances.filter(i => i.wakes.length).map(i => ({ path: `${w.name}/${s.name}/${i.label}`, fired: i.fired, wakes: i.wakes, requests: [] })),
610
+ ])).filter(r => !at || r.path === at || r.path.startsWith(at + '/'));
611
+ if (flags.json) console.log(JSON.stringify(rows, null, 1));
612
+ else for (const r of rows) {
613
+ console.log(`${r.path} last woken ${r.fired ? when(r.fired) : 'never'}${r.wakes.length || r.requests.length ? '' : ', none pending'}`);
614
+ for (const k of r.wakes) console.log(` wake ${k.id} ${when(k.at)}${k.label ? ` starts ${k.label}` : ''}${k.days ? `, then each ${k.days.join(', ')}` : ''}, set by ${k.from}`);
615
+ for (const q of r.requests) console.log(` request ${q.id} to start ${q.label}, from ${q.from} since ${when(q.at)}, waits on ${q.who ?? 'anyone'}`);
616
+ }
617
+ } else if (cmd === 'activity' && args.length <= 1) {
618
+ const at = (args[0] ?? '').replace(/\/+$/, ''), blocks = (await get(`/api/activity?since=${encodeURIComponent(String(flags.since ?? ''))}`))
619
+ .filter(b => !at || b.path === at || b.path.startsWith(at + '/'));
620
+ if (flags.json) console.log(JSON.stringify(blocks, null, 1));
621
+ else for (const b of blocks) {
622
+ console.log(b.path);
623
+ for (const e of b.entries) console.log(` ${when(e.at)} ${e.op === 'done' ? `run ${e.run} ${e.error ?? e.summary ?? 'no report'}`
624
+ : `${e.by} ${e.op === 'comment' ? `says: ${e.text.split('\n')[0].slice(0, 200)}` : e.op === 'upload' ? `uploads ${e.file}` : `${e.op === 'close' ? 'closes' : 'abandons'} it`}`}`);
370
625
  }
371
626
  } else if (cmd === 'people' && args.length <= 1) {
372
627
  // People as lines to edit and set: ROLE EMAIL for everyone, owner|member EMAIL-OR-GROUP for a workspace, each with a comment.
373
- const ws = args[0] === undefined ? undefined : (await get('/api')).find(w => w.name === args[0]);
374
- if (args[0] !== undefined && !ws) throw new Error(`no workspace ${args[0]}`);
375
- const last = (iso ) => iso ? `last in ${when(iso)}` : 'never in';
376
- const now = ws ? (await get(`/api/workspaces/${ws.id}/people`)).map(p => ({ kind: p.as, who: p.who, note: [p.who.includes('@') ? last(p.last_login) : 'a group', p.runs.length && `runs ${p.runs.join(', ')}`] }))
377
- : (await get('/users')).map(u => ({ kind: u.role, who: u.email, note: [u.disabled && 'disabled', last(u.last_login), `in ${u.workspaces.join(', ') || 'none'}`, u.outside.length && `runs outside them: ${u.outside.join(', ')}`] }));
378
- if (typeof flags.set !== 'string') {
628
+ const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
629
+ const last = (iso ) => iso ? `last in ${when(iso)}` : 'never in', listed = await get(ws ? `/api/workspaces/${ws.id}/people` : '/users');
630
+ const now = ws ? listed.map(p => ({ kind: p.as, who: p.who, note: [p.who.includes('@') ? last(p.last_login) : 'a group', p.runs.length && `runs ${p.runs.join(', ')}`] }))
631
+ : listed.map(u => ({ kind: u.role, who: u.email, note: [u.disabled && 'disabled', last(u.last_login), `in ${u.workspaces.join(', ') || 'none'}`, u.outside.length && `runs outside them: ${u.outside.join(', ')}`] }));
632
+ if (flags.json && typeof flags.set !== 'string') console.log(JSON.stringify(listed, null, 1));
633
+ else if (typeof flags.set !== 'string') {
379
634
  const w = Math.max(0, ...now.map(p => p.who.length));
380
635
  for (const p of now) console.log(`${p.kind.padEnd(6)} ${p.who.padEnd(w)} # ${p.note.filter(Boolean).join('; ')}`);
381
636
  if (!now.length) console.log('# no one is in it: only admins see it');
@@ -401,13 +656,14 @@ else if (cmd === 'comment' && args.length === 2) {
401
656
  await post('/brand', { clear: flags.clear, text: flags.text, logo }, 'PUT');
402
657
  console.log('saved');
403
658
  } else {
404
- const { text, logo } = (await get('/me')).brand;
405
- console.log(text || logo ? `${text ?? 'no text'}, ${logo ? 'with a logo' : 'no logo'}` : 'no brand: the plain look');
659
+ const { brand } = await get('/me'), { text, logo } = brand;
660
+ console.log(flags.json ? JSON.stringify(brand) : text || logo ? `${text ?? 'no text'}, ${logo ? 'with a logo' : 'no logo'}` : 'no brand: the plain look');
406
661
  }
407
662
  } else if (cmd === 'can' && args.length <= 2) {
408
663
  const [cap, list] = args, people = flags.clear ? [] : list?.split(',').map(p => p.trim()).filter(Boolean);
409
664
  const all = await (await (people ? post('/capabilities', { cap, people }, 'PUT') : api('/capabilities'))).json();
410
- for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || 'admins only'}`);
665
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
666
+ else for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || 'admins only'}`);
411
667
  } else if (cmd === 'user' && args.length >= 2) {
412
668
  const [what, email, role] = args, at = `/users/${encodeURIComponent(email)}`;
413
669
  if (what === 'add') await post('/users', { roles: { [email]: role ?? 'user' } }, 'PUT');
@@ -415,9 +671,12 @@ else if (cmd === 'comment' && args.length === 2) {
415
671
  else if (what === 'disable' || what === 'enable') await post(at, { disabled: what === 'disable' }, 'PUT');
416
672
  else if (what === 'signout') await post(at, { signout: true }, 'PUT');
417
673
  else if (what === 'remove') await api(at, { method: 'DELETE' });
418
- else throw new Error(USAGE);
674
+ else {
675
+ console.error(usage(cmd));
676
+ process.exit(2);
677
+ }
419
678
  console.log('done');
420
679
  } else {
421
- console.error(USAGE);
680
+ console.error(usage(cmd));
422
681
  process.exitCode = 2;
423
682
  }