@rfany/rf 0.10.0 → 0.12.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 +354 -100
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.10.0",
3
+ "version": "0.12.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,15 +6,80 @@ 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
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 and notes, requests to start an instance or to use a
18
+ website in a workspace you own, proposals, expired logins, and hosts a run's browser on a
19
+ website you added was refused
20
+ rf show PATH [--json] an instance: its items, the threads that wait on someone, by id, and its last run
21
+ rf log PATH [--since SEQ] [--follow] [--json] its log, a line an entry, after SEQ; --follow prints more as they come;
22
+ --json prints the entries as they are, a line each
23
+ rf cat PATH/FILE one file, to stdout
11
24
  rf pull PATH DIR [--delete] [-n|--dry-run] [--exclude PATTERN]... [--max-size SIZE]
12
25
  PATH's files into DIR as rsync copies them, whole, if their size or time differ: PATH/ fills DIR,
13
26
  PATH makes DIR/<its name>, / is all you see; --delete removes what the server no longer has;
14
27
  --max-size skips files bigger than SIZE, such as 50M
15
- rf help how rollforward works and how to use rf, for an agent
16
- 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
17
- rf upload PATH FILE [--onto ITEM] [--output]
28
+ rf help [COMMAND] how rollforward works and how to use rf, for an agent, or COMMAND's usage
29
+ rf --version rf's own version, to tell whether it's older than what the guide names
30
+ rf comment PATH TEXT [--item ID] [--ref REF] [--thread cN] [--wake|--wait] a new thread, or a reply under comment cN, as to
31
+ an agent's ask; --wake starts a run on it, as --wait does, which prints what the agent says back
32
+ rf upload PATH FILE [--onto ITEM] [--output] [--wake]
33
+ rf signoff PATH cN [TEXT] [--wake] signs off the agent's ask cN, which pins files, as they are, which commits the folder
34
+ in your name; to say no, reply
35
+ rf react PATH [cN] up|down|none your thumbs up or down on comment cN, or on the instance, or none; quiet, open or closed
36
+ rf close PATH [--as-series NAME] [--wake] the runner makes it the record and an example,
37
+ approving nothing; a task closes as a one-off, or as the first instance of the series NAME it
38
+ becomes; --wake starts runs of the series' later open instances, which may have used its draft
39
+ rf abandon PATH the runner leaves it as it is, neither an example nor a starting point
40
+ rf interrupt PATH stops its run
41
+ rf takeover PATH [--creds OFFER,...] you run it from now on, with those offers of your logins ticked
42
+ rf creds PATH [--set OFFER,...|--clear] what its runs may use: its runner's ticks, and the offers of your logins; --set
43
+ ticks anew, as its runner
44
+ rf rename PATH NAME an instance, a series or a workspace, by its path
45
+ rf new task WORKSPACE [LABEL] [--creds OFFER,...] [--comment TEXT [--wake]] a one-off task, Untitled until LABEL or its
46
+ first comment names it; --wake starts its run on the comment
47
+ rf new instance SERIES LABEL [--creds OFFER,...] [--wake] the series' next instance, which --wake runs at once
48
+ rf new series PATH NAME the task at PATH becomes the series NAME, itself its first instance
49
+ rf new workspace NAME yours to own, for admins and those they grant create
50
+ rf copy PATH LABEL [--creds OFFER,...] a closed or abandoned instance, copied into a new open one without its agent session
51
+ rf share PATH on|off [--creds OFFER,...] the series' people, and their agents, wake it as you, with those offers ticked;
52
+ off stops it, for its sharer or its workspace's owners
53
+ rf archive PATH [--undo] a workspace or a series leaves the sidebar as it is, until --undo brings it back
54
+ rf request start|drop ID [--creds OFFER,...] [--wake] a request to start an instance, by the ID rf waiting and rf wakes
55
+ print; --wake runs the instance it starts
56
+ rf logins [--json] your logins, each with its state, keepalive and offers; you sign in to them on the page
57
+ rf logins offer|unoffer LOGIN SOURCE|OFFER what a login offers runs: Microsoft 365's (m365) mailboxes, sites, folders and
58
+ files, by address or link, a Databricks login's SQL warehouses, by link; unoffer takes the
59
+ OFFER rf logins lists
60
+ rf logins allow SITE HOST a host the pages of SITE, a website you added or, for admins, any, need; once a grant to it
61
+ is approved, only within the domains it reaches, beyond which admins allow them
62
+ rf logins signout LOGIN
63
+ rf site add NAME URL a website whose sign-in starts at URL, which you sign in to on the page; at an address a
64
+ website has already, it's that one, whose name rf prints
65
+ rf site set NAME [--title TITLE] [--header NAME] [--keepalive PAGE] [--every 10m] [--writeback false]
66
+ a website you added, or for admins any: its name as people see it, a header its sign-in
67
+ needs that its pages never send, such as x-bot-token, whose value each person gives, the
68
+ page a login kept alive loads, by address or path, else its address, and how often, 10m
69
+ unless given, and whether a run's browser writes its state back; admins also set
70
+ --off true|false, for no one to use it, and --internal true|false, for its browsers to
71
+ reach internal hosts
72
+ rf site remove NAME a website you added, while no one else has a grant to it pending or approved, or for admins
73
+ any: its grants go with it, and everyone's login to it
74
+ rf site ask NAME WORKSPACE REASON to use your login to NAME in WORKSPACE's runs, for REASON, which one of its owners approves
75
+ or denies, seeing the server's check of the website, or an admin, where it rates it high
76
+ risk; a login no approved grant uses is signed out a week after you signed in, and once
77
+ you have no grant to it pending or approved
78
+ rf grants [WORKSPACE] [--json] the grants to use websites, yours and those of the workspaces you own, with their states
79
+ rf grant approve|deny ID [TEXT] a request to use a website in a workspace you own, with TEXT for its asker
80
+ rf grant revoke ID a grant pending or approved, yours or in a workspace you own; its runs' browsers close
81
+ rf correct PATH TEXT [--item ID] [--ref REF] [--superseded] [--see LABEL] a closed instance, or its item ID at REF, is
82
+ wrong, or superseded, as LABEL, another instance of its series, shows; it can't be withdrawn
18
83
  rf wake PATH AT [--label LABEL] [--days DAYS] | rf wake --cancel ID
19
84
  AT now, +<n>m|h|d or a date; PATH an open instance, or a series with LABEL; DAYS, such as
20
85
  mon-fri, repeats it weekly at AT's time; rf ls shows each wake's ID
@@ -28,12 +93,13 @@ rf status [--long MIN] [--json] what goes on and what's stuck: runs going, fla
28
93
  rf indexes [--json] each index of a source you index, all for admins: its kind, items and size, and per person
29
94
  its phase, crawl or follow, pages read, when last caught up, and its error and next try
30
95
  rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] [--json]
31
- a line per run: start, path, run, outcome, time, cost, what started it, summary or error;
96
+ a line per run: start, path, run, outcome, time, cost, what started it, and any error;
32
97
  the outcome is done, interrupted by a person, cut by a restart, running, or failed, for
33
98
  credits, policy, time limit or other
34
99
  rf costs [PATH] [--since DATE] [--by workspace|series|person|day|outcome] [--json] totals, runs and cost per run; person
35
100
  is the runner; runs leave out those a restart cut, as the next run carries each on
36
- rf activity [PATH] [--since DATE] [--json] per instance, what people said, uploaded and closed, and each run's report
101
+ rf activity [PATH] [--since DATE] [--json] per instance, what people and the agent said, what people uploaded and closed, and
102
+ each run that failed
37
103
  rf wakes [PATH] [--json] each series' pending wakes and requests to start an instance, and when a wake of it last
38
104
  fired, and each instance's pending wakes
39
105
  rf people WORKSPACE [--set FILE|-] [-n] [--force] its owners and admins: its people as lines of owner|member EMAIL-OR-GROUP,
@@ -48,75 +114,80 @@ Admins:
48
114
  rf people [--set FILE|-] [-n] [--force] everyone as lines of ROLE EMAIL, each with a comment; --set sets the roles of the people
49
115
  listed and adds new ones, removing no one
50
116
  rf user add EMAIL [admin] | role EMAIL admin|user [--force] | disable EMAIL | enable EMAIL | signout EMAIL | remove EMAIL
51
- rf connection set NAME TYPE [--SETTING VALUE]... an outside system runs reach as their runner, by a login each person makes:
52
- graph, Microsoft 365, with no settings; databricks, --host HOST --warehouse ID, a workspace
53
- and its SQL warehouse; website, --url URL [--hosts HOST,...] [--title TITLE] [--writeback
54
- false] [--header NAME] [--keepalive PAGE --every 10m [--hours 08:00-19:00]] [--people
55
- EMAIL|GROUP,...], where people sign in, the other hosts its pages need, such as
56
- *.example.com, whether a run's browser writes its state back, a header its sign-in needs
57
- that its pages never send, such as x-bot-token, whose value each person gives, a page, by
58
- its address or path, such as https://patriarch.patrina.net/PatriArchMVC/, to load in each
59
- live login's browser every so often, in office hours on weekdays if given, so idle sessions
60
- stay alive, and who alone may use it, by email or Entra group id
117
+ rf connection set NAME TYPE an outside system runs reach as their runner, by a login each person makes: graph,
118
+ Microsoft 365, or databricks, Azure Databricks, as each person adds what their login
119
+ offers; websites are rf site's
61
120
  rf connection remove NAME
62
121
  rf brand [--text TEXT] [--logo FILE] [--clear] the deployment's text and logo, a .png, .jpg, .gif, .webp or .svg, which top
63
122
  the sidebar and are the page's title and icon; --clear goes back to the plain look, and with
64
123
  no option it prints them
65
- rf can [CAP [EMAIL|GROUP,...] [--clear]] what users may do beyond the rest, as admins may: publish, push skills, and
66
- create, make workspaces; a list grants CAP to those emails and Entra group ids in place of
67
- whom it had, --clear to no one, and with neither it prints whom each is granted to`;
124
+ rf can [CAP [EMAIL|GROUP,...] [--clear]] what users may do beyond the rest, as admins may: publish, push skills;
125
+ create, make workspaces; and keepalive, keep their website logins alive for up to a
126
+ week as they sign in; a list grants CAP to those
127
+ emails and Entra group ids in place of whom it had, --clear to no one, and with neither it
128
+ prints whom each is granted to`;
68
129
 
69
130
  const GUIDE = `rollforward runs a team's recurring work, such as a weekly borrowing base or a month-end reconciliation, with an agent
70
- that does each period's work and people who check it. rf does what its page does, as you.
131
+ 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
132
+ COMMAND gives one's usage, every read takes --json, and a failure is one line on stderr, with exit code 1.
71
133
 
72
134
  What there is
73
135
  - A workspace holds series, and its people. A series is one recurring job; an instance is one period of it, labelled such as
74
136
  2026-08-23. A task is a one-off: a series of one instance, named by its label, until someone makes it a series. PATH is workspace/series/label, as rf ls prints it; for rf pull it may go deeper, into an instance's files.
75
- - An instance's screen is its items: inputs, steps and outputs, each pointing at a file, with what it's made from. People upload
76
- files and comment. The runner is the person whose logins the runs use, and who closes the instance once they stand by it. Their
77
- comments and uploads start a run of the agent, which reads them and carries on, as do everyone's where the runner shares the
78
- series, and a reply from whom an ask names; anyone else's is a note, which the agent takes up once the runner does.
79
- - A comment starts a thread, on the instance or on an item, at a cell such as Base!C25, and others reply in it. An ask is the
80
- agent's comment that waits on someone, the one it names or else the runner, until they reply or resolve it. rf ls says how many
81
- asks wait in each instance. A sign-off, an ask with signoff true, waits on the runner, who approves or rejects it on the page:
82
- either commits the instance's folder to its history, .git in it, as closing does.
137
+ - An instance's screen is its items: inputs, outputs and steps, each pointing at a file, with what it's made from. People upload
138
+ files, and review the work in threads with the agent. The runner is the person whose logins the runs use, and who closes the
139
+ instance, making it the period's record and an example for the next, which approves nothing. Their comments and uploads start a run of the agent, which reads them and carries on, as do everyone's where the
140
+ runner shares the series, and a reply from whom an ask names; anyone else's is a note, which the agent takes up once the runner
141
+ does.
142
+ - rf is quiet: a comment, upload, sign-off, close, new instance or request it starts begins no run unless --wake, and the agent
143
+ reads it at its next run; rf wake PATH now starts one. A quiet upload or comment is committed to the instance's history at once.
144
+ - A comment starts a thread, on the instance or on an item, at a cell such as Base!C25 or a line of a markdown file by its
145
+ opening words, and replies go under any comment in it, cN by its seq, a thread's id its first comment's. An ask is the agent's
146
+ comment that waits on someone, the one it names or else the runner, until someone replies under it. rf ls says how many asks
147
+ wait in each instance. Reactions, thumbs up or down, are quiet signals kept for later. An ask
148
+ may pin files, kept with their sha256 as the agent asks; anyone who sees the instance may sign it off, which commits the
149
+ instance's folder to its history, .git in it, as closing does. Whose sign-off counts, and for what, is the series' call.
83
150
 
84
151
  What rf pull copies, the folders as the agent sees them
85
152
  AGENTS.md the company's conventions; <workspace>/AGENTS.md the workspace's
86
153
  <workspace>/<series>/<label>/
87
- screen.json the screen: {rev, status, items: [{id, name, kind, file, from, headline, source}]}
154
+ screen.json the screen: {rev, status, items: [{id, name, kind, file, from, headline, source, destination, as_of}]}
88
155
  log.jsonl every event, by seq: by is a person's email, "server" or "agent"; op is upload, comment (thread, item,
89
- ref, text, ask, to, signoff), resolve, signoff (the runner's answer, with its commit), commit, point and
90
- item (the screen changing), run, report (the agent's account of a run), done (its cost, summary or
91
- error), close, and the rest
156
+ ref, parent, text, files, ask, to), signoff (someone's, on the ask it names, with its commit), react,
157
+ commit, point and item (the screen changing), run, done (its cost, or error), close, and the rest
92
158
  upload/ what people uploaded, their comments' attachments in upload/attachments/
93
159
  working/ what the agent made, its scripts, and process.md, how it does this series
94
- session/ each run's session: every message and tool call of it
160
+ session/ each session's transcript, which may carry several runs: every message and tool call
95
161
  browser/ each run's browser requests, and its screenshots
96
- skills/ the skills the latest run loaded
97
162
  names.tsv each instance in the latest run's reach, id<TAB>/work/<workspace>/<series>/<label>: names can
98
163
  change, so where a path in a file doesn't match, look its id up in the names.tsv of the commit
99
164
  that last changed the file (git log -1 -- FILE, then git show H:names.tsv), and its name now in
100
165
  rf ls
101
- The copy is read-only, and only rf changes what's on the server: comment, upload and wake.
166
+ The copy is read-only: only rf's commands change what's on the server.
102
167
 
103
168
  Usual work
104
- - What waits on me: rf ls, then the asks in that instance's log.jsonl, ask true, whose thread has nothing after them.
105
- - Answer an ask: rf comment PATH TEXT --thread T --wait, which prints what the agent says back.
106
- - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output].
107
- - Start an instance: rf wake SERIES now --label LABEL, which starts it as whoever shares the series, else asks on the page for
108
- someone to start it; take one you run up later: rf wake PATH +2h.
109
- - 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
110
- every step.
169
+ - What waits on me: rf waiting, then rf show PATH, which names each comment that waits by its id.
170
+ - Answer an ask: rf comment PATH TEXT --thread cN --wait, which prints what the agent says back; sign off one that pins files:
171
+ rf signoff PATH cN [TEXT] --wake, for the agent to carry on. Close an
172
+ instance once it's the record: rf close PATH.
173
+ - Take an instance over: rf creds PATH lists the offers of your logins, and rf takeover PATH --creds OFFER,... ticks them.
174
+ - Your logins: rf logins lists them, with what each offers, and an expired one's link to sign in again on the page.
175
+ - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output], with --wake on the last for a run on them
176
+ all.
177
+ - Start an instance: rf new instance SERIES LABEL --wake, as you, or rf wake SERIES now --label LABEL, which starts it as
178
+ whoever shares the series, else asks on the page for someone to start it; take one you run up later: rf wake PATH +2h. A
179
+ one-off: rf new task WORKSPACE --comment TEXT --wake, which becomes a series with rf new series PATH NAME.
180
+ - 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
181
+ for a file; rf pull PATH/ DIR copies the folder, with session/ for every step.
111
182
 
112
- Watching over it, for admins and power users; each sees what the caller sees, and takes --json
183
+ Watching over it, for admins and power users; each sees what the caller sees
113
184
  - What's stuck: rf status lists runs going, flagging those past --long MIN (30); queued runs, since when and why: their series is
114
185
  running, the RF_MAX_RUNS cap, or memory; what waits on whom since when: asks, notes for runners, expired logins and the instances
115
186
  they hold, and requests to start; open instances whose last run failed; and indexes crawling or failing.
116
187
  - Indexes: rf indexes shows each index of a big library or mailbox you index, every one for admins: its items and size, and per
117
188
  person whether it is crawling or following changes, pages read, when last caught up, and an error, if any, with its next try.
118
189
  - History: rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] prints a line per run: its start, path, run number,
119
- outcome, time taken, cost, what started it and by whom, and its summary or error. rf costs [PATH] [--since DATE] [--by
190
+ outcome, time taken, cost, what started it and by whom, and any error. rf costs [PATH] [--since DATE] [--by
120
191
  workspace|series|person|day] totals them, by the runner for person.
121
192
  - People: rf people (admins) prints everyone as ROLE EMAIL lines, and rf people WORKSPACE (its owners and admins) its owners and
122
193
  members as owner|member lines; a comment after each says when they last signed in and which open instances they run, and for
@@ -125,27 +196,30 @@ Watching over it, for admins and power users; each sees what the caller sees, an
125
196
  does); for a workspace it replaces its people. A change that would hide an open instance from the person who runs it is refused,
126
197
  naming them, unless --force: have someone who stays take those over first.`;
127
198
 
199
+ // A command's usage, as USAGE gives it; with none known, every command's.
200
+ const usage = (c ) => (c && USAGE.split(/\n(?=\S)/).map(e => e.trimEnd()).filter(e => e.split(/\s/)[1] === c).join('\n')) || USAGE;
201
+
128
202
  const config = join(homedir(), '.config', 'rollforward.json');
129
203
  const [cmd, ...argv] = process.argv.slice(2);
130
204
  const flags = {}, excludes = [], args = [];
131
205
  for (let i = 0; i < argv.length; i++) {
132
206
  const flag = argv[i] === '-n' ? 'dry-run' : argv[i].match(/^--(.+)$/)?.[1];
133
207
  if (!flag) args.push(argv[i]);
134
- else if (['wait', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear'].includes(flag)) flags[flag] = true;
135
- else if (argv[i + 1] === undefined) {
136
- console.error(`--${flag} takes a value\n\n${USAGE}`);
137
- process.exit(2);
138
- } else if (flag === 'exclude') excludes.push(argv[++i]);
208
+ else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount'].includes(flag)) flags[flag] = true;
209
+ else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
210
+ else if (flag === 'exclude') excludes.push(argv[++i]);
139
211
  else flags[flag] = argv[++i];
140
212
  }
141
- if (cmd === 'help') {
142
- console.log(GUIDE);
213
+ if (cmd === '--version') {
214
+ // Its package's: cli/ in the repo, beside rf.mjs once published.
215
+ console.log(JSON.parse(readFileSync(new URL(import.meta.url.endsWith('.ts') ? '../cli/package.json' : 'package.json', import.meta.url), 'utf8')).version);
143
216
  process.exit();
144
217
  }
145
- if (cmd !== 'login' && !existsSync(config)) {
146
- console.error(`Sign in first: rf login URL\n\n${USAGE}`);
147
- process.exit(2);
218
+ if (!cmd || cmd === 'help') {
219
+ console.log(!cmd ? USAGE : args[0] ? usage(args[0]) : GUIDE);
220
+ process.exit();
148
221
  }
222
+ if (cmd !== 'login' && !existsSync(config)) throw new Error('sign in first: rf login URL');
149
223
  let { url, token } = cmd === 'login' ? { url: args[0]?.replace(/\/$/, ''), token: args[1] } : JSON.parse(readFileSync(config, 'utf8'));
150
224
 
151
225
  async function api(path , init = {}) {
@@ -162,6 +236,26 @@ async function find(path ) {
162
236
  if (!series || (l !== undefined && !inst)) throw new Error(`nothing you can see at ${path}`);
163
237
  return { series, inst, at: inst ? `/api/instances/${inst.id}` : '' };
164
238
  }
239
+ async function instanceAt(path ) {
240
+ const { series, inst, at } = await find(path);
241
+ if (!inst) throw new Error(`${path} is a series: name one of its instances, as rf ls lists them`);
242
+ return { series, inst, at };
243
+ }
244
+ async function seriesAt(path ) {
245
+ const { series, inst } = await find(path);
246
+ if (inst) throw new Error(`${path} is an instance: name its series`);
247
+ return series;
248
+ }
249
+ async function workspaceNamed(name ) {
250
+ const ws = (await get('/api')).find(w => w.name === name);
251
+ if (!ws) throw new Error(`no workspace ${name}`);
252
+ return ws;
253
+ }
254
+ // An instance's path as rf ls prints it, by its id.
255
+ 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];
256
+ // The offers of your logins that --creds or --set name, ticked for an instance, and what ticking them agrees to.
257
+ const ticks = () => flags.clear ? [] : String(flags.creds ?? flags.set ?? '').split(',').map(o => o.trim()).filter(Boolean);
258
+ const consent = (offers ) => offers.length ? `, ticking ${offers.join(', ')}: you agree that agents carry these credentials while acting as you` : ', with no logins ticked';
165
259
 
166
260
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
167
261
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
@@ -205,6 +299,7 @@ async function pull(path , dir ) {
205
299
  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);
206
300
  if (!into) throw new Error(`${from} can't be a name here: pull ${from}/ into a folder of your choosing`);
207
301
  let fetched = 0, same = 0, deleted = 0, failed = 0, big = 0;
302
+ const fetches = [];
208
303
  for (const f of list.filter(f => !excluded(rel(f)))) {
209
304
  const local = rel(f) ? under(into, rel(f)) : into, st = local && existsSync(local) ? statSync(local) : undefined;
210
305
  if (!local) {
@@ -220,15 +315,21 @@ async function pull(path , dir ) {
220
315
  big++;
221
316
  continue;
222
317
  }
223
- console.log(`${st ? 'changed' : 'new'} ${f.path}`);
224
- try {
225
- if (!dry) write(local, f.text ?? new Uint8Array(await (await api(f.url )).arrayBuffer()), f.mtime);
226
- fetched++;
227
- } catch (e) {
228
- failed++;
229
- console.error(`${f.path}: ${(e ).message}`);
230
- }
318
+ fetches.push(async () => {
319
+ console.log(`${st ? 'changed' : 'new'} ${f.path}`);
320
+ try {
321
+ if (!dry) write(local, f.text ?? new Uint8Array(await (await api(f.url )).arrayBuffer()), f.mtime);
322
+ fetched++;
323
+ } catch (e) {
324
+ failed++;
325
+ console.error(`${f.path}: ${(e ).message}`);
326
+ }
327
+ });
231
328
  }
329
+ // Up to 8 files are fetched at once, each started in the list's order.
330
+ await Promise.all(Array.from({ length: 8 }, async () => {
331
+ for (let next; (next = fetches.shift());) await next();
332
+ }));
232
333
  if (flags.delete && list.some(rel) && existsSync(into)) {
233
334
  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)]);
234
335
  for (const p of mine(into)) {
@@ -248,8 +349,8 @@ async function pull(path , dir ) {
248
349
  // 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.
249
350
  async function browserToken() {
250
351
  const { id, code } = await (await fetch(`${url}/auth/cli`, { method: 'POST', body: JSON.stringify({ name: `rf on ${hostname()}` }) })).json();
251
- const link = `${url}/cli?code=${code}`;
252
- console.log(`Open ${link}\nand allow rf there if the page shows the code ${code}.`);
352
+ const link = `${url}/cli`;
353
+ console.log(`Open ${link}\nand type the code ${code} there.`);
253
354
  spawn(process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open', [link], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
254
355
  for (;;) {
255
356
  await new Promise(ok => setTimeout(ok, 2000));
@@ -265,22 +366,62 @@ if (cmd === 'login' && url) {
265
366
  mkdirSync(dirname(config), { recursive: true });
266
367
  writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
267
368
  console.log(`signed in as ${me.email}`);
268
- } else if (cmd === 'ls') {
269
- const wakes = (list ) => {
270
- for (const k of list) console.log(` wake ${k.id} ${k.at}${k.label ? ` starts ${k.label}` : ''}${k.days ? `, then each ${k.days.join(', ')}` : ''}`);
271
- };
272
- for (const w of await get('/api')) for (const s of w.series) {
273
- console.log(`${w.name}/${s.name}${s.requests.length ? ` ${s.requests.length} asking to start` : ''}`);
274
- wakes(s.wakes);
275
- for (const i of s.instances) {
276
- console.log(`${w.name}/${s.name}/${i.label} ${i.status}${i.running ? ', running' : ''}${i.asks.length ? `, ${i.asks.length} asks waiting` : ''}, runner ${i.runner}`);
277
- wakes(i.wakes);
369
+ } else if (cmd === 'ls' && !args.length) {
370
+ const rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
371
+ { path: `${w.name}/${s.name}`, id: s.id, requests: s.requests.length, wakes: s.wakes },
372
+ ...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 })),
373
+ ]));
374
+ if (flags.json) console.log(JSON.stringify(rows, null, 1));
375
+ else for (const r of rows) {
376
+ 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` : ''}`);
377
+ 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(', ')}` : ''}`);
378
+ }
379
+ } else if (cmd === 'waiting' && !args.length) {
380
+ const [me, s, all] = await Promise.all([get('/me'), get('/api/status'), get('/api')]), mine = (who ) => (who ?? me.email) === me.email;
381
+ const series = all.flatMap(w => w.series.map(x => ({ ...x, path: `${w.name}/${x.name}` })));
382
+ const rows = [
383
+ ...s.asks.filter(a => a.who === me.email).map(a => ({ kind: a.note ? 'note' : 'ask', path: a.path, since: a.since, text: a.text })),
384
+ ...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}` }))),
385
+ ...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`}` })),
386
+ ...s.expired.filter(e => e.who === me.email).map(e => ({ kind: 'expired', login: e.login, holding: e.holding, text: `your ${e.login} login expired` })),
387
+ ...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(', ')}` })))),
388
+ ...all.filter(w => w.manage).flatMap(w => w.grants.filter(g => g.state === 'pending').map(g => ({ kind: 'grant', path: w.name, since: g.at, id: g.id, text: `${g.person} asks to use ${g.site} here: ${g.reason} (${g.check?.risk ? `${g.check.risk} risk` : 'not checked'})` }))),
389
+ ];
390
+ if (flags.json) console.log(JSON.stringify(rows, null, 1));
391
+ else console.log(rows.map(r => `${r.kind} ${r.path ?? r.login}${r.since ? ` since ${when(r.since)}` : ''}${r.id ? `, ${r.kind === 'grant' ? 'grant' : 'request'} ${r.id}` : ''}: ${r.text.split('\n')[0].slice(0, 120)}`).join('\n') || 'Nothing waits on you.');
392
+ } else if (cmd === 'show' && args.length === 1) {
393
+ const { inst, at } = await instanceAt(args[0]), { doc, log, run, queued, runner, waiting: w } = await get(at);
394
+ const waiting = w.map(({ who, seq }) => {
395
+ const e = log[seq - 1], first = log.find(x => `c${x.seq}` === e.thread);
396
+ return { comment: `c${seq}`, thread: e.thread, kind: e.ask ? 'ask' : 'note', for: who, by: e.by, item: first.item, ref: first.ref, text: e.text };
397
+ });
398
+ const done = log.findLast(e => e.op === 'done'), last = done ? { run: done.run, cost: done.cost, error: done.error ?? null } : null;
399
+ 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));
400
+ else {
401
+ console.log(`${args[0]} ${doc.status}, runner ${runner.by}${run ? `, run ${run.n} going, ${usd(run.cost)}` : queued ? ', queued' : ''}`);
402
+ 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}` : ''}`);
403
+ for (const w of waiting) console.log(`${w.comment} ${w.kind} for ${w.for}${w.comment === w.thread ? '' : ` in ${w.thread}`}${w.item ? `, on ${w.item}${w.ref ? ` at ${w.ref}` : ''}` : ''}: ${w.text.split('\n')[0].slice(0, 160)}`);
404
+ if (last) console.log(`last run ${last.run} ${usd(last.cost ?? 0)}${last.error ? ` ${last.error}` : ''}`);
405
+ }
406
+ } else if (cmd === 'log' && args.length === 1) {
407
+ const { at } = await instanceAt(args[0]);
408
+ for (let since = Number(flags.since ?? 0); ; await new Promise(ok => setTimeout(ok, 3000))) {
409
+ const fresh = (await get(at)).log.filter(e => e.seq > since);
410
+ for (const e of fresh) {
411
+ const { seq, at, by, op, text, ...rest } = e;
412
+ 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)}` : ''}`);
278
413
  }
414
+ since = fresh.at(-1)?.seq ?? since;
415
+ if (!flags.follow) break;
279
416
  }
417
+ } else if (cmd === 'cat' && args.length === 1) {
418
+ const path = args[0].replace(/^\/+|\/+$/g, ''), [f, ...more] = await get(`/api/files?path=${encodeURIComponent(path)}`);
419
+ 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]}`);
420
+ process.stdout.write(f.text ?? Buffer.from(await (await api(f.url)).arrayBuffer()));
280
421
  } else if (cmd === 'pull' && args.length === 2) await pull(args[0], args[1]);
281
422
  else if (cmd === 'comment' && args.length === 2) {
282
- const { at } = await find(args[0]);
283
- await post(`${at}/comment`, { text: args[1], item: flags.item, ref: flags.ref, thread: flags.thread });
423
+ const { at } = await instanceAt(args[0]);
424
+ await post(`${at}/comment`, { text: args[1], item: flags.item, ref: flags.ref, thread: flags.thread, quiet: !flags.wake && !flags.wait });
284
425
  const { log, runner } = await get(at), { seq, note } = log.at(-1);
285
426
  if (note) console.log(`a note for the runner, ${runner.by}, seq ${seq}: it starts no run until they act`);
286
427
  else if (!flags.wait) console.log(`commented, seq ${seq}`);
@@ -290,13 +431,117 @@ else if (cmd === 'comment' && args.length === 2) {
290
431
  const log = (await get(at)).log, done = log.find(e => e.op === 'done' && e.seen >= seq);
291
432
  if (!done) continue;
292
433
  const from = Math.max(seq, log.find(e => e.op === 'run' && e.run === done.run).seq);
293
- for (const e of log.filter(e => e.seq > from && e.seq < done.seq && ((e.op === 'comment' && e.by === 'agent') || e.op === 'report'))) console.log(`${e.op === 'report' ? 'Report' : `${e.ask ? 'Asks' : 'Says'} in ${e.thread}`}:\n${e.text}\n`);
434
+ for (const e of log.filter(e => e.seq > from && e.seq < done.seq && e.op === 'comment' && e.by === 'agent')) console.log(`${e.ask ? 'Asks' : 'Says'} in ${e.thread}:\n${e.text}\n`);
294
435
  if (done.error) console.log(`The run failed: ${done.error}`);
295
436
  break;
296
437
  }
438
+ } else if (cmd === 'react' && [2, 3].includes(args.length) && ['up', 'down', 'none'].includes(args.at(-1) )) {
439
+ const on = args.length === 3 ? Number(args[1].replace(/^c/, '')) : undefined, up = { up: true, down: false, none: null }[args.at(-1) ];
440
+ await post(`${(await instanceAt(args[0])).at}/react`, { ...(on !== undefined && { on }), up });
441
+ console.log(`${args.at(-1)} on ${args.length === 3 ? args[1] : args[0]}`);
442
+ } else if (cmd === 'signoff' && [2, 3].includes(args.length)) {
443
+ await post(`${(await instanceAt(args[0])).at}/signoff`, { thread: args[1], text: args[2], quiet: !flags.wake });
444
+ console.log(`signed off ${args[1]}`);
445
+ } else if (['close', 'abandon', 'interrupt'].includes(cmd) && args.length === 1) {
446
+ const { series, at } = await instanceAt(args[0]);
447
+ if (cmd === 'close' && typeof flags['as-series'] === 'string') await post(`/api/series/${series.id}/promote`, { name: flags['as-series'] });
448
+ await post(`${at}/${cmd}`, { quiet: !flags.wake });
449
+ console.log(`${cmd === 'close' ? 'closed' : `${cmd}ed`} ${args[0]}`);
450
+ } else if (cmd === 'takeover' && args.length === 1) {
451
+ await post(`${(await instanceAt(args[0])).at}/takeover`, { logins: ticks() });
452
+ console.log(`you run ${args[0]} now${consent(ticks())}`);
453
+ } else if (cmd === 'creds' && args.length === 1) {
454
+ const { at } = await instanceAt(args[0]);
455
+ if (flags.set !== undefined || flags.clear) {
456
+ await post(`${at}/logins`, { logins: ticks() });
457
+ console.log(`saved${consent(ticks())}`);
458
+ } else {
459
+ const [{ runner }, mine] = await Promise.all([get(at), get('/logins')]);
460
+ 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 }) }))) };
461
+ if (flags.json) console.log(JSON.stringify(out, null, 1));
462
+ 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'));
463
+ }
464
+ } else if (cmd === 'rename' && args.length === 2) {
465
+ const [w, s, l] = args[0].replace(/\/+$/, '').split('/');
466
+ if (l !== undefined) await post(`${(await instanceAt(args[0])).at}/rename?as=${encodeURIComponent(args[1])}`, {});
467
+ else if (s !== undefined) await post(`/api/series/${(await find(args[0])).series.id}`, { name: args[1] }, 'PUT');
468
+ else await post(`/api/workspaces/${(await workspaceNamed(w)).id}`, { name: args[1] }, 'PUT');
469
+ console.log(`renamed ${args[0]} ${args[1]}`);
470
+ } else if (cmd === 'new' && args[0] === 'task' && [2, 3].includes(args.length)) {
471
+ const { instance } = await (await post('/api/series', { workspace: (await workspaceNamed(args[1])).id, single: true, logins: ticks() })).json();
472
+ if (args[2]) await post(`/api/instances/${instance}/rename?as=${encodeURIComponent(args[2])}`, {});
473
+ if (typeof flags.comment === 'string') await post(`/api/instances/${instance}/comment`, { text: flags.comment, quiet: !flags.wake });
474
+ console.log(`made ${await pathOf(instance)}${consent(ticks())}`);
475
+ } else if (cmd === 'new' && args[0] === 'instance' && args.length === 3) {
476
+ const { id } = await (await post(`/api/series/${(await seriesAt(args[1])).id}`, { label: args[2], logins: ticks(), quiet: !flags.wake })).json();
477
+ console.log(`made ${await pathOf(id)}${consent(ticks())}`);
478
+ } else if (cmd === 'new' && args[0] === 'series' && args.length === 3) {
479
+ await post(`/api/series/${(await find(args[1])).series.id}/promote`, { name: args[2] });
480
+ console.log(`made the series ${args[1].split('/')[0]}/${args[2]}`);
481
+ } else if (cmd === 'new' && args[0] === 'workspace' && args.length === 2) {
482
+ await post('/api/workspaces', { name: args[1] });
483
+ console.log(`made ${args[1]}`);
484
+ } else if (cmd === 'copy' && args.length === 2) {
485
+ const { id } = await (await post(`${(await instanceAt(args[0])).at}/duplicate?as=${encodeURIComponent(args[1])}`, { logins: ticks() })).json();
486
+ console.log(`made ${await pathOf(id)}${consent(ticks())}`);
487
+ } else if (cmd === 'share' && ['on', 'off'].includes(args[1]) && args.length === 2) {
488
+ await post(`/api/series/${(await seriesAt(args[0])).id}`, { share: args[1] === 'on', logins: ticks() }, 'PUT');
489
+ console.log(args[1] === 'on' ? `shared ${args[0]}${consent(ticks())}` : `stopped sharing ${args[0]}`);
490
+ } else if (cmd === 'archive' && args.length === 1) {
491
+ const [w, s] = args[0].replace(/\/+$/, '').split('/');
492
+ await post(s === undefined ? `/api/workspaces/${(await workspaceNamed(w)).id}` : `/api/series/${(await seriesAt(args[0])).id}`, { archived: !flags.undo }, 'PUT');
493
+ console.log(`${flags.undo ? 'brought back' : 'archived'} ${args[0]}`);
494
+ } else if (cmd === 'request' && ['start', 'drop'].includes(args[0]) && args.length === 2) {
495
+ if (args[0] === 'drop') await api(`/api/requests/${args[1]}`, { method: 'DELETE' });
496
+ console.log(args[0] === 'drop' ? `dropped request ${args[1]}` : `made ${await pathOf((await (await post(`/api/requests/${args[1]}`, { logins: ticks(), quiet: !flags.wake })).json()).id)}${consent(ticks())}`);
497
+ } else if (cmd === 'logins' && !args.length) {
498
+ const all = await get('/logins');
499
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
500
+ else for (const l of all) {
501
+ 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(', ')}` : ''}`);
502
+ // A website's login offers itself alone.
503
+ for (const o of l.offers.filter(o => o.id !== l.id)) console.log(` offers ${o.id} ${o.name}`);
504
+ }
505
+ } else if (cmd === 'logins' && ['offer', 'unoffer', 'allow'].includes(args[0]) && args.length === 3) {
506
+ const [what, login, x] = args, at = `/logins/${encodeURIComponent(login)}`;
507
+ if (what === 'offer') await post(`${at}/offers`, { add: x });
508
+ else if (what === 'unoffer') await api(`${at}/offers/${encodeURIComponent(x)}`, { method: 'DELETE' });
509
+ else await post(`/logins/web/${encodeURIComponent(login)}/hosts`, { host: x });
510
+ console.log(`${login} ${{ offer: 'offers', unoffer: 'no longer offers', allow: 'reaches' }[what]} ${x}`);
511
+ } else if (cmd === 'site' && args[0] === 'add' && args.length === 3) {
512
+ const { site, existing } = await (await post('/logins/sites', { name: args[1], url: args[2] })).json();
513
+ console.log(`${existing ? `${args[2]} is ${site}'s` : `added ${site}`}: sign in to it at ${url}/#logins, then rf site ask ${site} WORKSPACE REASON`);
514
+ } else if (cmd === 'site' && args[0] === 'set' && args.length === 2) {
515
+ await post(`/logins/sites/${encodeURIComponent(args[1])}`, flags, 'PATCH');
516
+ console.log('saved');
517
+ } else if (cmd === 'site' && args[0] === 'remove' && args.length === 2) {
518
+ await api(`/logins/sites/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
519
+ console.log(`removed ${args[1]}`);
520
+ } else if (cmd === 'site' && args[0] === 'ask' && args.length === 4) {
521
+ const { id, check: c } = await (await post('/grants', { site: args[1], workspace: (await workspaceNamed(args[2])).id, reason: args[3] })).json();
522
+ console.log(`asked, as grant ${id}: ${c.risk === 'high' ? 'an admin approves or denies it, as the check rates it high risk' : `one of ${args[2]}'s owners approves or denies it`}\n${!c.risk ? `not checked: ${c.error}`
523
+ : `check: ${c.risk} risk${c.flags.length ? ` (${c.flags.join('; ')})` : ''}. ${c.summary}${c.same ? ` It looks like ${c.same}, a website here already.` : ''}${c.hosts.length ? ` Approving lets it reach ${c.hosts.join(', ')}.` : ''}`}`);
524
+ } else if (cmd === 'grants' && args.length <= 1) {
525
+ const [all, ws] = await Promise.all([get('/grants'), get('/api')]), name = (id ) => ws.find(w => w.id === id)?.name ?? id;
526
+ const shown = all.filter(g => !args[0] || name(g.workspace) === args[0]);
527
+ if (flags.json) console.log(JSON.stringify(shown.map(g => ({ ...g, workspace: name(g.workspace) })), null, 1));
528
+ else for (const g of shown) console.log(`${g.id} ${g.state} ${g.site} in ${name(g.workspace)} for ${g.person}, since ${when(g.at)}: ${g.reason}${g.by ? `; ${g.state} by ${g.by}${g.text ? `: ${g.text}` : ''}` : ''} (${g.check?.risk ? `${g.check.risk} risk` : 'not checked'})`);
529
+ } else if (cmd === 'grant' && ['approve', 'deny'].includes(args[0]) && [2, 3].includes(args.length)) {
530
+ await post(`/grants/${args[1]}`, { approve: args[0] === 'approve', text: args[2] });
531
+ console.log(args[0] === 'approve' ? 'approved' : 'denied');
532
+ } else if (cmd === 'grant' && args[0] === 'revoke' && args.length === 2) {
533
+ await api(`/grants/${args[1]}`, { method: 'DELETE' });
534
+ console.log('revoked');
535
+ } else if (cmd === 'logins' && args[0] === 'signout' && args.length === 2) {
536
+ await api(`/logins/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
537
+ console.log(`signed out of ${args[1]}`);
538
+ } else if (cmd === 'correct' && args.length === 2) {
539
+ const { series, at } = await instanceAt(args[0]), see = flags.see === undefined ? undefined : series.instances.find(i => i.label === flags.see);
540
+ if (flags.see !== undefined && !see) throw new Error(`no instance ${flags.see} in its series`);
541
+ 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());
297
542
  } else if (cmd === 'upload' && args.length === 2) {
298
- const q = new URLSearchParams({ name: basename(args[1]), pane: flags.output ? 'out' : 'in', ...(typeof flags.onto === 'string' && { onto: flags.onto }) });
299
- await api(`${(await find(args[0])).at}/upload?${q}`, { method: 'POST', body: readFileSync(args[1]) });
543
+ const q = new URLSearchParams({ name: basename(args[1]), pane: flags.output ? 'out' : 'in', ...(typeof flags.onto === 'string' && { onto: flags.onto }), ...(!flags.wake && { quiet: '1' }) });
544
+ await api(`${(await instanceAt(args[0])).at}/upload?${q}`, { method: 'POST', body: readFileSync(args[1]) });
300
545
  console.log('uploaded');
301
546
  } else if (cmd === 'wake' && typeof flags.cancel === 'string' && !args.length) {
302
547
  await api(`/api/wakes/${flags.cancel}`, { method: 'DELETE' });
@@ -307,8 +552,7 @@ else if (cmd === 'comment' && args.length === 2) {
307
552
  const w = await (await post(`/api/wakes/${inst?.id ?? series.id}`, { at: new Date(at).toISOString(), label: flags.label, days: flags.days }, 'PUT')).json();
308
553
  console.log(`wake ${w.id} at ${w.at}${w.days ? `, then each ${w.days.join(', ')}` : ''}`);
309
554
  } else if (cmd === 'agents' && args.length <= 1) {
310
- const ws = args[0] === undefined ? undefined : (await get('/api')).find(w => w.name === args[0]);
311
- if (args[0] !== undefined && !ws) throw new Error(`no workspace ${args[0]}`);
555
+ const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
312
556
  if (typeof flags.set !== 'string') console.log(ws ? ws.agents : (await get('/agents')).text);
313
557
  else {
314
558
  const text = readFileSync(flags.set === '-' ? 0 : flags.set, 'utf8');
@@ -331,13 +575,19 @@ else if (cmd === 'comment' && args.length === 2) {
331
575
  }
332
576
  console.log(`pulled ${args[1]} version ${n} into ${dir}`);
333
577
  } else if (cmd === 'skill' && args[0] === 'versions' && args[1]) {
334
- for (const v of await get(`/skills/${encodeURIComponent(args[1])}/versions`)) console.log(`${v.version} ${v.at} ${v.by}`);
578
+ const versions = await get(`/skills/${encodeURIComponent(args[1])}/versions`);
579
+ if (flags.json) console.log(JSON.stringify(versions, null, 1));
580
+ else for (const v of versions) console.log(`${v.version} ${v.at} ${v.by}`);
335
581
  } else if (cmd === 'skill' && args[0] === 'rollback' && args.length === 3) {
336
582
  console.log(await (await post(`/skills/${encodeURIComponent(args[1])}/versions`, { from: Number(args[2]) })).text());
337
583
  } else if (cmd === 'skills') {
338
- for (const s of await get('/skills')) console.log(`${s.id} v${s.pushed.version} by ${s.pushed.by} ${s.pushed.at} ${s.description}`);
584
+ const skills = await get('/skills');
585
+ if (flags.json) console.log(JSON.stringify(skills, null, 1));
586
+ else for (const s of skills) console.log(`${s.id} v${s.pushed.version} by ${s.pushed.by} ${s.pushed.at} ${s.description}`);
339
587
  } else if (cmd === 'connections') {
340
- for (const { name, type, login, updated_by, updated_at, ...settings } of await get('/connections')) console.log(`${name} ${type} ${JSON.stringify(settings)}`);
588
+ const all = await get('/connections');
589
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
590
+ else for (const { name, type, login, updated_by, updated_at, ...settings } of all) console.log(`${name} ${type} ${JSON.stringify(settings)}`);
341
591
  } else if (cmd === 'connection' && args[0] === 'set' && args.length === 3) {
342
592
  await post(`/connections/${encodeURIComponent(args[1])}`, { type: args[2], ...flags }, 'PUT');
343
593
  console.log('saved');
@@ -354,7 +604,7 @@ else if (cmd === 'comment' && args.length === 2) {
354
604
  [`Waiting`, [
355
605
  ...[...s.asks, ...s.requests.map(r => ({ ...r, who: r.who ?? 'anyone', since: r.at, text: `${r.from} asks to start ${r.label}`, request: true })),
356
606
  ...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 }))]
357
- .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)}`),
607
+ .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.note ? 'a note' : 'an ask'} in ${a.path} since ${when(a.since)}: ${a.text.split('\n')[0].slice(0, 80)}`),
358
608
  ...s.expired.map(e => `${e.who} their ${e.login} login expired${e.holding.length ? `, holding ${e.holding.join(', ')}` : ''}`),
359
609
  ]],
360
610
  [`Last run failed`, s.failed.map(f => `${f.path} run ${f.run} at ${when(f.at)}: ${f.error}`)],
@@ -371,13 +621,13 @@ else if (cmd === 'comment' && args.length === 2) {
371
621
  } else if (cmd === 'runs' && args.length <= 1) {
372
622
  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));
373
623
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
374
- 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 ?? ''}`);
624
+ 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 ?? ''}`);
375
625
  } else if (cmd === 'costs' && args.length <= 1) {
376
626
  const by = String(flags.by ?? 'series'), key = {
377
627
  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),
378
628
  outcome: r => r.failure ? `failed, ${r.failure}` : r.outcome,
379
629
  }[by];
380
- if (!key) throw new Error(USAGE);
630
+ if (!key) throw new Error('--by: workspace, series, person, day or outcome');
381
631
  // A run a restart cut is carried on by the next, so it adds its cost, not a run.
382
632
  const sums = new Map (), rows = await runsIn(args[0]), counted = (r ) => r.outcome === 'cut' ? 0 : 1;
383
633
  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 });
@@ -405,17 +655,17 @@ else if (cmd === 'comment' && args.length === 2) {
405
655
  if (flags.json) console.log(JSON.stringify(blocks, null, 1));
406
656
  else for (const b of blocks) {
407
657
  console.log(b.path);
408
- for (const e of b.entries) console.log(` ${when(e.at)} ${e.op === 'done' ? `run ${e.run} ${e.error ?? e.summary ?? 'no report'}`
658
+ for (const e of b.entries) console.log(` ${when(e.at)} ${e.op === 'done' ? `run ${e.run} failed: ${e.error}`
409
659
  : `${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`}`}`);
410
660
  }
411
661
  } else if (cmd === 'people' && args.length <= 1) {
412
662
  // People as lines to edit and set: ROLE EMAIL for everyone, owner|member EMAIL-OR-GROUP for a workspace, each with a comment.
413
- const ws = args[0] === undefined ? undefined : (await get('/api')).find(w => w.name === args[0]);
414
- if (args[0] !== undefined && !ws) throw new Error(`no workspace ${args[0]}`);
415
- const last = (iso ) => iso ? `last in ${when(iso)}` : 'never in';
416
- 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(', ')}`] }))
417
- : (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(', ')}`] }));
418
- if (typeof flags.set !== 'string') {
663
+ const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
664
+ const last = (iso ) => iso ? `last in ${when(iso)}` : 'never in', listed = await get(ws ? `/api/workspaces/${ws.id}/people` : '/users');
665
+ 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(', ')}`] }))
666
+ : 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(', ')}`] }));
667
+ if (flags.json && typeof flags.set !== 'string') console.log(JSON.stringify(listed, null, 1));
668
+ else if (typeof flags.set !== 'string') {
419
669
  const w = Math.max(0, ...now.map(p => p.who.length));
420
670
  for (const p of now) console.log(`${p.kind.padEnd(6)} ${p.who.padEnd(w)} # ${p.note.filter(Boolean).join('; ')}`);
421
671
  if (!now.length) console.log('# no one is in it: only admins see it');
@@ -441,13 +691,14 @@ else if (cmd === 'comment' && args.length === 2) {
441
691
  await post('/brand', { clear: flags.clear, text: flags.text, logo }, 'PUT');
442
692
  console.log('saved');
443
693
  } else {
444
- const { text, logo } = (await get('/me')).brand;
445
- console.log(text || logo ? `${text ?? 'no text'}, ${logo ? 'with a logo' : 'no logo'}` : 'no brand: the plain look');
694
+ const { brand } = await get('/me'), { text, logo } = brand;
695
+ console.log(flags.json ? JSON.stringify(brand) : text || logo ? `${text ?? 'no text'}, ${logo ? 'with a logo' : 'no logo'}` : 'no brand: the plain look');
446
696
  }
447
697
  } else if (cmd === 'can' && args.length <= 2) {
448
698
  const [cap, list] = args, people = flags.clear ? [] : list?.split(',').map(p => p.trim()).filter(Boolean);
449
699
  const all = await (await (people ? post('/capabilities', { cap, people }, 'PUT') : api('/capabilities'))).json();
450
- for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || 'admins only'}`);
700
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
701
+ else for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || 'admins only'}`);
451
702
  } else if (cmd === 'user' && args.length >= 2) {
452
703
  const [what, email, role] = args, at = `/users/${encodeURIComponent(email)}`;
453
704
  if (what === 'add') await post('/users', { roles: { [email]: role ?? 'user' } }, 'PUT');
@@ -455,9 +706,12 @@ else if (cmd === 'comment' && args.length === 2) {
455
706
  else if (what === 'disable' || what === 'enable') await post(at, { disabled: what === 'disable' }, 'PUT');
456
707
  else if (what === 'signout') await post(at, { signout: true }, 'PUT');
457
708
  else if (what === 'remove') await api(at, { method: 'DELETE' });
458
- else throw new Error(USAGE);
709
+ else {
710
+ console.error(usage(cmd));
711
+ process.exit(2);
712
+ }
459
713
  console.log('done');
460
714
  } else {
461
- console.error(USAGE);
715
+ console.error(usage(cmd));
462
716
  process.exitCode = 2;
463
717
  }