@rfany/rf 0.14.0 → 0.16.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 +5 -1
  2. package/package.json +1 -1
  3. package/rf.mjs +405 -168
package/README.md CHANGED
@@ -6,4 +6,8 @@ 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 and `rf help COMMAND` gives one's usage; `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. Without saved config, help works offline; once signed in, it reads your current capabilities from the server.
10
+
11
+ `rf site ask NAME WORKSPACE REASON` asks its owners to use your login there, or approves it at once where you may. `rf grants` describes the system and what runs may do; general platforms and high-risk or failed checks need an admin. Only admins allow hosts, with `rf logins allow SITE HOST --person EMAIL`; you remove one with `rf logins disallow SITE HOST`.
12
+
13
+ On servers with client VPN support, only people explicitly granted `vpn` see its commands in help; being an admin is not enough. `rf vpns` lists definitions and your connection states; sign in on the page. `rf site set NAME --via VPN` selects one for your website, `--via ''` clears it, and `rf sites` shows it. Opted-in admins manage definitions with `rf vpn add NAME fortinet HOST:PORT [--servercert pin-sha256:HASH]` and `rf vpn remove NAME`; admins grant access with `rf can vpn EMAIL|GROUP,...` and revoke it with `rf can vpn --clear`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfany/rf",
3
- "version": "0.14.0",
3
+ "version": "0.16.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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // rf for people: what the page does, from a shell or a desktop agent, as you, with a personal token made on the page (Tokens).
3
3
  // Published to npm as @rfany/rf, from cli/. PATH is workspace/series/label, as `rf ls` prints it.
4
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
4
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync, } from 'node:fs';
5
5
  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';
@@ -12,11 +12,14 @@ process.on('uncaughtException', e => {
12
12
  process.exit(1);
13
13
  });
14
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
15
+ const usage = (c , vpn = false, admin = false) => {
16
+ const all = `rf login URL [TOKEN] without a TOKEN, through the browser: type rf's code on the page, and allow it
17
+ rf ls [--mine] [--json] every workspace, series and instance you see, with its status, runner, asks waiting and wakes;
18
+ --mine, only the open instances you run
19
+ rf waiting [--json] what waits on you: asks and notes, instances someone assigned you, requests to start or wake an
20
+ instance or to use a
21
+ website in a workspace you own, proposals and expired logins; only admins see hosts a run's
22
+ browser was refused that the server rates high or finds at an internal address
20
23
  rf show PATH [--json] an instance: its items, the threads that wait on someone, by id, and its last run
21
24
  rf log PATH [--since SEQ] [--follow] [--json] its log, a line an entry, after SEQ; --follow prints more as they come;
22
25
  --json prints the entries as they are, a line each
@@ -24,21 +27,30 @@ rf cat PATH/FILE one file, to stdout
24
27
  rf pull PATH DIR [--delete] [-n|--dry-run] [--exclude PATTERN]... [--max-size SIZE]
25
28
  PATH's files into DIR as rsync copies them, whole, if their size or time differ: PATH/ fills DIR,
26
29
  PATH makes DIR/<its name>, / is all you see; --delete removes what the server no longer has;
27
- --max-size skips files bigger than SIZE, such as 50M
30
+ --max-size skips files bigger than SIZE, such as 50M; on Windows and macOS, of two names
31
+ that differ only in case, the second is skipped
28
32
  rf help [COMMAND] how rollforward works and how to use rf, for an agent, or COMMAND's usage
29
33
  rf --version rf's own version, to tell whether it's older than what the guide names
30
34
  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
35
+ an agent's question; --wake starts a run on it, as --wait does, which prints what the agent
36
+ says back
32
37
  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
38
+ rf approve PATH cN [TEXT] [--wake] approves the agent's proposal cN: it goes ahead with it, and the folder is
39
+ committed as it is now, in your name; a reply approves nothing
40
+ rf reject PATH cN [TEXT] [--wake] rejects the agent's proposal cN: it won't do it, and carries on as TEXT says
35
41
  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
42
  rf close PATH [--as-series NAME] [--wake] the runner makes it the record and an example,
37
43
  approving nothing; a task closes as a one-off, or as the first instance of the series NAME it
38
44
  becomes; --wake starts runs of the series' later open instances, which may have used its draft
39
45
  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
46
+ rf delete PATH [--yes] its workspace's owners and admins delete an instance, in any status, once they confirm, or
47
+ with --yes: a run for it is cut, and all the server holds of it goes but its label and place,
48
+ shown as deleted, by whom and when; it can't be undone, and copies outside the server stay
49
+ rf interrupt PATH stops its run: its runner, an owner of its workspace or an admin
50
+ rf takeover PATH [--creds OFFER,...] you run it from now on, with those offers of your logins ticked; a run going is stopped
51
+ first, if you may stop it
52
+ rf assign PATH EMAIL EMAIL runs it from now on, ticking their own logins, none until they do: its runner, its
53
+ workspace's owners and admins; a run going is stopped first
42
54
  rf creds PATH [--set OFFER,...|--clear] what its runs may use: its runner's ticks, and the offers of your logins; --set
43
55
  ticks anew, as its runner
44
56
  rf rename PATH NAME an instance, a series or a workspace, by its path
@@ -47,42 +59,50 @@ rf new task WORKSPACE [LABEL] [--creds OFFER,...] [--comment TEXT [--wake]] a
47
59
  rf new instance SERIES LABEL [--creds OFFER,...] [--wake] the series' next instance, which --wake runs at once
48
60
  rf new series PATH NAME the task at PATH becomes the series NAME, itself its first instance
49
61
  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
62
  rf share PATH on|off [--creds OFFER,...] the series' people, and their agents, wake it as you, with those offers ticked;
52
63
  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
64
+ rf archive PATH [--undo] a workspace or a series leaves the sidebar, and nothing in it changes or runs, until --undo brings it back;
65
+ its wakes and requests are cancelled for good
66
+ rf request start|drop ID [--creds OFFER,...] [--wake] a request to start or wake an instance, by the ID rf waiting and rf
67
+ wakes print; --wake runs the instance it starts or wakes
56
68
  rf logins [--json] your logins, each with its state, keepalive and offers; you sign in to them on the page
57
69
  rf logins offer|unoffer LOGIN SOURCE|OFFER what a login offers runs: Microsoft 365's (m365) mailboxes, sites, folders and
58
70
  files, by address or link, a Databricks login's SQL warehouses, by link; unoffer takes the
59
71
  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
72
+ rf logins allow SITE HOST --person EMAIL admins alone allow a host the server left refused; one at an internal address
73
+ is allowed once for everyone's websites
74
+ rf logins disallow SITE HOST a host your website SITE reaches no more, which stays refused, the server's check letting
75
+ it no more
76
+ rf logins signout LOGIN${vpn ? '\nrf vpns [--json] client VPNs and whether you are connected to each; sign in on the page' : ''}
77
+ rf sites [--json] your websites, each with its address and the other hosts it reaches, with what the server's
78
+ check said of those it let it reach
79
+ rf site add NAME URL [--header NAME] a website of your own, by a NAME you choose, whose sign-in starts at URL, which you
80
+ sign in to on the page; --header names a header its sign-in needs that its pages never
81
+ send, such as x-bot-token, whose value you give as you sign in
82
+ rf site set NAME [--header NAME] [--keepalive PAGE] [--every 10m] [--writeback false]${vpn ? ' [--via VPN]' : ''}
83
+ your website NAME: a header its sign-in needs that its pages never send, such as
84
+ x-bot-token, or '' to clear, whose value you give as you sign in, the page a login kept alive loads, by
85
+ address or path, else its address, and how often, 10m unless given, and whether a run's
86
+ browser writes its state back; admins set --internal true|false, with --person EMAIL for
87
+ someone's, for its browsers to reach internal hosts, and its hosts at internal addresses
88
+ everyone's websites, with no admin again, until one sets it false${vpn ? "\n --via VPN routes this website through your connection to that client VPN; --via '' clears it" : ''}
89
+ rf site remove NAME your website NAME, with your login to it and your grants for it
74
90
  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
91
+ or denies, seeing what the system is and what runs may do; an admin decides general platforms,
92
+ high risk and failed checks; asked by someone who may approve it, an owner or an admin, it's
93
+ approved at once; a login no approved grant uses is signed out a week after sign-in, and once
77
94
  you have no grant to it pending or approved
78
95
  rf grants [WORKSPACE] [--json] the grants to use websites, yours and those of the workspaces you own, with their states
79
96
  rf grant approve|deny ID [TEXT] a request to use a website in a workspace you own, with TEXT for its asker
80
97
  rf grant revoke ID a grant pending or approved, yours or in a workspace you own; its runs' browsers close
81
98
  rf correct PATH TEXT [--item ID] [--ref REF] [--superseded] [--see LABEL] a closed instance, or its item ID at REF, is
82
99
  wrong, or superseded, as LABEL, another instance of its series, shows; it can't be withdrawn
83
- rf wake PATH AT [--label LABEL] [--days DAYS] | rf wake --cancel ID
84
- AT now, +<n>m|h|d or a date; PATH an open instance, or a series with LABEL; DAYS, such as
85
- mon-fri, repeats it weekly at AT's time; rf ls shows each wake's ID
100
+ rf wake PATH AT [TEXT] [--label LABEL] [--days DAYS] | rf wake --cancel ID
101
+ AT now, +<n>m|h|d or a date; PATH an open instance, or a series with LABEL; TEXT a short
102
+ message for the run it starts; DAYS, such as mon-fri, repeats it weekly at AT's time; rf ls
103
+ shows each wake's ID
104
+ rf note SERIES [TEXT] [--json] tells the series something for its runs, about the series rather than one period or while no
105
+ instance is open, which starts no run; without TEXT, its notes, open and settled
86
106
  rf agents [WORKSPACE] [--set FILE|-] the company's AGENTS.md, or a workspace's; setting the company's is for admins
87
107
  rf readers WORKSPACE [add|remove OTHER] the workspaces whose agents read WORKSPACE and those its own read, as each one's
88
108
  owners let them; its owners let OTHER's agents read it, one they see, and its owners or
@@ -91,18 +111,19 @@ rf skills
91
111
  rf skill pull ID [DIR] [--version N] the newest version, or N, into DIR, ./ID by default, new or empty, as push reads it
92
112
  rf skill versions ID
93
113
  rf connections
94
- rf status [--long MIN] [--json] what goes on and what's stuck: runs going, flagged past MIN minutes (30), and queued, with why;
95
- what waits on whom since when; open instances whose last run failed
114
+ rf status [--long MIN] [--json] what goes on and what's stuck: low OpenRouter credit (for admins), runs going, flagged past
115
+ MIN minutes (30), and queued, with why; what waits on whom since when; open instances whose last run failed
96
116
  rf indexes [--json] each index of a source you index, all for admins: its kind, items and size, and per person
97
117
  its phase, crawl or follow, pages read, when last caught up, and its error and next try
98
118
  rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] [--json]
99
119
  a line per run: start, path, run, outcome, time, cost, what started it, and any error;
100
120
  the outcome is done, interrupted by a person, cut, by a restart or a change that broke its
101
121
  lease, running, or failed, for credits, policy, time limit or other
102
- rf costs [PATH] [--since DATE] [--by workspace|series|person|day|outcome] [--json] totals, runs and cost per run; person
103
- is the runner; runs leave out those that were cut, as the next run carries each on
104
- rf activity [PATH] [--since DATE] [--json] per instance, what people and the agent said, what people uploaded and closed, and
105
- each run that failed
122
+ rf costs [PATH] [--since DATE] [--by workspace|series|person|day|outcome] [--daily] [--json] totals, runs and cost per run,
123
+ plus server calls and OpenRouter key usage for admins; --daily lists each day by workspace,
124
+ person, run and server; runs leave out those that were cut, as the next run carries each on
125
+ rf activity [PATH] [--since DATE] [--json] per instance, what people and the agent said, what people uploaded, closed and
126
+ deleted, and each run that failed
106
127
  rf wakes [PATH] [--json] each series' pending wakes and requests to start an instance, and when a wake of it last
107
128
  fired, and each instance's pending wakes
108
129
  rf people WORKSPACE [--set FILE|-] [-n] [--force] its owners and admins: its people as lines of owner|member EMAIL-OR-GROUP,
@@ -119,9 +140,13 @@ rf people [--set FILE|-] [-n] [--force] everyone as lines of ROLE EMAIL, each
119
140
  rf user add EMAIL [admin] | role EMAIL admin|user [--force] | disable EMAIL | enable EMAIL | signout EMAIL | remove EMAIL
120
141
  rf egress [add|remove HOST] the hosts runs may reach beyond package registries, GitHub and documentation sites, such as
121
142
  api.example.com or *.example.org; admins add and remove them
143
+ rf internal [remove HOST] [--json] the hosts at internal addresses admins let every website reach, each with who let it and
144
+ when, as rf site set NAME --internal true or allowing one does; remove takes one out, after
145
+ which everyone's websites at it wait for an admin again
122
146
  rf connection set NAME TYPE an outside system runs reach as their runner, by a login each person makes: graph,
123
147
  Microsoft 365, or databricks, Azure Databricks, as each person adds what their login
124
- offers; websites are rf site's
148
+ offers; service --url http://HOST:PORT --paths 'AP/,GL/2026/' [--key KEY] lends paths
149
+ through a deployment's service at https://NAME.rf.internal/; websites are rf site's
125
150
  rf connection remove NAME
126
151
  rf brand [--text TEXT] [--logo FILE] [--clear] the deployment's text and logo, a .png, .jpg, .gif, .webp or .svg, which top
127
152
  the sidebar and are the page's title and icon; --clear goes back to the plain look, and with
@@ -130,7 +155,9 @@ rf can [CAP [EMAIL|GROUP,...] [--clear]] what users may do beyond the rest, as
130
155
  create, make workspaces; and keepalive, keep their website logins alive for up to a
131
156
  week as they sign in; a list grants CAP to those
132
157
  emails and Entra group ids in place of whom it had, --clear to no one, and with neither it
133
- prints whom each is granted to`;
158
+ prints whom each is granted to${vpn ? '\n vpn, using client VPNs, needs an explicit grant even for admins' : ''}${vpn && admin ? '\nrf vpn add NAME fortinet HOST:PORT [--servercert pin-sha256:HASH] admins with vpn add a client VPN definition, which each\n person signs in to on the page; --servercert pins the gateway key, as a refusal names it\nrf vpn remove NAME admins with vpn remove a client VPN definition' : ''}`;
159
+ return (c && all.split(/\n(?=\S)/).map(e => e.trimEnd()).filter(e => e.split(/\s/)[1] === c).join('\n')) || all;
160
+ };
134
161
 
135
162
  const GUIDE = `rollforward runs a team's recurring work, such as a weekly borrowing base or a month-end reconciliation, with an agent
136
163
  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
@@ -142,58 +169,69 @@ What there is
142
169
  - An instance's screen is its items: inputs, outputs and steps, each pointing at a file, with what it's made from. People upload
143
170
  files, and review the work in threads with the agent. The runner is the person whose logins the runs use, and who closes the
144
171
  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
145
- 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
146
- does.
147
- - rf is quiet: a comment, upload, sign-off, close, new instance or request it starts begins no run unless --wake, and the agent
172
+ runner shares the series, and a reply, approval or rejection from whom an ask names; anyone else's is a note, as are a wake someone else sets, another
173
+ instance's agent's comment and rf note's notes on a series: the agent's next run reads it, using what it brings and putting what
174
+ it asks for to the runner. The runner changes only by an assign, rf takeover or rf assign, which stops a run going: what came
175
+ before it is a note to the agent, whoever said it, and starts nothing.
176
+ - rf is quiet: a comment, upload, approval, rejection, close, new instance or request it starts begins no run unless --wake, and the agent
148
177
  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.
149
178
  - 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
150
- 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
151
- comment that waits on someone, the one it names or else the runner, until someone replies under it. rf ls says how many asks
152
- wait in each instance. Reactions, thumbs up or down, are quiet signals kept for later. An ask
153
- may pin files, kept with their sha256 as the agent asks; anyone who sees the instance may sign it off, which commits the
154
- instance's folder to its history, .git in it, as closing does. Whose sign-off counts, and for what, is the series' call.
179
+ opening words, and replies go under any comment in it, cN by its seq, a thread's id its first comment's. The agent asks
180
+ questions, which wait on someone, the one it names or else the runner, until a person replies under it, and proposes what it
181
+ will do for its runner, such as sending mail, which waits until someone approves or rejects it, or the agent withdraws it; a
182
+ reply under a proposal approves nothing. rf ls says how many asks wait in each instance. Reactions, thumbs up or down, are
183
+ quiet signals kept for later. Anyone who sees the instance may approve a proposal, which commits the instance's folder to its
184
+ history, .git in it, as it is then, as closing does. Whose approval counts, and for what, is the series' call.
155
185
 
156
186
  What rf pull copies, the folders as the agent sees them
157
187
  AGENTS.md the company's conventions; <workspace>/AGENTS.md the workspace's
158
188
  <workspace>/<series>/<label>/
159
- screen.json the screen: {rev, status, items: [{id, name, kind, file, from, headline, source, destination, as_of}]}
189
+ screen.json the screen: {rev, status, items: [{id, name, kind, file, from, headline, source, destination}]}
160
190
  log.jsonl every event, by seq: by is a person's email, "server" or "agent"; op is upload, comment (thread, item,
161
- ref, parent, text, files, ask, to), signoff (someone's, on the ask it names, with its commit), react,
191
+ ref, parent, text, files, ask, question or proposal, to), signoff (an approval of the proposal it names, on,
192
+ with its commit), reject, withdraw (the agent's, of its question or proposal on), react,
162
193
  commit, point and item (the screen changing), run, done (its cost, or error), close, and the rest
163
194
  upload/ what people uploaded, their comments' attachments in upload/attachments/
164
195
  working/ what the agent made, its scripts, and process.md, how it does this series
165
- session/ each session's transcript, which may carry several runs: every message and tool call
196
+ session/ each run's transcript: every message and tool call
166
197
  browser/ each run's browser requests, and its screenshots
167
198
  names.tsv each instance in the latest run's reach, id<TAB>/work/<workspace>/<series>/<label>: names can
168
199
  change, so where a path in a file doesn't match, look its id up in the names.tsv of the commit
169
200
  that last changed the file (git log -1 -- FILE, then git show H:names.tsv), and its name now in
170
201
  rf ls
202
+ pylib.tsv the series' .pylib, the Python packages its runs installed, which later runs run, as the latest
203
+ run started: path<TAB>size<TAB>change time, one file a line
171
204
  The copy is read-only: only rf's commands change what's on the server.
172
205
 
173
206
  Usual work
174
207
  - What waits on me: rf waiting, then rf show PATH, which names each comment that waits by its id.
175
- - Answer an ask: rf comment PATH TEXT --thread cN --wait, which prints what the agent says back; sign off one that pins files:
176
- rf signoff PATH cN [TEXT] --wake, for the agent to carry on. Close an
208
+ - Answer a question: rf comment PATH TEXT --thread cN --wait, which prints what the agent says back. Decide a proposal:
209
+ rf approve PATH cN [TEXT] --wake, for the agent to go ahead, or rf reject PATH cN [TEXT] --wake. Close an
177
210
  instance once it's the record: rf close PATH.
178
- - Take an instance over: rf creds PATH lists the offers of your logins, and rf takeover PATH --creds OFFER,... ticks them.
211
+ - Take an instance over: rf creds PATH lists the offers of your logins, and rf takeover PATH --creds OFFER,... ticks them. Hand
212
+ one you run, or one in a workspace you own, to someone else: rf assign PATH EMAIL; they tick their own logins with rf creds
213
+ PATH --set. Either way, what came before is history to the agent, and the next run waits for the new runner's act.
179
214
  - Your logins: rf logins lists them, with what each offers, and an expired one's link to sign in again on the page.
180
215
  - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output], with --wake on the last for a run on them
181
216
  all.
182
217
  - Start an instance: rf new instance SERIES LABEL --wake, as you, or rf wake SERIES now --label LABEL, which starts it as
183
218
  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
184
219
  one-off: rf new task WORKSPACE --comment TEXT --wake, which becomes a series with rf new series PATH NAME.
220
+ - Tell a series something for its runs, such as a rule from now on, or while no instance is open: rf note SERIES TEXT, which
221
+ starts no run; rf note SERIES lists its notes, open, and settled by a run or by hand.
185
222
  - 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
186
223
  for a file; rf pull PATH/ DIR copies the folder, with session/ for every step.
187
224
 
188
225
  Watching over it, for admins and power users; each sees what the caller sees
189
- - What's stuck: rf status lists runs going, flagging those past --long MIN (30); queued runs, since when and why: their series is
190
- running, the RF_MAX_RUNS cap, or memory; what waits on whom since when: asks, notes for runners, expired logins and the instances
226
+ - What's stuck: rf status lists low OpenRouter credit (for admins), runs going, flagging those past --long MIN (30); queued runs, since when and why: their series is
227
+ running, an update's drain, the RF_MAX_RUNS cap, or memory; what waits on whom since when: asks, notes for runners, expired logins and the instances
191
228
  they hold, and requests to start; open instances whose last run failed; and indexes crawling or failing.
192
229
  - Indexes: rf indexes shows each index of a big library or mailbox you index, every one for admins: its items and size, and per
193
230
  person whether it is crawling or following changes, pages read, when last caught up, and an error, if any, with its next try.
194
231
  - History: rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] prints a line per run: its start, path, run number,
195
232
  outcome, time taken, cost, what started it and by whom, and any error. rf costs [PATH] [--since DATE] [--by
196
- workspace|series|person|day] totals them, by the runner for person.
233
+ workspace|series|person|day|outcome] [--daily] totals them (by the runner for person, plus server calls and OpenRouter key usage
234
+ for admins). A DATE such as 2026-11-01 starts at its midnight on this machine's clock, the days --by day groups by.
197
235
  - People: rf people (admins) prints everyone as ROLE EMAIL lines, and rf people WORKSPACE (its owners and admins) its owners and
198
236
  members as owner|member lines; a comment after each says when they last signed in and which open instances they run, and for
199
237
  everyone those they run in workspaces they aren't in. Edit the lines, see the changes with --set FILE -n (FILE may be - for
@@ -201,16 +239,13 @@ Watching over it, for admins and power users; each sees what the caller sees
201
239
  does); for a workspace it replaces its people. A change that would hide an open instance from the person who runs it is refused,
202
240
  naming them, unless --force: have someone who stays take those over first.`;
203
241
 
204
- // A command's usage, as USAGE gives it; with none known, every command's.
205
- const usage = (c ) => (c && USAGE.split(/\n(?=\S)/).map(e => e.trimEnd()).filter(e => e.split(/\s/)[1] === c).join('\n')) || USAGE;
206
-
207
242
  const config = join(homedir(), '.config', 'rollforward.json');
208
243
  const [cmd, ...argv] = process.argv.slice(2);
209
244
  const flags = {}, excludes = [], args = [];
210
245
  for (let i = 0; i < argv.length; i++) {
211
246
  const flag = argv[i] === '-n' ? 'dry-run' : argv[i].match(/^--(.+)$/)?.[1];
212
247
  if (!flag) args.push(argv[i]);
213
- else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount'].includes(flag)) flags[flag] = true;
248
+ else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount', 'yes', 'mine', 'daily'].includes(flag)) flags[flag] = true;
214
249
  else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
215
250
  else if (flag === 'exclude') excludes.push(argv[++i]);
216
251
  else flags[flag] = argv[++i];
@@ -220,8 +255,8 @@ if (cmd === '--version') {
220
255
  console.log(JSON.parse(readFileSync(new URL(import.meta.url.endsWith('.ts') ? '../cli/package.json' : 'package.json', import.meta.url), 'utf8')).version);
221
256
  process.exit();
222
257
  }
223
- if (!cmd || cmd === 'help') {
224
- console.log(!cmd ? USAGE : args[0] ? usage(args[0]) : GUIDE);
258
+ if ((!cmd || cmd === 'help') && !existsSync(config)) {
259
+ console.log(!cmd ? usage() : args[0] ? usage(args[0]) : GUIDE);
225
260
  process.exit();
226
261
  }
227
262
  if (cmd !== 'login' && !existsSync(config)) throw new Error('sign in first: rf login URL');
@@ -235,8 +270,19 @@ async function api(path , init = {}) {
235
270
  const get = async (path ) => (await api(path)).json();
236
271
  const post = (path , body , method = 'POST') => api(path, { method, body: JSON.stringify(body) });
237
272
 
273
+ if (!cmd || cmd === 'help') {
274
+ const me = await get('/me'), vpn = me.can.includes('vpn'), admin = me.role === 'admin';
275
+ const guide = GUIDE + (vpn ? `\n\nClient VPNs
276
+ ${usage('vpns', vpn, admin)}
277
+ ${admin ? `${usage('vpn', vpn, admin)}\n` : ''}rf site set NAME --via VPN uses your connection to that client VPN for this website; --via '' clears it.
278
+ Sign in to a VPN on the page. VPN access needs an explicit grant, even for admins.` : '');
279
+ console.log(!cmd || args[0] ? usage(args[0], vpn, admin) : guide);
280
+ process.exit();
281
+ }
282
+
238
283
  async function find(path ) {
239
- const [w, s, l] = path.split('/'), series = (await get('/api')).find(x => x.name === w)?.series.find(x => x.name === s);
284
+ const [w, s, l, more] = path.replace(/\/+$/, '').split('/');
285
+ const series = s !== undefined && more === undefined ? (await get('/api')).find(x => x.name === w)?.series.find(x => x.name === s) : undefined;
240
286
  const inst = l === undefined ? undefined : series?.instances.find(i => i.label === l);
241
287
  if (!series || (l !== undefined && !inst)) throw new Error(`nothing you can see at ${path}`);
242
288
  return { series, inst, at: inst ? `/api/instances/${inst.id}` : '' };
@@ -264,9 +310,15 @@ const consent = (offers ) => offers.length ? `, ticking ${offers.join('
264
310
 
265
311
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
266
312
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
313
+ const grantText = (g ) => `${g.description}${g.flags.length ? ` Flags: ${g.flags.join('; ')}.` : ''}${g.adminOnly ? ` ${g.adminWhy}.` : ''}`;
267
314
  const took = (s ) => s < 60 ? `${Math.round(s)}s` : s < 3600 ? `${Math.round(s / 60)}m` : `${Math.floor(s / 3600)}h${String(Math.round((s % 3600) / 60)).padStart(2, '0')}`;
268
- const usd = (n ) => `$${n.toFixed(2)}`;
269
- const runsIn = async (path = '') => (await get(`/api/runs?since=${encodeURIComponent(String(flags.since ?? ''))}`))
315
+ const usd = (n , est ) => `${est ? '~' : ''}${n < 0 ? '-$' + (-n).toFixed(2) : '$' + n.toFixed(2)}`;
316
+ const usdNote = (n , est ) => `${usd(n, est)}${est ? ' (est.)' : ''}`;
317
+ const signedUsd = (n ) => `${n >= 0 ? '+$' : '-$'}${Math.abs(n).toFixed(2)}`;
318
+ const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? '';
319
+ // --since DATE from its midnight on this machine's clock, as --by day groups by.
320
+ const since = encodeURIComponent(/^\d{4}-\d{2}-\d{2}$/.test(String(flags.since)) ? new Date(`${flags.since}T00:00`).toISOString() : String(flags.since ?? ''));
321
+ const runsIn = async (path = '') => (await get(`/api/runs?since=${since}`))
270
322
  .filter(r => !path || r.path === path.replace(/\/+$/, '') || r.path.startsWith(path.replace(/\/+$/, '') + '/'));
271
323
 
272
324
  function write(path , data , mtime ) {
@@ -279,11 +331,21 @@ function write(path , data , mtime ) {
279
331
 
280
332
  // A path the server named, under `base`, or undefined where a name in it can't be one here: on Windows a name may hold \ or :, which
281
333
  // would put the file elsewhere, even in another workspace's folder, or another file's stream; or name a device, such as CON; or end
282
- // in a dot or a space, which Windows drops.
334
+ // in a dot or a space, which Windows drops. Nor may a name be what git takes for a .git, such as .GIT on a disk that ignores case,
335
+ // whose config would run a command as git runs there. A link where one of its folders goes, or `base`, would take the file
336
+ // elsewhere too, and is refused.
283
337
  const under = (base , rel ) => {
284
338
  const names = rel.split('/');
285
- if (names.some(n => !n || n === '.' || n === '..' || basename(n) !== n
339
+ if (names.some(n => !n || n === '.' || n === '..' || basename(n) !== n || /^(\.git|git~1)[. ]*([:\\]|$)/i.test(n)
286
340
  || (process.platform === 'win32' && (/[<>:"|?*\x00-\x1f]|[. ]$/.test(n) || /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(n))))) return undefined;
341
+ let folder = base;
342
+ for (const name of ['', ...names.slice(0, -1)]) {
343
+ folder = join(folder, name);
344
+ let st ;
345
+ try { st = lstatSync(folder, { throwIfNoEntry: false }); }
346
+ catch (e) { if ((e ).code === 'ENOTDIR') break; throw e; }
347
+ if (st?.isSymbolicLink()) throw new Error(`${folder} is a symlink: remove it or pull into another directory`);
348
+ }
287
349
  return join(base, ...names);
288
350
  };
289
351
 
@@ -293,7 +355,8 @@ const globs = excludes.map(p => [p.replace(/^\/|\/$/g, '').includes('/'), new Re
293
355
  const excluded = (rel ) => globs.some(([whole, re]) => rel.split('/').some((name, k, all) => re.test(whole ? all.slice(0, k + 1).join('/') : name)));
294
356
 
295
357
  // Copies PATH's files into DIR as rsync does, from the server only and whole: a file whose size or time differ from the server's is
296
- // fetched, and given the server's time, so the next pull compares against it. Nothing is kept besides the files.
358
+ // fetched, and given the server's time, so the next pull compares against it. Nothing is kept besides the files. DIR may be a link, as the
359
+ // person who names it chose; no folder in it may.
297
360
  async function pull(path , dir ) {
298
361
  const at = path.replace(/^\/+/, ''), from = at.replace(/\/+$/, ''), dry = !!flags['dry-run'];
299
362
  const size = /^(\d+)([KMG]?)$/i.exec(String(flags['max-size'] ?? '0'));
@@ -301,17 +364,33 @@ async function pull(path , dir ) {
301
364
  const max = flags['max-size'] === undefined ? Infinity : Number(size[1]) * 1024 ** ' KMG'.indexOf(size[2].toUpperCase() || ' ');
302
365
  const list = await get(`/api/files?path=${encodeURIComponent(from)}`);
303
366
  if (!list.length) throw new Error(`nothing you can see at ${path}`);
304
- 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);
367
+ const to = existsSync(dir) ? realpathSync(dir) : resolve(dir);
368
+ const into = !from || at.endsWith('/') ? to : under(to, from.slice(from.lastIndexOf('/') + 1)), rel = (f ) => f.path.slice(from ? from.length + 1 : 0);
305
369
  if (!into) throw new Error(`${from} can't be a name here: pull ${from}/ into a folder of your choosing`);
306
370
  let fetched = 0, same = 0, deleted = 0, failed = 0, big = 0;
307
- const fetches = [];
371
+ const fold = (r ) => ['win32', 'darwin'].includes(process.platform) ? r.toLowerCase() : r;
372
+ const fetches = [], cased = new Map (), keep = new Set ();
308
373
  for (const f of list.filter(f => !excluded(rel(f)))) {
309
- const local = rel(f) ? under(into, rel(f)) : into, st = local && existsSync(local) ? statSync(local) : undefined;
374
+ const local = rel(f) ? under(into, rel(f)) : into;
375
+ let st ;
376
+ try { st = local ? statSync(local, { throwIfNoEntry: false }) : undefined; }
377
+ catch (e) { if ((e ).code !== 'ENOTDIR') throw e; }
310
378
  if (!local) {
311
379
  console.error(`skipped ${f.path}: it can't be a file's name here`);
312
380
  continue;
313
381
  }
314
- if (st && st.size === f.size && Math.floor(st.mtimeMs / 1000) === Math.floor(Date.parse(f.mtime) / 1000)) {
382
+ // Windows' and macOS's disks take two names that differ only in case for one file or folder: the second is skipped.
383
+ if (['win32', 'darwin'].includes(process.platform)) {
384
+ const parts = f.path.split('/'), prefixes = parts.map((_, k) => parts.slice(0, k + 1).join('/'));
385
+ const hit = prefixes.map(p => cased.get(p.toLowerCase())).find((v, k) => v && (v !== prefixes[k] || k === prefixes.length - 1));
386
+ if (hit) {
387
+ console.error(`skipped ${f.path}: this disk takes it for ${hit}, which differs only in case`);
388
+ continue;
389
+ }
390
+ for (const p of prefixes) cased.set(p.toLowerCase(), p);
391
+ }
392
+ keep.add(fold(rel(f)));
393
+ if (st?.isFile() && st.size === f.size && Math.floor(st.mtimeMs / 1000) === Math.floor(Date.parse(f.mtime) / 1000)) {
315
394
  same++;
316
395
  continue;
317
396
  }
@@ -321,7 +400,7 @@ async function pull(path , dir ) {
321
400
  continue;
322
401
  }
323
402
  fetches.push(async () => {
324
- console.log(`${st ? 'changed' : 'new'} ${f.path}`);
403
+ console.log(`${st?.isFile() ? 'changed' : 'new'} ${f.path}`);
325
404
  try {
326
405
  if (!dry) write(local, f.text ?? new Uint8Array(await (await api(f.url )).arrayBuffer()), f.mtime);
327
406
  fetched++;
@@ -331,22 +410,40 @@ async function pull(path , dir ) {
331
410
  }
332
411
  });
333
412
  }
334
- // Up to 8 files are fetched at once, each started in the list's order.
335
- await Promise.all(Array.from({ length: 8 }, async () => {
336
- for (let next; (next = fetches.shift());) await next();
337
- }));
338
- if (flags.delete && list.some(rel) && existsSync(into)) {
339
- 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)]);
413
+ if (flags.delete && list.some(f => rel(f) && !excluded(rel(f))) && existsSync(into) && !lstatSync(into).isDirectory()) {
414
+ console.log(`deleted ${basename(into)}`);
415
+ deleted++;
416
+ if (!dry) rmSync(into);
417
+ }
418
+ if (flags.delete && existsSync(into) && lstatSync(into).isDirectory()) {
419
+ // Windows' and macOS's disks ignore case, as the fetches above did: a file renamed only in case is kept, as fetched.
420
+ const mine = (d ) => readdirSync(d, { withFileTypes: true }).flatMap(e => {
421
+ const full = join(d, e.name), r = relative(into, full).split(sep).join('/');
422
+ return excluded(r) ? [] : e.isDirectory() ? mine(full) : [full];
423
+ });
340
424
  for (const p of mine(into)) {
341
425
  const r = relative(into, p).split(sep).join('/');
342
- if (keep.has(r) || excluded(r)) continue;
426
+ if (keep.has(fold(r))) continue;
343
427
  console.log(`deleted ${r}`);
344
428
  deleted++;
345
429
  if (!dry) rmSync(p, { force: true });
346
430
  }
347
- 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); };
348
- if (!dry) prune(into);
431
+ const prune = (d ) => {
432
+ for (const e of readdirSync(d, { withFileTypes: true })) {
433
+ const full = join(d, e.name), r = relative(into, full).split(sep).join('/');
434
+ if (e.isDirectory() && !excluded(r)) prune(full);
435
+ }
436
+ if (d !== into && !excluded(relative(into, d).split(sep).join('/')) && !readdirSync(d).length) rmdirSync(d);
437
+ };
438
+ if (!dry) {
439
+ prune(into);
440
+ if (list.some(f => !rel(f) && !excluded('')) && !readdirSync(into).length) rmdirSync(into);
441
+ }
349
442
  }
443
+ // Up to 8 files are fetched at once, each started in the list's order.
444
+ await Promise.all(Array.from({ length: 8 }, async () => {
445
+ for (let next; (next = fetches.shift());) await next();
446
+ }));
350
447
  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}`);
351
448
  if (failed) process.exitCode = 1;
352
449
  }
@@ -372,41 +469,43 @@ if (cmd === 'login' && url) {
372
469
  writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
373
470
  console.log(`signed in as ${me.email}`);
374
471
  } else if (cmd === 'ls' && !args.length) {
375
- const rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
376
- { path: `${w.name}/${s.name}`, id: s.id, requests: s.requests.length, wakes: s.wakes },
377
- ...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 })),
472
+ // --mine: the open instances you run, alone.
473
+ const me = flags.mine && await get('/me'), rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
474
+ ...me ? [] : [{ path: `${w.name}/${s.name}`, id: s.id, requests: s.requests.length, wakes: s.wakes }],
475
+ ...s.instances.filter(i => !me || (i.status === 'open' && i.runner === me.email)).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, ...(i.deleted && { deleted: i.deleted }) })),
378
476
  ]));
379
477
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
380
478
  else for (const r of rows) {
381
- 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` : ''}`);
382
- 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(', ')}` : ''}`);
479
+ console.log(r.deleted ? `${r.path} deleted by ${r.deleted.by} ${when(r.deleted.at)}` : 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` : ''}`);
480
+ 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(', ')}` : ''}${k.text ? `: ${k.text}` : ''}`);
383
481
  }
384
482
  } else if (cmd === 'waiting' && !args.length) {
385
483
  const [me, s, all] = await Promise.all([get('/me'), get('/api/status'), get('/api')]), mine = (who ) => (who ?? me.email) === me.email;
386
484
  const series = all.flatMap(w => w.series.map(x => ({ ...x, path: `${w.name}/${x.name}` })));
387
485
  const rows = [
388
486
  ...s.asks.filter(a => a.who === me.email).map(a => ({ kind: a.note ? 'note' : 'ask', path: a.path, since: a.since, text: a.text })),
389
- ...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}` }))),
487
+ ...s.assigned.filter(a => a.who === me.email).map(a => ({ kind: 'assigned', path: a.path, since: a.at, text: `${a.by} assigned you ${a.path}` })),
488
+ ...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 ${r.target ? 'wake' : 'start'} ${r.label}${r.text ? `: ${r.text}` : ''}` }))),
390
489
  ...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`}` })),
391
490
  ...s.expired.filter(e => e.who === me.email).map(e => ({ kind: 'expired', login: e.login, holding: e.holding, text: `your ${e.login} login expired` })),
392
- ...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(', ')}` })))),
393
- ...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'})` }))),
491
+ ...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, person: r.login, why: r.why, text: `run ${r.run}'s browser on ${r.login}'s ${r.site} was refused ${r.hosts.map((h ) => r.why[h] ? `${h} (${r.why[h]})` : h).join(', ')}` })))),
492
+ ...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: grantText(g) }))),
394
493
  ];
395
494
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
396
- 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.');
495
+ 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.kind === 'grant' ? r.text : r.text.split('\n')[0].slice(0, 120)}`).join('\n') || 'Nothing waits on you.');
397
496
  } else if (cmd === 'show' && args.length === 1) {
398
497
  const { inst, at } = await instanceAt(args[0]), { doc, log, run, queued, runner, waiting: w } = await get(at);
399
498
  const waiting = w.map(({ who, seq }) => {
400
499
  const e = log[seq - 1], first = log.find(x => `c${x.seq}` === e.thread);
401
- 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 };
500
+ return { comment: `c${seq}`, thread: e.thread, kind: e.ask === true ? 'ask' : e.ask ?? 'note', for: who, by: e.by, item: first.item, ref: first.ref, text: e.text };
402
501
  });
403
- const done = log.findLast(e => e.op === 'done'), last = done ? { run: done.run, cost: done.cost, error: done.error ?? null } : null;
404
- 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));
502
+ const done = log.findLast(e => e.op === 'done'), last = done ? { run: done.run, cost: done.cost, ...(done.estimated && { estimated: true }), error: done.error ?? null } : null;
503
+ 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, ...(doc.status === 'deleted' && { deleted: { by: log[0].by, at: log[0].at } }) }, null, 1));
405
504
  else {
406
- console.log(`${args[0]} ${doc.status}, runner ${runner.by}${run ? `, run ${run.n} going, ${usd(run.cost)}` : queued ? ', queued' : ''}`);
505
+ console.log(doc.status === 'deleted' ? `${args[0]} deleted by ${log[0].by} ${when(log[0].at)}` : `${args[0]} ${doc.status}, runner ${runner.by}${run ? `, run ${run.n} going, ${usdNote(run.cost, run.estimated)}` : queued ? ', queued' : ''}`);
407
506
  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}` : ''}`);
408
507
  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)}`);
409
- if (last) console.log(`last run ${last.run} ${usd(last.cost ?? 0)}${last.error ? ` ${last.error}` : ''}`);
508
+ if (last) console.log(`last run ${last.run} ${usdNote(last.cost ?? 0, last.estimated)}${last.error ? ` ${last.error}` : ''}`);
410
509
  }
411
510
  } else if (cmd === 'log' && args.length === 1) {
412
511
  const { at } = await instanceAt(args[0]);
@@ -426,35 +525,59 @@ if (cmd === 'login' && url) {
426
525
  } else if (cmd === 'pull' && args.length === 2) await pull(args[0], args[1]);
427
526
  else if (cmd === 'comment' && args.length === 2) {
428
527
  const { at } = await instanceAt(args[0]);
429
- await post(`${at}/comment`, { text: args[1], item: flags.item, ref: flags.ref, thread: flags.thread, quiet: !flags.wake && !flags.wait });
430
- const { log, runner } = await get(at), { seq, note } = log.at(-1);
431
- if (note) console.log(`a note for the runner, ${runner.by}, seq ${seq}: it starts no run until they act`);
432
- else if (!flags.wait) console.log(`commented, seq ${seq}`);
528
+ const posted = await post(`${at}/comment`, { text: args[1], item: flags.item, ref: flags.ref, thread: flags.thread, quiet: !flags.wake && !flags.wait });
529
+ const seq = Number(posted.headers.get('X-RF-Comment-Seq')), { doc, log, runner, starts } = await get(at), note = log.find(e => e.seq === seq)?.note;
530
+ if (note && !starts) console.log(`a note for the runner, ${runner.by}, seq ${seq}: it starts no run until they act`);
531
+ else if (!flags.wait) console.log(`${note ? `a note for the runner, ${runner.by}` : 'commented'}, seq ${seq}`);
532
+ else if (doc.status !== 'open') console.log(`The instance was ${doc.status}.`);
433
533
  else for (;;) {
434
534
  // The run that saw the comment, and what it said from then on: a run ending as it came may not have.
435
535
  await new Promise(r => setTimeout(r, 5000));
436
- const log = (await get(at)).log, done = log.find(e => e.op === 'done' && e.seen >= seq);
437
- if (!done) continue;
438
- const from = Math.max(seq, log.find(e => e.op === 'run' && e.run === done.run).seq);
439
- 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`);
440
- if (done.error) console.log(`The run failed: ${done.error}`);
441
- break;
536
+ const { doc, log } = await get(at);
537
+ const done = log.find(e => e.op === 'done' && (e.seen >= seq || (e.seq > seq && (e.error || e.aborted) && !log.some(w => w.seq > e.seq && ((w.op === 'wake' && w.cause === e.seq) || w.op === 'run')))));
538
+ if (done) {
539
+ const from = Math.max(seq, log.find(e => e.op === 'run' && e.run === done.run)?.seq ?? 0);
540
+ for (const e of log.filter(e => e.seq > from && e.seq < done.seq && e.op === 'comment' && e.by === 'agent' && !e.see)) console.log(`${e.ask === 'proposal' ? 'Proposes' : e.ask ? 'Asks' : 'Says'} in ${e.thread}:\n${e.text}\n`);
541
+ if (done.error) console.log(`The run failed: ${done.error}`);
542
+ else if (done.aborted && done.seen < seq) console.log('The run was stopped.');
543
+ break;
544
+ }
545
+ if (doc.status !== 'open') {
546
+ console.log(`The instance was ${doc.status}.`);
547
+ break;
548
+ }
442
549
  }
443
550
  } else if (cmd === 'react' && [2, 3].includes(args.length) && ['up', 'down', 'none'].includes(args.at(-1) )) {
444
551
  const on = args.length === 3 ? Number(args[1].replace(/^c/, '')) : undefined, up = { up: true, down: false, none: null }[args.at(-1) ];
445
552
  await post(`${(await instanceAt(args[0])).at}/react`, { ...(on !== undefined && { on }), up });
446
553
  console.log(`${args.at(-1)} on ${args.length === 3 ? args[1] : args[0]}`);
447
- } else if (cmd === 'signoff' && [2, 3].includes(args.length)) {
448
- await post(`${(await instanceAt(args[0])).at}/signoff`, { thread: args[1], text: args[2], quiet: !flags.wake });
449
- console.log(`signed off ${args[1]}`);
554
+ } else if (['approve', 'reject'].includes(cmd) && [2, 3].includes(args.length)) {
555
+ await post(`${(await instanceAt(args[0])).at}/${cmd === 'approve' ? 'signoff' : 'reject'}`, { thread: args[1], text: args[2], quiet: !flags.wake });
556
+ console.log(`${cmd === 'approve' ? 'approved' : 'rejected'} ${args[1]}`);
450
557
  } else if (['close', 'abandon', 'interrupt'].includes(cmd) && args.length === 1) {
451
558
  const { series, at } = await instanceAt(args[0]);
452
- if (cmd === 'close' && typeof flags['as-series'] === 'string') await post(`/api/series/${series.id}/promote`, { name: flags['as-series'] });
453
559
  await post(`${at}/${cmd}`, { quiet: !flags.wake });
560
+ if (cmd === 'close' && typeof flags['as-series'] === 'string') await post(`/api/series/${series.id}/promote`, { name: flags['as-series'] });
454
561
  console.log(`${cmd === 'close' ? 'closed' : `${cmd}ed`} ${args[0]}`);
562
+ } else if (cmd === 'delete' && args.length === 1) {
563
+ // One confirm, which says it can't be undone and what stays outside the server.
564
+ const { at } = await instanceAt(args[0]);
565
+ if (!flags.yes) {
566
+ const warning = `Deleting ${args[0]} can't be undone. A run for it is cut, and everything the server holds of it goes: its uploads, the agent's files, its items, threads and log, its runs' transcripts and browser logs, and its history; its label stays in its place, shown as deleted by you. Copies outside the server stay: instances copied from it, files other runs copied, rf pull copies, mail sent.`;
567
+ if (!process.stdin.isTTY) throw new Error(`${warning} Confirm with --yes`);
568
+ const { createInterface } = await import('node:readline/promises'), rl = createInterface({ input: process.stdin, output: process.stdout });
569
+ const answer = await rl.question(`${warning}\nType delete to delete it: `);
570
+ rl.close();
571
+ if (answer.trim() !== 'delete') throw new Error(`kept ${args[0]}`);
572
+ }
573
+ await post(`${at}/delete`, {});
574
+ console.log(`deleted ${args[0]}`);
455
575
  } else if (cmd === 'takeover' && args.length === 1) {
456
- await post(`${(await instanceAt(args[0])).at}/takeover`, { logins: ticks() });
576
+ await post(`${(await instanceAt(args[0])).at}/assign`, { logins: ticks() });
457
577
  console.log(`you run ${args[0]} now${consent(ticks())}`);
578
+ } else if (cmd === 'assign' && args.length === 2) {
579
+ await post(`${(await instanceAt(args[0])).at}/assign`, { to: args[1] });
580
+ console.log(`${args[1]} runs ${args[0]} now, with no logins ticked until they tick theirs`);
458
581
  } else if (cmd === 'creds' && args.length === 1) {
459
582
  const { at } = await instanceAt(args[0]);
460
583
  if (flags.set !== undefined || flags.clear) {
@@ -473,8 +596,16 @@ else if (cmd === 'comment' && args.length === 2) {
473
596
  else await post(`/api/workspaces/${(await workspaceNamed(w)).id}`, { name: args[1] }, 'PUT');
474
597
  console.log(`renamed ${args[0]} ${args[1]}`);
475
598
  } else if (cmd === 'new' && args[0] === 'task' && [2, 3].includes(args.length)) {
476
- const { instance } = await (await post('/api/series', { workspace: (await workspaceNamed(args[1])).id, single: true, logins: ticks() })).json();
477
- if (args[2]) await post(`/api/instances/${instance}/rename?as=${encodeURIComponent(args[2])}`, {});
599
+ const workspace = await workspaceNamed(args[1]), clean = args.length === 3 ? args[2].replace(/[/\\\x00-\x1f\x7f\x85\u2028\u2029]/g, '_') : '';
600
+ if (args.length === 3) {
601
+ if (!clean) throw new Error('a name is needed');
602
+ if (clean.startsWith('.')) throw new Error(`a name can't start with a dot: ${args[2]}`);
603
+ if (clean === 'AGENTS.md') throw new Error("AGENTS.md is the name of the agents' instructions: choose another");
604
+ if (Buffer.byteLength(clean) > 200) throw new Error(`a name is 200 bytes at most, about 66 Chinese characters, not ${Buffer.byteLength(clean)}`);
605
+ if (workspace.series.some((s ) => s.name === clean)) throw new Error(`${clean} exists`);
606
+ }
607
+ const { instance } = await (await post('/api/series', { workspace: workspace.id, single: true, logins: ticks() })).json();
608
+ if (clean && (await pathOf(instance)).split('/').at(-1) !== clean) await post(`/api/instances/${instance}/rename?as=${encodeURIComponent(args[2])}`, {});
478
609
  if (typeof flags.comment === 'string') await post(`/api/instances/${instance}/comment`, { text: flags.comment, quiet: !flags.wake });
479
610
  console.log(`made ${await pathOf(instance)}${consent(ticks())}`);
480
611
  } else if (cmd === 'new' && args[0] === 'instance' && args.length === 3) {
@@ -486,52 +617,74 @@ else if (cmd === 'comment' && args.length === 2) {
486
617
  } else if (cmd === 'new' && args[0] === 'workspace' && args.length === 2) {
487
618
  await post('/api/workspaces', { name: args[1] });
488
619
  console.log(`made ${args[1]}`);
489
- } else if (cmd === 'copy' && args.length === 2) {
490
- const { id } = await (await post(`${(await instanceAt(args[0])).at}/duplicate?as=${encodeURIComponent(args[1])}`, { logins: ticks() })).json();
491
- console.log(`made ${await pathOf(id)}${consent(ticks())}`);
492
620
  } else if (cmd === 'share' && ['on', 'off'].includes(args[1]) && args.length === 2) {
493
621
  await post(`/api/series/${(await seriesAt(args[0])).id}`, { share: args[1] === 'on', logins: ticks() }, 'PUT');
494
622
  console.log(args[1] === 'on' ? `shared ${args[0]}${consent(ticks())}` : `stopped sharing ${args[0]}`);
495
623
  } else if (cmd === 'archive' && args.length === 1) {
496
624
  const [w, s] = args[0].replace(/\/+$/, '').split('/');
497
625
  await post(s === undefined ? `/api/workspaces/${(await workspaceNamed(w)).id}` : `/api/series/${(await seriesAt(args[0])).id}`, { archived: !flags.undo }, 'PUT');
498
- console.log(`${flags.undo ? 'brought back' : 'archived'} ${args[0]}`);
626
+ console.log(flags.undo ? `brought back ${args[0]}` : `archived ${args[0]}, its wakes and requests cancelled for good`);
499
627
  } else if (cmd === 'request' && ['start', 'drop'].includes(args[0]) && args.length === 2) {
500
- if (args[0] === 'drop') await api(`/api/requests/${args[1]}`, { method: 'DELETE' });
501
- 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())}`);
628
+ if (args[0] === 'drop') {
629
+ await api(`/api/requests/${args[1]}`, { method: 'DELETE' });
630
+ console.log(`dropped request ${args[1]}`);
631
+ } else {
632
+ const setCreds = flags.creds !== undefined || !!flags.clear;
633
+ const r = await post(`/api/requests/${args[1]}`, { ...(setCreds && { logins: ticks() }), quiet: !flags.wake });
634
+ const woke = r.headers.get('X-RF-Woke') === '1', { id } = await r.json();
635
+ console.log(`${woke ? 'woke' : 'made'} ${await pathOf(id)}${!woke || setCreds ? consent(ticks()) : ''}`);
636
+ }
502
637
  } else if (cmd === 'logins' && !args.length) {
503
638
  const all = await get('/logins');
504
639
  if (flags.json) console.log(JSON.stringify(all, null, 1));
505
640
  else for (const l of all) {
506
- 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(', ')}` : ''}`);
641
+ console.log(`${l.id} ${l.name} ${l.expired ? `expired: sign in again at ${url}/#logins` : `${l.kind === 'key' ? 'saved' : l.kind === 'service' ? 'connected' : '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(', ')}` : ''}`);
507
642
  // A website's login offers itself alone.
508
643
  for (const o of l.offers.filter(o => o.id !== l.id)) console.log(` offers ${o.id} ${o.name}`);
509
644
  }
510
- } else if (cmd === 'logins' && ['offer', 'unoffer', 'allow'].includes(args[0]) && args.length === 3) {
645
+ } else if (cmd === 'logins' && ['offer', 'unoffer', 'allow', 'disallow'].includes(args[0]) && args.length === 3) {
511
646
  const [what, login, x] = args, at = `/logins/${encodeURIComponent(login)}`;
512
647
  if (what === 'offer') await post(`${at}/offers`, { add: x });
513
648
  else if (what === 'unoffer') await api(`${at}/offers/${encodeURIComponent(x)}`, { method: 'DELETE' });
514
- else await post(`/logins/web/${encodeURIComponent(login)}/hosts`, { host: x });
515
- console.log(`${login} ${{ offer: 'offers', unoffer: 'no longer offers', allow: 'reaches' }[what]} ${x}`);
649
+ else if (what === 'disallow') await api(`/logins/web/${encodeURIComponent(login)}/hosts/${encodeURIComponent(x)}`, { method: 'DELETE' });
650
+ else await post(`/logins/web/${encodeURIComponent(login)}/hosts${flags.person ? `?person=${encodeURIComponent(String(flags.person))}` : ''}`, { host: x });
651
+ console.log(`${login} ${{ offer: 'offers', unoffer: 'no longer offers', allow: 'reaches', disallow: 'no longer reaches' }[what]} ${x}`);
652
+ } else if (cmd === 'vpns' && !args.length) {
653
+ const all = await get('/vpns');
654
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
655
+ else for (const v of all) console.log(`${v.name} ${v.type} ${v.gateway} ${v.connected ? `connected${v.since ? ` since ${when(v.since)}` : ''}` : 'disconnected'}${v.error ? `: ${v.error}` : ''}`);
656
+ } else if (cmd === 'vpn' && args[0] === 'add' && args.length === 4) {
657
+ await post('/vpns', { name: args[1], type: args[2], gateway: args[3], servercert: flags.servercert });
658
+ console.log(`added ${args[1]}`);
659
+ } else if (cmd === 'vpn' && args[0] === 'remove' && args.length === 2) {
660
+ await api(`/vpns/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
661
+ console.log(`removed ${args[1]}`);
662
+ } else if (cmd === 'sites' && !args.length) {
663
+ const [all, me] = await Promise.all([get('/logins/sites'), get('/me')]);
664
+ if (!me.can.includes('vpn')) for (const w of Object.values (all)) delete w.via;
665
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
666
+ else for (const [name, w] of Object.entries (all)) console.log(`${name} ${w.url}${w.via ? ` via ${w.via}` : ''}${w.hosts.map((h ) => `\n reaches ${h}${w.checks?.[h]?.verdict === 'pass' ? `: ${w.checks[h].why}` : ''}`).join('')}`);
516
667
  } else if (cmd === 'site' && args[0] === 'add' && args.length === 3) {
517
- const { site, existing } = await (await post('/logins/sites', { name: args[1], url: args[2] })).json();
518
- console.log(`${existing ? `${args[2]} is ${site}'s` : `added ${site}`}: sign in to it at ${url}/#logins, then rf site ask ${site} WORKSPACE REASON`);
668
+ const { site } = await (await post('/logins/sites', { name: args[1], url: args[2], header: flags.header })).json();
669
+ console.log(`added ${site}: sign in to it at ${url}/#logins, then rf site ask ${site} WORKSPACE REASON`);
519
670
  } else if (cmd === 'site' && args[0] === 'set' && args.length === 2) {
520
- await post(`/logins/sites/${encodeURIComponent(args[1])}`, flags, 'PATCH');
671
+ await post(`/logins/sites/${encodeURIComponent(args[1])}${flags.person ? `?person=${encodeURIComponent(String(flags.person))}` : ''}`, { ...flags, person: undefined }, 'PATCH');
521
672
  console.log('saved');
522
673
  } else if (cmd === 'site' && args[0] === 'remove' && args.length === 2) {
523
674
  await api(`/logins/sites/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
524
675
  console.log(`removed ${args[1]}`);
525
676
  } else if (cmd === 'site' && args[0] === 'ask' && args.length === 4) {
526
- const { id, check: c } = await (await post('/grants', { site: args[1], workspace: (await workspaceNamed(args[2])).id, reason: args[3] })).json();
527
- 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}`
528
- : `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(', ')}.` : ''}`}`);
677
+ const { id, said } = await (await post('/grants', { site: args[1], workspace: (await workspaceNamed(args[2])).id, reason: args[3] })).json();
678
+ console.log(`${said} Grant ${id}: ${grantText((await get('/grants')).find(g => g.id === id))}`);
529
679
  } else if (cmd === 'grants' && args.length <= 1) {
530
680
  const [all, ws] = await Promise.all([get('/grants'), get('/api')]), name = (id ) => ws.find(w => w.id === id)?.name ?? id;
531
681
  const shown = all.filter(g => !args[0] || name(g.workspace) === args[0]);
532
682
  if (flags.json) console.log(JSON.stringify(shown.map(g => ({ ...g, workspace: name(g.workspace) })), null, 1));
533
- 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'})`);
683
+ else for (const g of shown) console.log(`${g.id} ${g.state} since ${when(g.at)}: ${grantText(g)}${g.by ? `; ${g.state} by ${g.by}${g.text ? `: ${g.text}` : ''}` : ''}${g.use ? ` Used by ${g.use.runs} runs, ${g.use.wrote} wrote; last use ${g.use.last ? when(g.use.last) : 'never'}.` : ''}`);
534
684
  } else if (cmd === 'grant' && ['approve', 'deny'].includes(args[0]) && [2, 3].includes(args.length)) {
685
+ const g = (await get('/grants')).find(g => g.id === args[1]);
686
+ if (!g) throw new Error(`no request ${args[1]} waits`);
687
+ console.log(grantText(g));
535
688
  await post(`/grants/${args[1]}`, { approve: args[0] === 'approve', text: args[2] });
536
689
  console.log(args[0] === 'approve' ? 'approved' : 'denied');
537
690
  } else if (cmd === 'grant' && args[0] === 'revoke' && args.length === 2) {
@@ -551,11 +704,19 @@ else if (cmd === 'comment' && args.length === 2) {
551
704
  } else if (cmd === 'wake' && typeof flags.cancel === 'string' && !args.length) {
552
705
  await api(`/api/wakes/${flags.cancel}`, { method: 'DELETE' });
553
706
  console.log('cancelled');
554
- } else if (cmd === 'wake' && args.length === 2) {
707
+ } else if (cmd === 'wake' && [2, 3].includes(args.length)) {
555
708
  const { series, inst } = await find(args[0]);
556
709
  const at = args[1] === 'now' ? Date.now() : args[1].startsWith('+') ? Date.now() + Number(args[1].slice(1, -1)) * { m: 60e3, h: 3600e3, d: 86400e3 }[args[1].at(-1) ] : Date.parse(args[1]);
557
- const w = await (await post(`/api/wakes/${inst?.id ?? series.id}`, { at: new Date(at).toISOString(), label: flags.label, days: flags.days }, 'PUT')).json();
710
+ const w = await (await post(`/api/wakes/${inst?.id ?? series.id}`, { at: new Date(at).toISOString(), label: flags.label, days: flags.days, text: args[2] }, 'PUT')).json();
558
711
  console.log(`wake ${w.id} at ${w.at}${w.days ? `, then each ${w.days.join(', ')}` : ''}`);
712
+ } else if (cmd === 'note' && [1, 2].includes(args.length)) {
713
+ const at = `/api/series/${(await seriesAt(args[0])).id}/notes`;
714
+ if (args[1]) console.log(`noted ${(await (await post(at, { text: args[1] })).json()).id} on ${args[0]}: it starts no run, and its runs read it`);
715
+ else {
716
+ const all = await get(at);
717
+ if (flags.json) console.log(JSON.stringify(all, null, 1));
718
+ else for (const n of all) console.log(`n${n.seq} ${when(n.at)} ${n.by === 'agent' ? `agent of ${n.see.label}, for ${n.runner}` : n.by} ${n.settled ? `${n.settled.op === 'taken' ? 'taken' : 'set aside'} by ${n.settled.by === 'agent' ? 'agent' : n.settled.by}: ${n.settled.text}` : 'open'}\n ${n.text.split('\n')[0].slice(0, 200)}`);
719
+ }
559
720
  } else if (cmd === 'agents' && args.length <= 1) {
560
721
  const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
561
722
  if (typeof flags.set !== 'string') console.log(ws ? ws.agents : (await get('/agents')).text);
@@ -569,14 +730,17 @@ else if (cmd === 'comment' && args.length === 2) {
569
730
  if (flags.json) console.log(JSON.stringify({ readers: ws.readers, reads: ws.reads }, null, 1));
570
731
  else console.log([...ws.readers.map(r => `${r.name} reads ${ws.name}`), ...ws.reads.map(r => `${ws.name} reads ${r.name}`)].join('\n') || `${ws.name} reads no other workspace, and none reads it`);
571
732
  } else if (cmd === 'readers' && args.length === 3 && ['add', 'remove'].includes(args[1])) {
572
- // A workspace you don't see, whose agents' reading of one of yours you take off, is found among what yours read.
573
- const all = await get('/api'), [ws, other] = [args[0], args[2]].map(name => all.find(w => w.name === name) ?? all.flatMap(w => w.reads).find(r => r.name === name));
733
+ // A workspace you don't see, whose link with one of yours you take off, is found among what yours read or let read them.
734
+ const all = await get('/api'), linked = args[1] === 'remove' ? all.flatMap(w => [...w.reads, ...w.readers]) : [];
735
+ const [ws, other] = [args[0], args[2]].map(name => all.find(w => w.name === name) ?? linked.find(r => r.name === name));
574
736
  if (!ws || !other) throw new Error(`no workspace ${ws ? args[2] : args[0]}`);
575
737
  await post(`/api/workspaces/${ws.id}/readers/${other.id}`, {}, args[1] === 'add' ? 'PUT' : 'DELETE');
576
738
  console.log(args[1] === 'add' ? `${other.name}'s agents read ${ws.name} from their next run` : `${other.name}'s agents no longer read ${ws.name}`);
577
739
  } else if (cmd === 'skill' && args[0] === 'push' && args[1]) {
578
- const files = Object.fromEntries(readdirSync(args[1], { recursive: true, withFileTypes: true }).filter(d => d.isFile())
579
- .map(d => [relative(args[1], join(d.parentPath, d.name)).split(sep).join('/'), readFileSync(join(d.parentPath, d.name)).toString('base64')]));
740
+ const dotgit = (n ) => [n, ...Array.from(n.slice(1).matchAll(/\\/g), m => n.slice(m.index + 2))].some(t => /^(\.git|git~1)[. ]*([:\\]|$)/i.test(t));
741
+ const walk = (at ) => readdirSync(at, { withFileTypes: true }).filter(d => !dotgit(d.name))
742
+ .flatMap(d => d.isDirectory() ? walk(join(at, d.name)) : d.isFile() ? [join(at, d.name)] : []);
743
+ const files = Object.fromEntries(walk(args[1]).map(p => [relative(args[1], p).split(sep).join('/'), readFileSync(p).toString('base64')]).filter(([rel]) => rel !== '.pushed.json'));
580
744
  console.log(await (await post(`/skills/${encodeURIComponent(basename(resolve(args[1])))}/versions`, { files })).text());
581
745
  } else if (cmd === 'skill' && args[0] === 'pull' && args[1] && args.length <= 3) {
582
746
  const id = encodeURIComponent(args[1]), dir = resolve(args[2] ?? args[1]), n = flags.version ?? (await get(`/skills/${id}/versions`)).at(-1)?.version;
@@ -613,20 +777,22 @@ else if (cmd === 'comment' && args.length === 2) {
613
777
  const [s, ix] = await Promise.all([get('/api/status'), get('/api/indexes')]), long = Number(flags.long ?? 30);
614
778
  if (flags.json) console.log(JSON.stringify({ ...s, indexes: ix }, null, 1));
615
779
  else {
780
+ const lowLine = s.low_credit ? `Low OpenRouter credit: ${usd(s.low_credit.remaining)} remaining${s.low_credit.limit !== null ? ` of ${usd(s.low_credit.limit)} limit` : ''}${s.low_credit.reset ? ` (resets ${s.low_credit.reset})` : ''}` : '';
616
781
  const sections = [
617
- [`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` : ''}`)],
782
+ [`Running`, s.running.map(r => `${r.path} run ${r.run} for ${took((Date.now() - Date.parse(r.at)) / 1000)} ${usdNote(r.cost, r.estimated)}${Date.now() - Date.parse(r.at) > long * 60e3 ? ` LONG, past ${long}m` : ''}`)],
618
783
  [`Queued`, s.queued.map(q => `${q.path} since ${when(q.since)}: ${q.why}`)],
619
784
  [`Waiting`, [
620
- ...[...s.asks, ...s.requests.map(r => ({ ...r, who: r.who ?? 'anyone', since: r.at, text: `${r.from} asks to start ${r.label}`, request: true })),
785
+ ...[...s.asks, ...s.assigned.map(a => ({ ...a, since: a.at, text: `${a.by} assigned it to them`, assigned: true })), ...s.requests.map(r => ({ ...r, who: r.who ?? 'anyone', since: r.at, text: `${r.from} asks to ${r.target ? 'wake' : 'start'} ${r.label}`, request: true })),
621
786
  ...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 }))]
622
- .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)}`),
787
+ .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.assigned ? 'an assignment' : a.note ? 'a note' : 'an ask'} in ${a.path} since ${when(a.since)}: ${a.text.split('\n')[0].slice(0, 80)}`),
623
788
  ...s.expired.map(e => `${e.who} their ${e.login} login expired${e.holding.length ? `, holding ${e.holding.join(', ')}` : ''}`),
624
789
  ]],
625
790
  [`Last run failed`, s.failed.map(f => `${f.path} run ${f.run} at ${when(f.at)}: ${f.error}`)],
626
791
  [`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)
627
792
  .map(p => `${p.who} ${p.error ? `failing${p.retry_at ? `, again ${when(p.retry_at)}` : ''}: ${p.error.split('\n')[0].slice(0, 80)}` : `crawling, ${p.pages} pages`}`).join('; ')}`)],
628
793
  ].filter(([, rows]) => rows.length);
629
- console.log(sections.map(([title, rows]) => `${title} (${rows.length})\n${rows.map(r => ` ${r}`).join('\n')}`).join('\n\n') || 'Nothing is running, queued, waiting or failed.');
794
+ const body = sections.map(([title, rows]) => `${title} (${rows.length})\n${rows.map(r => ` ${r}`).join('\n')}`).join('\n\n');
795
+ console.log([lowLine, body].filter(Boolean).join('\n\n') || 'Nothing is running, queued, waiting or failed.');
630
796
  }
631
797
  } else if (cmd === 'indexes' && !args.length) {
632
798
  const ix = await get('/api/indexes');
@@ -636,22 +802,77 @@ else if (cmd === 'comment' && args.length === 2) {
636
802
  } else if (cmd === 'runs' && args.length <= 1) {
637
803
  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));
638
804
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
639
- 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 ?? ''}`);
805
+ 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)} ${usdNote(r.cost, r.estimated)} ${r.started ? `${r.started.op} by ${r.started.by}` : '-'} ${r.error ?? ''}`);
640
806
  } else if (cmd === 'costs' && args.length <= 1) {
641
- const by = String(flags.by ?? 'series'), key = {
642
- 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),
643
- outcome: r => r.failure ? `failed, ${r.failure}` : r.outcome,
644
- }[by];
645
- if (!key) throw new Error('--by: workspace, series, person, day or outcome');
807
+ const keyText = (k ) => `OpenRouter key (${k.day} UTC): ${k.usage_daily !== null ? `${usd(k.usage_daily)} today vs ${usdNote(k.server_total, k.server_estimated)} recorded (${signedUsd(k.unattributed)} unattributed) · ` : ''}${usd(k.usage)} used${k.limit !== null ? ` · ${usd(k.remaining)} of ${usd(k.limit)} remaining${k.reset ? ` (${k.reset})` : ''}` : ', no limit'}`;
646
808
  // A run that was cut is carried on by the next, so it adds its cost, not a run.
647
- const sums = new Map (), rows = await runsIn(args[0]), counted = (r ) => r.outcome === 'cut' ? 0 : 1;
648
- 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 });
649
- 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 }))
650
- .sort((a, b) => by === 'day' ? a.day.localeCompare(b.day) : b.cost - a.cost);
651
- if (flags.json) console.log(JSON.stringify(out, null, 1));
652
- else {
653
- 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]}`);
654
- 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`);
809
+ const at = (args[0] ?? '').replace(/\/+$/, ''), counted = (r ) => r.outcome === 'cut' ? 0 : 1;
810
+ const report = await get(`/api/costs?since=${since}&tz=${encodeURIComponent(localTz)}`);
811
+ if (flags.daily) {
812
+ const scoped = !at ? report : {
813
+ days: report.days.flatMap((d ) => {
814
+ const runs = at === 'server' ? [] : d.runs.filter((r ) => r.path === at || r.path.startsWith(at + '/'));
815
+ const server = at === 'server' && d.server?.items.length ? d.server : undefined;
816
+ if (!runs.length && !server) return [];
817
+ const by_workspace = Object.create(null);
818
+ const by_person = Object.create(null);
819
+ let runCost = 0, runs_count = 0, est = !!server?.estimated;
820
+ for (const r of runs) {
821
+ const c = counted(r);
822
+ runCost += r.cost; runs_count += c; est ||= !!r.estimated;
823
+ const w = by_workspace[r.workspace] ??= { runs: 0, cost: 0 };
824
+ w.runs += c; w.cost = +(w.cost + r.cost).toFixed(6); if (r.estimated) w.estimated = true;
825
+ const p = by_person[r.person] ??= { runs: 0, cost: 0 };
826
+ p.runs += c; p.cost = +(p.cost + r.cost).toFixed(6); if (r.estimated) p.estimated = true;
827
+ }
828
+ return [{ day: d.day, cost: +(runCost + (server?.cost ?? 0)).toFixed(6), runs_count, ...(est && { estimated: true }), by_workspace, by_person, runs, ...(server && { server }) }];
829
+ }),
830
+ };
831
+ if (flags.json) console.log(JSON.stringify(scoped, null, 1));
832
+ else {
833
+ if (scoped.key) console.log(keyText(scoped.key));
834
+ for (const d of scoped.days) {
835
+ console.log(`${d.day} ${usdNote(d.cost, d.estimated)} ${d.runs_count} runs${d.server?.cost ? ` server ${usdNote(d.server.cost, d.server.estimated)}` : ''}`);
836
+ for (const [w, v] of Object.entries (d.by_workspace)) console.log(` workspace ${usdNote(v.cost, v.estimated).padStart(10)} ${v.runs} runs ${w}`);
837
+ for (const [p, v] of Object.entries (d.by_person)) console.log(` person ${usdNote(v.cost, v.estimated).padStart(10)} ${v.runs} runs ${p}`);
838
+ for (const r of d.runs) console.log(` run ${usdNote(r.cost, r.estimated).padStart(10)} ${r.path} run ${r.run} ${r.person} ${r.outcome}`);
839
+ for (const s of d.server?.items ?? []) console.log(` server ${usdNote(s.cost, s.estimated).padStart(10)} ${s.kind}${s.site ? `: ${s.site}` : ''} (${s.person}) ${s.calls} calls`);
840
+ }
841
+ if (!scoped.days.length && !scoped.key) console.log('No costs recorded.');
842
+ }
843
+ } else {
844
+ const by = String(flags.by ?? 'series'), key = {
845
+ workspace: (r ) => r.workspace, series: (r ) => r.series, person: (r ) => r.person, day: (r ) => r.day,
846
+ outcome: (r ) => r.failure ? `failed, ${r.failure}` : r.outcome,
847
+ }[by];
848
+ if (!key) throw new Error('--by: workspace, series, person, day or outcome');
849
+ const sums = new Map ();
850
+ const add = (k , runs , cost , est ) => {
851
+ const prev = sums.get(k) ?? { runs: 0, cost: 0, estimated: false };
852
+ sums.set(k, { runs: prev.runs + runs, cost: prev.cost + cost, estimated: prev.estimated || est });
853
+ };
854
+ let totalCost = 0, totalRuns = 0, totalEst = false;
855
+ for (const d of report.days) {
856
+ if (at !== 'server') for (const r of d.runs) {
857
+ if (at && r.path !== at && !r.path.startsWith(at + '/')) continue;
858
+ const c = counted(r);
859
+ add(key({ ...r, day: d.day }), c, r.cost, !!r.estimated);
860
+ totalCost += r.cost; totalRuns += c; totalEst ||= !!r.estimated;
861
+ }
862
+ if ((!at || at === 'server') && d.server) for (const s of d.server.items) {
863
+ const sk = by === 'day' ? d.day : by === 'series' ? (s.site ? `server/${s.kind}/${s.site}` : `server/${s.kind}`) : by === 'person' ? `server (${s.person})` : 'server';
864
+ add(sk, 0, s.cost, !!s.estimated);
865
+ totalCost += s.cost; totalEst ||= !!s.estimated;
866
+ }
867
+ }
868
+ 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, ...(v.estimated && { estimated: true }) }))
869
+ .sort((a, b) => by === 'day' ? (a ).day.localeCompare((b ).day) : b.cost - a.cost);
870
+ if (flags.json) console.log(JSON.stringify(out, null, 1));
871
+ else {
872
+ for (const o of out) console.log(`${usd(o.cost, o.estimated).padStart(10)} ${String(o.runs).padStart(5)} runs ${(o.per_run === null ? '-' : usd(o.per_run, o.estimated)).padStart(8)} a run ${o[by]}${o.estimated ? ' (est.)' : ''}`);
873
+ console.log(`${usd(totalCost, totalEst).padStart(10)} ${String(totalRuns).padStart(5)} runs in all${totalEst ? ' (partly estimated)' : ''}`);
874
+ if (!at && report.key) console.log(keyText(report.key));
875
+ }
655
876
  }
656
877
  } else if (cmd === 'wakes' && args.length <= 1) {
657
878
  const at = (args[0] ?? '').replace(/\/+$/, ''), rows = (await get('/api')).flatMap(w => w.series.filter(s => !s.archived).flatMap(s => [
@@ -661,44 +882,59 @@ else if (cmd === 'comment' && args.length === 2) {
661
882
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
662
883
  else for (const r of rows) {
663
884
  console.log(`${r.path} last woken ${r.fired ? when(r.fired) : 'never'}${r.wakes.length || r.requests.length ? '' : ', none pending'}`);
664
- 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}`);
665
- 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'}`);
885
+ 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}${k.text ? `: ${k.text}` : ''}`);
886
+ for (const q of r.requests) console.log(` request ${q.id} to ${q.target ? 'wake' : 'start'} ${q.label}, from ${q.from} since ${when(q.at)}, waits on ${q.who ?? 'anyone'}${q.text ? `: ${q.text}` : ''}`);
666
887
  }
667
888
  } else if (cmd === 'activity' && args.length <= 1) {
668
- const at = (args[0] ?? '').replace(/\/+$/, ''), blocks = (await get(`/api/activity?since=${encodeURIComponent(String(flags.since ?? ''))}`))
889
+ const at = (args[0] ?? '').replace(/\/+$/, ''), blocks = (await get(`/api/activity?since=${since}`))
669
890
  .filter(b => !at || b.path === at || b.path.startsWith(at + '/'));
670
891
  if (flags.json) console.log(JSON.stringify(blocks, null, 1));
671
892
  else for (const b of blocks) {
672
893
  console.log(b.path);
673
894
  for (const e of b.entries) console.log(` ${when(e.at)} ${e.op === 'done' ? `run ${e.run} failed: ${e.error}`
674
- : `${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`}`}`);
895
+ : `${e.by} ${e.op === 'comment' ? `says: ${e.text.split('\n')[0].slice(0, 200)}` : e.op === 'upload' ? `uploads ${e.file}` : `${{ close: 'closes', abandon: 'abandons', delete: 'deletes' }[e.op]} it`}`}`);
675
896
  }
676
897
  } else if (cmd === 'egress' && (!args.length || (args.length === 2 && ['add', 'remove'].includes(args[0])))) {
677
898
  let hosts = await (await api('/egress')).json();
678
899
  if (args.length) hosts = await (await post('/egress', { hosts: args[0] === 'add' ? [...new Set([...hosts, args[1]])] : hosts.filter(h => h !== args[1]) }, 'PUT')).json();
679
900
  console.log(hosts.join('\n'));
901
+ } else if (cmd === 'internal' && (!args.length || (args.length === 2 && args[0] === 'remove'))) {
902
+ const hosts = args.length ? await (await api(`/internal/${encodeURIComponent(args[1])}`, { method: 'DELETE' })).json() : await get('/internal');
903
+ if (flags.json) console.log(JSON.stringify(hosts, null, 1));
904
+ else {
905
+ const w = Math.max(0, ...Object.keys(hosts).map(h => h.length));
906
+ for (const [h, { by, at }] of Object.entries(hosts)) console.log(`${h.padEnd(w)} ${when(at)} ${by}`);
907
+ if (!Object.keys(hosts).length) console.log('none: an admin lets websites reach one with rf site set NAME --internal true');
908
+ }
680
909
  } else if (cmd === 'people' && args.length <= 1) {
681
910
  // People as lines to edit and set: ROLE EMAIL for everyone, owner|member EMAIL-OR-GROUP for a workspace, each with a comment.
682
911
  const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
912
+ const kinds = ws ? ['owner', 'member'] : ['admin', 'user'];
913
+ const canon = (rows ) => {
914
+ const m = new Map ();
915
+ for (const [who, kind] of rows) if (!m.has(who) || kind === kinds[0]) m.set(who, kind);
916
+ return m;
917
+ };
683
918
  const last = (iso ) => iso ? `last in ${when(iso)}` : 'never in', listed = await get(ws ? `/api/workspaces/${ws.id}/people` : '/users');
684
- 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(', ')}`] }))
919
+ const raw = 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(', ')}`] }))
685
920
  : 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(', ')}`] }));
921
+ const had = canon(raw.map(p => [p.who, p.kind])), seen = new Set ();
922
+ const now = raw.filter(p => p.kind === had.get(p.who) && !seen.has(p.who) && !!seen.add(p.who));
686
923
  if (flags.json && typeof flags.set !== 'string') console.log(JSON.stringify(listed, null, 1));
687
924
  else if (typeof flags.set !== 'string') {
688
925
  const w = Math.max(0, ...now.map(p => p.who.length));
689
926
  for (const p of now) console.log(`${p.kind.padEnd(6)} ${p.who.padEnd(w)} # ${p.note.filter(Boolean).join('; ')}`);
690
927
  if (!now.length) console.log('# no one is in it: only admins see it');
691
928
  } else {
692
- const kinds = ws ? ['owner', 'member'] : ['admin', 'user'];
693
929
  const want = readFileSync(flags.set === '-' ? 0 : flags.set, 'utf8').split('\n').map(l => l.replace(/#.*/, '').trim()).filter(Boolean).map(l => l.split(/\s+/));
694
930
  const bad = want.find(([kind, who, more]) => !kinds.includes(kind) || !who || more);
695
931
  if (bad) throw new Error(`each line is ${kinds.join('|')} ${ws ? 'EMAIL-OR-GROUP' : 'EMAIL'}, not: ${bad.join(' ')}`);
696
- const had = new Map(now.map(p => [p.who, p.kind])), wanted = new Map(want.map(([kind, who]) => [who.toLowerCase(), kind]));
932
+ const wanted = canon(want.map(([kind, who]) => [who.toLowerCase(), kind]));
697
933
  const set = [...wanted].filter(([who, kind]) => had.get(who) !== kind), gone = ws ? [...had].filter(([who]) => !wanted.has(who)) : [];
698
934
  const changes = [...set.map(([who, kind]) => had.has(who) ? `${who}: ${had.get(who)} -> ${kind}` : `+ ${kind} ${who}`), ...gone.map(([who, kind]) => `- ${kind} ${who}`)];
699
935
  console.log(changes.join('\n') || 'no changes');
700
936
  if (changes.length && !flags['dry-run']) {
701
- const ofKind = (kind ) => want.filter(([k]) => k === kind).map(([, who]) => who);
937
+ const ofKind = (kind ) => [...wanted].filter(([, k]) => k === kind).map(([who]) => who);
702
938
  await (ws ? post(`/api/workspaces/${ws.id}`, { owners: ofKind('owner'), members: ofKind('member'), force: !!flags.force }, 'PUT')
703
939
  : post('/users', { roles: Object.fromEntries(set), force: !!flags.force }, 'PUT'));
704
940
  console.log('saved');
@@ -717,7 +953,7 @@ else if (cmd === 'comment' && args.length === 2) {
717
953
  const [cap, list] = args, people = flags.clear ? [] : list?.split(',').map(p => p.trim()).filter(Boolean);
718
954
  const all = await (await (people ? post('/capabilities', { cap, people }, 'PUT') : api('/capabilities'))).json();
719
955
  if (flags.json) console.log(JSON.stringify(all, null, 1));
720
- else for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || 'admins only'}`);
956
+ else for (const [c, who] of Object.entries(all)) if (!cap || c === cap) console.log(`${c}: ${who.join(', ') || (c === 'vpn' ? 'no one' : 'admins only')}`);
721
957
  } else if (cmd === 'user' && args.length >= 2) {
722
958
  const [what, email, role] = args, at = `/users/${encodeURIComponent(email)}`;
723
959
  if (what === 'add') await post('/users', { roles: { [email]: role ?? 'user' } }, 'PUT');
@@ -731,6 +967,7 @@ else if (cmd === 'comment' && args.length === 2) {
731
967
  }
732
968
  console.log('done');
733
969
  } else {
734
- console.error(usage(cmd));
970
+ const me = await get('/me');
971
+ console.error(usage(cmd, me.can.includes('vpn'), me.role === 'admin'));
735
972
  process.exitCode = 2;
736
973
  }