@rfany/rf 0.20.2 → 0.20.4

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 +9 -4
  2. package/package.json +1 -1
  3. package/rf.mjs +168 -36
package/README.md CHANGED
@@ -2,13 +2,18 @@
2
2
 
3
3
  People's command line for [rollforward](https://github.com/spoj/rollforward): what its page does, from a shell or a desktop agent, as you.
4
4
 
5
- npm i -g @rfany/rf
6
- rf login https://rollforward.example.com
5
+ Run with `npx` so you always stay on the latest version automatically:
6
+
7
+ npx @rfany/rf@latest login https://rollforward.example.com
8
+
9
+ Or use short-lived Entra ID tokens via Azure CLI (no static token saved to disk; requires HTTPS off loopback and an explicit `--resource api://<app-id>`, plus an initial browser sign-in to link your account and establish run-owner sign-in):
10
+
11
+ npx @rfany/rf@latest login https://rollforward.example.com --az --resource api://<app-id>
7
12
 
8
13
  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. Without saved config, help works offline; once signed in, it reads your current capabilities from the server.
14
+ `npx @rfany/rf@latest 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
15
 
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.
16
+ `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 series credentials 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
17
 
13
18
  `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
19
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfany/rf",
3
- "version": "0.20.2",
3
+ "version": "0.20.4",
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,8 +1,9 @@
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';
5
- import { spawn } from 'node:child_process';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync, } from 'node:fs';
6
+ import { execFileSync, spawn } from 'node:child_process';
6
7
  import { homedir, hostname } from 'node:os';
7
8
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
8
9
  import { parseArgs } from 'node:util';
@@ -14,7 +15,7 @@ process.on('uncaughtException', e => {
14
15
  });
15
16
 
16
17
  const usage = (c , vpn = false, admin = false) => {
17
- const all = `rf login URL [TOKEN] without a TOKEN, through the browser: type rf's code on the page, and allow it
18
+ const all = `rf login URL [TOKEN] [--az [--resource URI]] without a TOKEN, through the browser; with --az, short-lived Entra tokens via Azure CLI (no token on disk); run via npx @rfany/rf@latest
18
19
  rf ls [--mine] [--json] every workspace, series and instance you see, with its status, owner, asks waiting and wakes;
19
20
  --mine, only open instances of series you own
20
21
  rf waiting [--json] what waits on you: asks, proposals, requests and expired logins; also note notices (FYI).
@@ -49,9 +50,9 @@ rf approve PATH cN [TEXT] [--wake] records content approval of proposal cN, no
49
50
  rf reject PATH cN [TEXT] [--wake] rejects the agent's proposal cN, with feedback on missing information or changes;
50
51
  revised work takes a new proposal
51
52
  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
52
- rf close PATH [--as-series NAME] [--wake] the series owner makes it the record and an example,
53
+ rf close PATH [--as-series NAME] the series owner makes it the record and an example,
53
54
  approving nothing; a task closes as a one-off, or as the first instance of the series NAME it
54
- becomes; --wake starts runs of the series' later open instances, which may have used its draft
55
+ becomes
55
56
  rf abandon PATH the series owner leaves it as it is, neither an example nor a starting point
56
57
  rf delete PATH [--yes] its workspace's owners and admins delete an instance, in any status, once they confirm, or
57
58
  with --yes: a run for it is cut, and all the server holds of it goes but its label and place,
@@ -61,7 +62,7 @@ rf series owner SERIES [EMAIL] [--json] the whole series' owner; EMAIL transfe
61
62
  clearing consent; only its current owner or a workspace manager may transfer it
62
63
  rf series credentials SERIES [--set OFFER,...|--clear] [--autonomous true|false] [--json]
63
64
  credentials for every instance; only the owner saves consent, explicitly including [] with
64
- --clear; saving requires --autonomous true|false; no credentials or schedules transfer
65
+ --clear; saving requires --autonomous true|false; no credentials transfer (schedules pause until opted in)
65
66
  rf rename PATH NAME an instance, a series or a workspace, by its path
66
67
  rf new task WORKSPACE [LABEL] [--creds OFFER,...|--clear] [--autonomous true|false] [--comment TEXT [--wake]] a one-off task, Untitled until LABEL or its
67
68
  first comment names it; --wake starts its run on the comment; without --creds or --clear,
@@ -105,12 +106,14 @@ rf grant approve|deny ID [TEXT] a request to use a website in a workspace you
105
106
  rf grant revoke ID a grant pending or approved, yours or in a workspace you own; its runs' browsers close
106
107
  rf correct PATH TEXT [--item ID] [--ref REF] [--superseded] [--see LABEL] a closed instance, or its item ID at REF, is
107
108
  wrong, or superseded, as LABEL, another instance of its series, shows; it can't be withdrawn
108
- rf wake PATH AT [TEXT] [--label LABEL] [--days DAYS] [--check PATH [--deadline ISO]] | rf wake --cancel ID
109
+ rf wake PATH AT [TEXT] [--label LABEL] [--days DAYS] [--check PATH [--deadline ISO] [--max-stale MIN] [--backstop-hours H]] | rf wake --cancel ID
109
110
  AT now, +<n>m|h|d or a date; PATH an open instance, or a series with LABEL; TEXT a short
110
111
  message for the run; the owner's now starts under current consent without autonomous opt-in;
111
112
  later or agent-set wakes need it. Collaborators' wakes are requests. DAYS, such as mon-fri,
112
113
  repeats weekly at AT's time. With the owner's wake-check capability, --check working/FILE.py (or .ts)
113
- gates a scheduled wake; optional --deadline TIME (ISO with offset) runs Pi even if the check stops.
114
+ gates a scheduled wake; optional --deadline TIME (ISO with offset) runs Pi even if the check stops,
115
+ --max-stale MIN overrides the 150m M365 index staleness cap, and --backstop-hours H overrides the
116
+ 24h recurring skip backstop.
114
117
  rf agents [WORKSPACE] [--set FILE|-] the company's AGENTS.md, or a workspace's; setting the company's is for admins
115
118
  rf readers WORKSPACE [add|remove OTHER] the workspaces whose agents read WORKSPACE and those its own read, as each one's
116
119
  owners let them; its owners let OTHER's agents read it, one they see, and its owners or
@@ -187,7 +190,7 @@ What there is
187
190
  credentials. Scheduled and autonomous runs need a separate opt-in. Other collaborators' comments, uploads and approvals are notes that start nothing.
188
191
  Transferring the whole series stops old runs and clears consent; old unread instructions become notes. Each act keeps
189
192
  its author, and every run its executor.
190
- - rf is quiet: a comment, upload, approval, rejection, close, new instance or request it starts begins no run unless --wake, and the agent
193
+ - rf is quiet: a comment, upload, approval, rejection, new instance or request it starts begins no run unless --wake, and the agent
191
194
  reads it at its next run. The owner's rf wake PATH now starts one under current consent, without autonomous opt-in.
192
195
  A quiet upload or comment is committed to the instance's history at once.
193
196
  - 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
@@ -231,7 +234,7 @@ Usual work
231
234
  - Give an input or a corrected output: rf upload PATH FILE [--onto ITEM] [--output], with --wake on the last for a run on them
232
235
  all.
233
236
  - Start an instance: rf new instance SERIES LABEL --wake, only as the series owner. Scheduled wakes need that owner's
234
- autonomous opt-in and keep their authorized credential snapshot; collaborators' wakes become requests for the owner.
237
+ autonomous opt-in and use their current series credentials at fire time; collaborators' wakes become requests for the owner.
235
238
  A one-off: rf new task WORKSPACE --clear --comment TEXT --wake. Promotion with rf new series PATH NAME keeps its owner.
236
239
  - Tell a series something for its runs, or while no instance is open: rf comment SERIES TEXT, which starts no run.
237
240
  rf comment SERIES lists its notes; rf comment --mine lists your notes. Settle an informing note with
@@ -283,7 +286,7 @@ if (cmd === 'comment' || cmd === 'settle') {
283
286
  } else for (let i = 0; i < argv.length; i++) {
284
287
  const flag = argv[i] === '-n' ? 'dry-run' : argv[i] === '-d' ? 'delay' : argv[i].match(/^--(.+)$/)?.[1];
285
288
  if (!flag) args.push(argv[i]);
286
- else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount', 'yes', 'mine', 'daily', 'all'].includes(flag)) flags[flag] = true;
289
+ else if (['wait', 'wake', 'output', 'delete', 'dry-run', 'force', 'json', 'failed', 'running', 'clear', 'follow', 'superseded', 'undo', 'by-amount', 'yes', 'mine', 'daily', 'all', 'az'].includes(flag)) flags[flag] = true;
287
290
  else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
288
291
  else if (flag === 'exclude') excludes.push(argv[++i]);
289
292
  else flags[flag] = argv[++i];
@@ -298,10 +301,69 @@ if ((!cmd || cmd === 'help') && !existsSync(config)) {
298
301
  process.exit();
299
302
  }
300
303
  if (cmd !== 'login' && !existsSync(config)) throw new Error('sign in first: rf login URL');
301
- let { url, token } = cmd === 'login' ? { url: args[0]?.replace(/\/$/, ''), token: args[1] } : JSON.parse(readFileSync(config, 'utf8'));
304
+ let { url, token, auth, resource } = cmd === 'login'
305
+ ? { url: args[0]?.replace(/\/$/, ''), token: args[1], auth: flags.az ? 'az' : (typeof flags.auth === 'string' ? flags.auth : undefined), resource: typeof flags.resource === 'string' ? flags.resource : undefined }
306
+ : JSON.parse(readFileSync(config, 'utf8'));
307
+
308
+ function assertSafeAzUrl(rawUrl ) {
309
+ let parsed ;
310
+ try {
311
+ parsed = new URL(rawUrl);
312
+ } catch {
313
+ throw new Error(`invalid server URL: ${rawUrl}`);
314
+ }
315
+ const host = parsed.hostname.toLowerCase();
316
+ const isLoopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
317
+ if (parsed.protocol !== 'https:' && !isLoopback) {
318
+ throw new Error('--az requires https:// off loopback');
319
+ }
320
+ }
321
+
322
+ function assertValidAzResource(res ) {
323
+ if (!res || res.startsWith('-') || !/^[A-Za-z0-9:/._-]+$/.test(res)) {
324
+ throw new Error('invalid --resource for --az; pass an explicit Entra resource such as --resource api://<app-id>');
325
+ }
326
+ }
327
+
328
+ function jwtExpMs(tok ) {
329
+ try {
330
+ const parts = tok.split('.');
331
+ if (parts.length !== 3) return 0;
332
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
333
+ return typeof payload?.exp === 'number' ? payload.exp * 1000 : 0;
334
+ } catch {
335
+ return 0;
336
+ }
337
+ }
338
+
339
+ let cachedAzToken ;
340
+ function bearerToken() {
341
+ if (auth === 'az') {
342
+ if (cachedAzToken && (cachedAzToken.expMs === 0 || cachedAzToken.expMs - Date.now() > 300_000)) {
343
+ return cachedAzToken.token;
344
+ }
345
+ assertSafeAzUrl(url);
346
+ if (!resource) throw new Error('missing resource for --az auth; run rf login URL --az --resource api://<app-id>');
347
+ assertValidAzResource(resource);
348
+ const azBin = process.env.RF_AZ_BIN || 'az';
349
+ const azArgs = ['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'];
350
+ try {
351
+ const out = (process.platform === 'win32'
352
+ ? execFileSync('cmd.exe', ['/d', '/s', '/c', azBin, ...azArgs], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
353
+ : execFileSync(azBin, azArgs, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })).trim();
354
+ if (!out) throw new Error('empty access token returned by az');
355
+ cachedAzToken = { token: out, expMs: jwtExpMs(out) };
356
+ return out;
357
+ } catch (e ) {
358
+ const stderr = String(e?.stderr ?? '').trim();
359
+ throw new Error(`az account get-access-token failed: ${stderr || e.message}`);
360
+ }
361
+ }
362
+ return token;
363
+ }
302
364
 
303
365
  async function api(path , init = {}, accept = []) {
304
- const r = await fetch(url + path, { ...init, headers: { authorization: `Bearer ${token}` } });
366
+ const r = await fetch(url + path, { ...init, headers: { authorization: `Bearer ${bearerToken()}` } });
305
367
  if (!r.ok && !accept.includes(r.status)) throw new Error(`${init.method ?? 'GET'} ${path}: ${r.status} ${await r.text()}`);
306
368
  return r;
307
369
  }
@@ -344,7 +406,7 @@ async function workspaceNamed(name ) {
344
406
  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];
345
407
  // Explicit series-wide offer selection.
346
408
  const ticks = () => flags.clear ? [] : String(flags.creds ?? flags.set ?? '').split(',').map(o => o.trim()).filter(Boolean);
347
- const consent = (offers ) => `, series-wide ceiling: ${offers.join(', ') || 'no credentials'}; you explicitly consent to agents acting as you`;
409
+ const consent = (offers ) => `, series credentials: ${offers.join(', ') || 'no credentials'}; you explicitly consent to agents acting as you`;
348
410
 
349
411
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
350
412
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
@@ -406,24 +468,52 @@ const runsIn = async (path = '') => (await get(`/api/runs?since=${since}`))
406
468
  .filter(r => !path || r.path === path.replace(/\/+$/, '') || r.path.startsWith(path.replace(/\/+$/, '') + '/'));
407
469
 
408
470
  function write(path , data , mtime ) {
409
- mkdirSync(dirname(path), { recursive: true });
410
- rmSync(path, { force: true });
411
- writeFileSync(path, data);
412
- utimesSync(path, new Date(mtime), new Date(mtime));
413
- chmodSync(path, 0o444);
471
+ const dir = dirname(path);
472
+ mkdirSync(dir, { recursive: true });
473
+ const existing = lstatSync(path, { throwIfNoEntry: false });
474
+ if (existing?.isSymbolicLink()) throw new Error(`${path} is a symlink: remove it or pull into another directory`);
475
+ const tmp = join(dir, `.rf-pull-${process.pid}-${randomBytes(6).toString('hex')}.tmp`);
476
+ try {
477
+ writeFileSync(tmp, data, { flag: 'wx', mode: 0o600 });
478
+ utimesSync(tmp, new Date(mtime), new Date(mtime));
479
+ chmodSync(tmp, 0o444);
480
+ try {
481
+ renameSync(tmp, path);
482
+ } catch (e) {
483
+ const code = (e ).code;
484
+ if (process.platform === 'win32' && (code === 'EPERM' || code === 'EACCES')) {
485
+ const cur = lstatSync(path, { throwIfNoEntry: false });
486
+ if (cur && !cur.isSymbolicLink() && cur.isFile()) {
487
+ const oldMode = cur.mode;
488
+ chmodSync(path, 0o644);
489
+ try {
490
+ renameSync(tmp, path);
491
+ } catch (retryErr) {
492
+ try { chmodSync(path, oldMode); } catch {}
493
+ throw retryErr;
494
+ }
495
+ return;
496
+ }
497
+ }
498
+ throw e;
499
+ }
500
+ } catch (e) {
501
+ rmSync(tmp, { force: true });
502
+ throw e;
503
+ }
414
504
  }
415
505
 
416
506
  // 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
417
507
  // 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
418
508
  // 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,
419
- // whose config would run a command as git runs there. A link where one of its folders goes, or `base`, would take the file
420
- // elsewhere too, and is refused.
509
+ // whose config would run a command as git runs there. A link where one of its folders goes, or `base`, or at the file itself,
510
+ // would take the file elsewhere too, and is refused.
421
511
  const under = (base , rel ) => {
422
512
  const names = rel.split('/');
423
513
  if (names.some(n => !n || n === '.' || n === '..' || basename(n) !== n || /^(\.git|git~1)[. ]*([:\\]|$)/i.test(n)
424
514
  || (process.platform === 'win32' && (/[<>:"|?*\x00-\x1f]|[. ]$/.test(n) || /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(n))))) return undefined;
425
515
  let folder = base;
426
- for (const name of ['', ...names.slice(0, -1)]) {
516
+ for (const name of ['', ...names]) {
427
517
  folder = join(folder, name);
428
518
  let st ;
429
519
  try { st = lstatSync(folder, { throwIfNoEntry: false }); }
@@ -547,11 +637,22 @@ async function browserToken() {
547
637
  }
548
638
 
549
639
  if (cmd === 'login' && url) {
550
- token ??= await browserToken();
551
- const me = await get('/me');
552
- mkdirSync(dirname(config), { recursive: true });
553
- writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
554
- console.log(`signed in as ${me.email}`);
640
+ if (auth === 'az') {
641
+ assertSafeAzUrl(url);
642
+ resource ||= process.env.RF_AZ_RESOURCE;
643
+ if (!resource) throw new Error('--az requires an explicit trusted --resource api://<app-id> (or RF_AZ_RESOURCE)');
644
+ assertValidAzResource(resource);
645
+ const me = await get('/me');
646
+ mkdirSync(dirname(config), { recursive: true });
647
+ writeFileSync(config, JSON.stringify({ url, auth: 'az', resource }), { mode: 0o600 });
648
+ console.log(`signed in as ${me.email} (az)`);
649
+ } else {
650
+ token ??= await browserToken();
651
+ const me = await get('/me');
652
+ mkdirSync(dirname(config), { recursive: true });
653
+ writeFileSync(config, JSON.stringify({ url, token }), { mode: 0o600 });
654
+ console.log(`signed in as ${me.email}`);
655
+ }
555
656
  } else if (cmd === 'ls' && !args.length) {
556
657
  // --mine: open instances of series you own.
557
658
  const me = flags.mine && await get('/me'), rows = (await get('/api')).flatMap(w => w.series.flatMap(s => [
@@ -562,7 +663,7 @@ if (cmd === 'login' && url) {
562
663
  else for (const r of rows) {
563
664
  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` : ''}`);
564
665
  if (r.wakeCheck) console.log(` Wake check stopped: ${clip(r.wakeCheck.message.replace(/[\x00-\x1f\x7f-\x9f]/g, ' '), TEXT_COLS)}`);
565
- 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}` : ''}${k.check ? `; check ${k.check}${k.deadline ? ` until ${k.deadline}` : ''}` : ''}`);
666
+ 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}` : ''}${k.check ? `; check ${k.check}${k.deadline ? ` until ${k.deadline}` : ''}${k.maxStaleMin ? `, max-stale ${k.maxStaleMin}m` : ''}${k.backstopHours ? `, backstop ${k.backstopHours}h` : ''}` : ''}`);
566
667
  }
567
668
  } else if (cmd === 'waiting' && !args.length) {
568
669
  const [me, s, all] = await Promise.all([get('/me'), get('/api/status'), get('/api')]), mine = (who ) => (who ?? me.email) === me.email;
@@ -726,16 +827,43 @@ else if (cmd === 'comment' && args.length < 2) {
726
827
  else console.log(`${args[1]}: series owner ${s.owner ?? 'not selected'}`);
727
828
  } else if (cmd === 'series' && args[0] === 'credentials' && args.length === 2) {
728
829
  const s = await seriesAt(args[1]);
830
+ const fmtSched = (k ) => ` ${k.id} ${k.targetLabel ?? k.target} ${k.at}${k.deadline ? ` (deadline ${k.deadline})` : ''}${k.days ? ` (${k.days.join(',')})` : ''}${k.label ? ` ${k.label}` : ''}${k.from ? ` by ${k.from}` : ''}${k.check ? ` check=${k.check}` : ''}${k.text ? ` ${k.text}` : ''}`;
729
831
  if (flags.set !== undefined || flags.clear) {
730
832
  if (!['true', 'false'].includes(String(flags.autonomous))) throw new Error('saving requires --autonomous true|false');
731
- await post(`/api/series/${s.id}/credentials`, { logins: ticks(), autonomous: flags.autonomous === 'true' }, 'PUT');
833
+ const previewRes = await api(`/api/series/${s.id}/credentials`, {}, flags.autonomous === 'true' ? [] : [404, 405]);
834
+ const preview = previewRes.ok ? await previewRes.json() : null;
835
+ if (flags.autonomous === 'true' && !preview) {
836
+ throw new Error('could not load pending schedules to review before enabling autonomous runs');
837
+ }
838
+ if (flags.autonomous === 'true' && Array.isArray(preview?.schedules) && preview.schedules.length) {
839
+ console.log(`pending schedules to be adopted (${preview.schedules.length}):`);
840
+ for (const k of preview.schedules) console.log(fmtSched(k));
841
+ }
842
+ const body = { logins: ticks(), autonomous: flags.autonomous === 'true' };
843
+ if (preview?.epoch !== undefined) body.expectedEpoch = preview.epoch;
844
+ if (preview?.scheduleRevision) body.expectedSchedules = preview.scheduleRevision;
845
+ const putRes = await post(`/api/series/${s.id}/credentials`, body, 'PUT');
846
+ const rawText = await putRes.text();
847
+ let saved = null;
848
+ try { saved = JSON.parse(rawText); } catch {}
732
849
  console.log(`saved ${args[1]}${consent(ticks())}; autonomous ${flags.autonomous}`);
850
+ if (!preview && flags.autonomous === 'true' && Array.isArray(saved?.schedules) && saved.schedules.length) {
851
+ console.log(`pending schedules that will run (${saved.schedules.length}):`);
852
+ for (const k of saved.schedules) console.log(fmtSched(k));
853
+ }
733
854
  } else {
734
855
  if (flags.autonomous !== undefined) throw new Error('select credentials with --set OFFER,... or --clear');
735
856
  const mine = await get('/logins');
736
- const out = { owner: s.owner, consent: s.consent, yours: mine.flatMap(l => l.offers.map(o => ({ ...o, ...(l.expired && { expired: true }) }))) };
857
+ const detail = await api(`/api/series/${s.id}/credentials`, {}, [404, 405]).then(async r => r.ok ? r.json() : null).catch(() => null);
858
+ const out = { owner: s.owner, consent: s.consent, schedules: detail?.schedules ?? [], yours: mine.flatMap((l ) => l.offers.map((o ) => ({ ...o, ...(l.expired && { expired: true }) }))) };
737
859
  if (flags.json) console.log(JSON.stringify(out, null, 1));
738
- 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'));
860
+ else console.log([
861
+ `Series owner: ${out.owner ?? 'not selected'}`,
862
+ out.consent ? `Series credentials: ${out.consent.logins.join(', ') || 'no credentials'}; autonomous ${out.consent.autonomous}` : 'No execution consent',
863
+ ...(out.schedules.length ? [`pending schedules (${out.schedules.length}):`, ...out.schedules.map(fmtSched)] : []),
864
+ 'your offers:',
865
+ ...out.yours.map((o ) => ` ${o.id} ${o.name}${o.expired ? ' expired' : ''}`),
866
+ ].join('\n'));
739
867
  }
740
868
  } else if (cmd === 'rename' && args.length === 2) {
741
869
  const [w, s, l] = args[0].replace(/\/+$/, '').split('/');
@@ -763,7 +891,7 @@ else if (cmd === 'comment' && args.length < 2) {
763
891
  if (flags.creds !== undefined || flags.clear || flags.autonomous !== undefined) throw new Error('instance credentials were removed: use rf series credentials SERIES');
764
892
  const series = await seriesAt(args[1]);
765
893
  const { id } = await (await post(`/api/series/${series.id}`, { label: args[2], quiet: !flags.wake })).json();
766
- console.log(`made ${await pathOf(id)}; series owner and ceiling unchanged${series.owner ? `; ${series.owner} starts its runs` : ''}`);
894
+ console.log(`made ${await pathOf(id)}; series owner and credentials unchanged${series.owner ? `; ${series.owner} starts its runs` : ''}`);
767
895
  } else if (cmd === 'new' && args[0] === 'series' && args.length === 3) {
768
896
  await post(`/api/series/${(await find(args[1])).series.id}/promote`, { name: args[2] });
769
897
  console.log(`made the series ${args[1].split('/')[0]}/${args[2]}`);
@@ -782,7 +910,7 @@ else if (cmd === 'comment' && args.length < 2) {
782
910
  if (flags.creds !== undefined || flags.clear) throw new Error('request credentials were removed: use rf series credentials SERIES');
783
911
  const r = await post(`/api/requests/${args[1]}`, { quiet: !flags.wake });
784
912
  const woke = r.headers.get('X-RF-Woke') === '1', { id } = await r.json();
785
- console.log(`${woke ? 'woke' : 'made'} ${await pathOf(id)}; series owner and ceiling unchanged`);
913
+ console.log(`${woke ? 'woke' : 'made'} ${await pathOf(id)}; series owner and credentials unchanged`);
786
914
  }
787
915
  } else if (cmd === 'logins' && !args.length) {
788
916
  const all = await get('/logins');
@@ -857,8 +985,12 @@ else if (cmd === 'comment' && args.length < 2) {
857
985
  } else if (cmd === 'wake' && [2, 3].includes(args.length)) {
858
986
  const { series, inst } = await find(args[0]);
859
987
  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]);
860
- 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], check: flags.check, deadline: flags.deadline }, 'PUT')).json();
861
- console.log(`wake ${w.id} at ${w.at}${w.days ? `, then each ${w.days.join(', ')}` : ''}${w.check ? `; check ${w.check}${w.deadline ? ` until ${w.deadline}` : ''}` : ''}`);
988
+ const num = (v ) => (typeof v !== 'string' ? undefined : /^\d+$/.test(v) ? Number(v) : v);
989
+ const w = await (await post(`/api/wakes/${inst?.id ?? series.id}`, {
990
+ at: new Date(at).toISOString(), label: flags.label, days: flags.days, text: args[2], check: flags.check, deadline: flags.deadline,
991
+ maxStaleMin: num(flags['max-stale']), backstopHours: num(flags['backstop-hours']),
992
+ }, 'PUT')).json();
993
+ console.log(`wake ${w.id} at ${w.at}${w.days ? `, then each ${w.days.join(', ')}` : ''}${w.check ? `; check ${w.check}${w.deadline ? ` until ${w.deadline}` : ''}${w.maxStaleMin ? `, max-stale ${w.maxStaleMin}m` : ''}${w.backstopHours ? `, backstop ${w.backstopHours}h` : ''}` : ''}`);
862
994
  } else if (cmd === 'agents' && args.length <= 1) {
863
995
  const ws = args[0] === undefined ? undefined : await workspaceNamed(args[0]);
864
996
  if (typeof flags.set !== 'string') console.log(ws ? ws.agents : (await get('/agents')).text);
@@ -1064,7 +1196,7 @@ else if (cmd === 'kill' && args.length === 1 && /^\d+$/.test(args[0])) {
1064
1196
  if (flags.json) console.log(JSON.stringify(rows, null, 1));
1065
1197
  else for (const r of rows) {
1066
1198
  console.log(`${r.path} last woken ${r.fired ? when(r.fired) : 'never'}${r.wakes.length || r.requests.length ? '' : ', none pending'}`);
1067
- 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}` : ''}${k.check ? `; check ${k.check}${k.deadline ? ` until ${k.deadline}` : ''}` : ''}`);
1199
+ 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}` : ''}${k.check ? `; check ${k.check}${k.deadline ? ` until ${k.deadline}` : ''}${k.maxStaleMin ? `, max-stale ${k.maxStaleMin}m` : ''}${k.backstopHours ? `, backstop ${k.backstopHours}h` : ''}` : ''}`);
1068
1200
  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}` : ''}`);
1069
1201
  }
1070
1202
  } else if (cmd === 'activity' && args.length <= 1) {