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