@rfany/rf 0.17.0 → 0.18.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 (2) hide show
  1. package/package.json +1 -1
  2. package/rf.mjs +126 -32
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfany/rf",
3
- "version": "0.17.0",
3
+ "version": "0.18.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
@@ -111,12 +111,14 @@ rf skills
111
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
112
112
  rf skill versions ID
113
113
  rf connections
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
114
+ rf status [--long MIN] [--all] [-d SECONDS] [--json] what goes on and what's stuck: low OpenRouter credit (for admins), runs going, flagged
115
+ past MIN minutes (30), and queued, with why; what waits on whom since when, the oldest three
116
+ each unless --all; open instances whose last run failed; -d shows it
117
+ again every SECONDS, as top does, until Ctrl+C
116
118
  rf indexes [--json] each index of a source you index, all for admins: its kind, items and size, and per person
117
119
  its phase, crawl or follow, pages read, when last caught up, and its error and next try
118
- rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] [--json]
119
- a line per run: start, path, run, outcome, time, cost, what started it, and any error;
120
+ rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] [-d SECONDS] [--json]
121
+ a table, a row per run: start, path, run, outcome, time, cost, what started it, and any error;
120
122
  the outcome is done, interrupted by a person, cut, by a restart or a change that broke its
121
123
  lease, running, or failed, for credits, policy, time limit or other
122
124
  rf costs [PATH] [--since DATE] [--by workspace|series|person|day|outcome] [--daily] [--json] totals, runs and cost per run,
@@ -137,6 +139,11 @@ rf skill rollback ID N pushes version N again, as the newest
137
139
  Admins:
138
140
  rf people [--set FILE|-] [-n] [--force] everyone as lines of ROLE EMAIL, each with a comment; --set sets the roles of the people
139
141
  listed and adds new ones, removing no one
142
+ rf top [-d SECONDS] [--json] the host's CPU, load and memory; each run going, with its processes and what they use; and the
143
+ ten processes of runs busiest by CPU and by memory, each by its PID, script and command line
144
+ rf kill PID [--start N] ends a process of a run going, as rf top lists it, and all it started, with SIGTERM, then SIGKILL
145
+ after 5 seconds, logged in its instance, whose agent hears of it; N, its start in rf top --json,
146
+ makes sure it's that process still; never the sandbox's own: rf interrupt PATH stops its run
140
147
  rf user add EMAIL [admin] | role EMAIL admin|user [--force] | disable EMAIL | enable EMAIL | signout EMAIL | remove EMAIL
141
148
  rf egress [add|remove HOST] the hosts runs may reach beyond package registries, GitHub and documentation sites, such as
142
149
  api.example.com or *.example.org; admins add and remove them
@@ -227,10 +234,14 @@ Usual work
227
234
  Watching over it, for admins and power users; each sees what the caller sees
228
235
  - 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
236
  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
230
- they hold, and requests to start; open instances whose last run failed; and indexes crawling or failing.
237
+ they hold, and requests to start, grouped by whom they wait on, the oldest three each unless --all; open instances whose last run
238
+ failed; and indexes crawling or failing.
239
+ - What runs use (admins): rf top shows the host's CPU, load and memory, each run going with its processes, CPU and memory, and the
240
+ ten processes of runs busiest by CPU and by memory. rf kill PID ends one, with all it started; rf interrupt PATH stops a run.
241
+ rf top, rf status and rf runs take -d SECONDS to show again every SECONDS, as top does, until Ctrl+C.
231
242
  - Indexes: rf indexes shows each index of a big library or mailbox you index, every one for admins: its items and size, and per
232
243
  person whether it is crawling or following changes, pages read, when last caught up, and an error, if any, with its next try.
233
- - History: rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] prints a line per run: its start, path, run number,
244
+ - History: rf runs [PATH] [--since DATE] [--failed] [--running] [--long MIN] prints a table, a row per run: its start, path, run number,
234
245
  outcome, time taken, cost, what started it and by whom, and any error. rf costs [PATH] [--since DATE] [--by
235
246
  workspace|series|person|day|outcome] [--daily] totals them (by the runner for person, plus server calls and OpenRouter key usage
236
247
  for admins). A DATE such as 2026-11-01 starts at its midnight on this machine's clock, the days --by day groups by.
@@ -245,9 +256,9 @@ const config = join(homedir(), '.config', 'rollforward.json');
245
256
  const [cmd, ...argv] = process.argv.slice(2);
246
257
  const flags = {}, excludes = [], args = [];
247
258
  for (let i = 0; i < argv.length; i++) {
248
- const flag = argv[i] === '-n' ? 'dry-run' : argv[i].match(/^--(.+)$/)?.[1];
259
+ const flag = argv[i] === '-n' ? 'dry-run' : argv[i] === '-d' ? 'delay' : argv[i].match(/^--(.+)$/)?.[1];
249
260
  if (!flag) args.push(argv[i]);
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;
261
+ 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;
251
262
  else if (argv[i + 1] === undefined) throw new Error(`--${flag} takes a value`);
252
263
  else if (flag === 'exclude') excludes.push(argv[++i]);
253
264
  else flags[flag] = argv[++i];
@@ -313,10 +324,56 @@ const consent = (offers ) => `, series-wide ceiling: ${offers.join(', '
313
324
  // Times as this machine's clock reads them, and lengths of time and costs, for the views.
314
325
  const when = (iso ) => new Date(iso).toLocaleString('sv-SE', { dateStyle: 'short', timeStyle: 'short' });
315
326
  const grantText = (g ) => `${g.description}${g.flags.length ? ` Flags: ${g.flags.join('; ')}.` : ''}${g.adminOnly ? ` ${g.adminWhy}.` : ''}`;
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')}`;
327
+ const took = (s ) => s < 60 ? `${Math.round(s)}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 86400 ? `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}` : `${Math.floor(s / 86400)}d${Math.floor((s % 86400) / 3600)}h`;
317
328
  const usd = (n , est ) => `${est ? '~' : ''}${n < 0 ? '-$' + (-n).toFixed(2) : '$' + n.toFixed(2)}`;
318
329
  const usdNote = (n , est ) => `${usd(n, est)}${est ? ' (est.)' : ''}`;
319
330
  const signedUsd = (n ) => `${n >= 0 ? '+$' : '-$'}${Math.abs(n).toFixed(2)}`;
331
+ // Text as a terminal lays it out: a CJK character or an emoji takes two columns. A cell is cut to its column's width with …, and a
332
+ // table's columns line up under its header; the last one is left as long as it is.
333
+ const wide = (c ) => (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff)
334
+ || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff) || (c >= 0x20000 && c <= 0x3fffd);
335
+ const cols = (t ) => [...t].reduce((n, ch) => n + (wide(ch.codePointAt(0) ) ? 2 : 1), 0);
336
+ function clip(t , max ) {
337
+ if (cols(t) <= max) return t;
338
+ let out = '', n = 0;
339
+ for (const ch of t) {
340
+ const w = wide(ch.codePointAt(0) ) ? 2 : 1;
341
+ if (n + w > max - 1) break;
342
+ out += ch; n += w;
343
+ }
344
+ return `${out}…`;
345
+ }
346
+ const table = (header , rows , indent = ' ') => {
347
+ const all = header.length ? [header, ...rows] : rows, widths = (all[0] ?? []).map((_, i) => Math.max(...all.map(r => cols(r[i] ?? ''))));
348
+ return all.map(r => indent + r.map((c, i) => (i === r.length - 1 ? c : c + ' '.repeat(widths[i] - cols(c)))).join(' ').trimEnd()).join('\n');
349
+ };
350
+ // What a person reads of an agent's words in a list: the first line, without markdown's marks, cut to `max` columns.
351
+ const gist = (text , max ) => clip((text.split('\n').find(l => l.trim()) ?? '').trim()
352
+ .replace(/\*\*|__|`/g, '').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^#+\s*/, ''), max);
353
+ // An error as one line: an answer's JSON body gives way to its message, as in "402 This request requires more credits".
354
+ function brief(error , max = 100) {
355
+ const line = error.split('\n')[0], at = line.indexOf('{');
356
+ if (at < 0) return clip(line, max);
357
+ const head = line.slice(0, at).replace(/[\s:]+$/, ''), message = /"message"\s*:\s*"((?:[^"\\]|\\.)+)"/.exec(line.slice(at))?.[1];
358
+ return clip([head, message?.replace(/\\(.)/g, '$1')].filter(Boolean).join(' '), max);
359
+ }
360
+ // -d SECONDS shows a view again every SECONDS, from the top of the screen, as top does, until Ctrl+C; a failure to fetch it shows in
361
+ // its place, and the next refresh tries again.
362
+ const MIN_DELAY = 1;
363
+ async function watch(view ) {
364
+ if (flags.delay === undefined) return console.log(await view());
365
+ const every = Number(flags.delay);
366
+ if (!(every >= MIN_DELAY)) throw new Error(`-d: the seconds between refreshes, ${MIN_DELAY} or more`);
367
+ for (;;) {
368
+ let text ;
369
+ try { text = await view(); } catch (e) { if (!(e instanceof Error)) throw e; text = `rf: ${e.message}`; }
370
+ process.stdout.write(`\x1b[H\x1b[2J${new Date().toLocaleString('sv-SE')} every ${every}s, Ctrl+C to stop\n\n${text}\n`);
371
+ await new Promise(r => setTimeout(r, every * 1000));
372
+ }
373
+ }
374
+ // A view's widest path and text, in columns, and how many of what waits on one person rf status lists before --all.
375
+ const PATH_COLS = 60, TEXT_COLS = 70, WAITING = 3;
376
+ const mb = (bytes ) => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(1)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
320
377
  const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? '';
321
378
  // --since DATE from its midnight on this machine's clock, as --by day groups by.
322
379
  const since = encodeURIComponent(/^\d{4}-\d{2}-\d{2}$/.test(String(flags.since)) ? new Date(`${flags.since}T00:00`).toISOString() : String(flags.since ?? ''));
@@ -485,6 +542,7 @@ if (cmd === 'login' && url) {
485
542
  const [me, s, all] = await Promise.all([get('/me'), get('/api/status'), get('/api')]), mine = (who ) => (who ?? me.email) === me.email;
486
543
  const series = all.flatMap(w => w.series.map(x => ({ ...x, path: `${w.name}/${x.name}` })));
487
544
  const rows = [
545
+ ...s.ownership.map(s => ({ kind: 'owner', path: s.path, text: s.text })),
488
546
  ...s.asks.filter(a => a.who === me.email).map(a => ({ kind: a.note ? 'note' : 'ask', path: a.path, since: a.since, text: a.text })),
489
547
  ...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}` : ''}` }))),
490
548
  ...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`}` })),
@@ -618,8 +676,9 @@ else if (cmd === 'comment' && args.length === 2) {
618
676
  console.log(`made ${await pathOf(instance)}${selected ? consent(ticks()) : '; no execution consent: select series credentials before running'}`);
619
677
  } else if (cmd === 'new' && args[0] === 'instance' && args.length === 3) {
620
678
  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`);
679
+ const series = await seriesAt(args[1]);
680
+ const { id } = await (await post(`/api/series/${series.id}`, { label: args[2], quiet: !flags.wake })).json();
681
+ console.log(`made ${await pathOf(id)}; series owner and ceiling unchanged${series.owner ? `; ${series.owner} starts its runs` : ''}`);
623
682
  } else if (cmd === 'new' && args[0] === 'series' && args.length === 3) {
624
683
  await post(`/api/series/${(await find(args[1])).series.id}/promote`, { name: args[2] });
625
684
  console.log(`made the series ${args[1].split('/')[0]}/${args[2]}`);
@@ -779,36 +838,71 @@ else if (cmd === 'comment' && args.length === 2) {
779
838
  } else if (cmd === 'connection' && args[0] === 'remove' && args[1]) {
780
839
  await api(`/connections/${encodeURIComponent(args[1])}`, { method: 'DELETE' });
781
840
  console.log('removed');
782
- } else if (cmd === 'status' && !args.length) {
841
+ } else if (cmd === 'status' && !args.length) await watch(async () => {
783
842
  const [s, ix] = await Promise.all([get('/api/status'), get('/api/indexes')]), long = Number(flags.long ?? 30);
784
- if (flags.json) console.log(JSON.stringify({ ...s, indexes: ix }, null, 1));
843
+ if (flags.json) return JSON.stringify({ ...s, indexes: ix }, null, 1);
785
844
  else {
786
845
  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' : ''}` : '';
787
- const sections = [
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` : ''}`)],
789
- [`Queued`, s.queued.map(q => `${q.path} since ${when(q.since)}: ${q.why}`)],
790
- [`Waiting`, [
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 })),
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 }))]
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)}`),
794
- ...s.expired.map(e => `${e.who} their ${e.login} login expired${e.holding.length ? `, holding ${e.holding.join(', ')}` : ''}`),
795
- ]],
796
- [`Last run failed`, s.failed.map(f => `${f.path} run ${f.run} at ${when(f.at)}: ${f.error}`)],
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)
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('; ')}`)],
799
- ].filter(([, rows]) => rows.length);
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.');
846
+ // What waits, by whom it waits on, oldest first, at most WAITING each unless --all.
847
+ const waiting = [
848
+ ...s.ownership.map(o => ({ who: 'workspace managers', kind: 'owner', path: o.path, text: o.text })),
849
+ ...s.asks.map(a => ({ who: a.who, kind: a.note ? 'note' : 'ask', since: a.since, path: a.path, text: a.text })),
850
+ ...s.requests.map(r => ({ who: r.who ?? 'anyone', kind: 'request', since: r.at, path: r.path, text: `${r.from} asks to ${r.target ? 'wake' : 'start'} ${r.label}` })),
851
+ ...s.proposals.map(p => ({ who: `${p.to}'s owners`, kind: 'proposal', since: p.at, path: p.to, text: `${p.by} proposes to ${p.kind === 'merge' ? `merge ${p.from} into it` : `move ${p.from}/${p.series} to it`}` })),
852
+ ...s.expired.map(e => ({ who: e.who, kind: 'login', path: e.holding.join(', '), text: `their ${e.login} login expired` })),
853
+ ];
854
+ const byWho = Map.groupBy(waiting.sort((a, b) => a.who.localeCompare(b.who) || (a.since ?? '').localeCompare(b.since ?? '')), w => w.who);
855
+ // One table, its columns lined up across everyone, with each person's name above their rows.
856
+ const groups = [...byWho].map(([who, ws]) => ({ who, all: ws.length, shown: flags.all ? ws : ws.slice(0, WAITING) }));
857
+ const lines = table([], groups.flatMap(g => g.shown.map(w => [w.kind, w.since ? when(w.since) : '', clip(w.path, PATH_COLS), gist(w.text, TEXT_COLS)])), ' ').split('\n');
858
+ const waits = groups.map(g => [` ${g.who} (${g.all})`, ...lines.splice(0, g.shown.length),
859
+ ...(g.shown.length < g.all ? [` … ${g.all - g.shown.length} more: rf status --all`] : [])].join('\n'));
860
+ const failing = ix.flatMap(x => x.people.filter(p => p.phase === 'crawl' || p.error).map(p => [clip(x.name, PATH_COLS), p.who,
861
+ p.error ? `failing${p.retry_at ? `, again ${when(p.retry_at)}` : ''}` : `crawling, ${p.pages} pages`, p.error ? brief(p.error, TEXT_COLS) : '']));
862
+ const sections = [
863
+ ['Running', s.running.length, table(['PATH', 'RUN', 'FOR', 'COST', ''], s.running.map(r => [clip(r.path, PATH_COLS), String(r.run), took((Date.now() - Date.parse(r.at)) / 1000),
864
+ usdNote(r.cost, r.estimated), Date.now() - Date.parse(r.at) > long * 60e3 ? `LONG, past ${long}m` : '']))],
865
+ ['Queued', s.queued.length, table(['PATH', 'SINCE', 'WHY'], s.queued.map(q => [clip(q.path, PATH_COLS), when(q.since), q.why]))],
866
+ [`Waiting on ${byWho.size} ${byWho.size === 1 ? 'person' : 'people'}`, waiting.length, waits.join('\n')],
867
+ ['Last run failed', s.failed.length, table(['PATH', 'RUN', 'AT', 'ERROR'], s.failed.map(f => [clip(f.path, PATH_COLS), String(f.run), when(f.at), brief(f.error, TEXT_COLS)]))],
868
+ ['Indexes crawling or failing', failing.length, table(['INDEX', 'PERSON', 'STATE', 'ERROR'], failing)],
869
+ ].filter(([, n]) => n) ;
870
+ const body = sections.map(([title, n, rows]) => `${title} (${n})\n${rows}`).join('\n\n');
871
+ return [lowLine, body].filter(Boolean).join('\n\n') || 'Nothing is running, queued, waiting or failed.';
802
872
  }
803
- } else if (cmd === 'indexes' && !args.length) {
873
+ });
874
+ else if (cmd === 'indexes' && !args.length) {
804
875
  const ix = await get('/api/indexes');
805
876
  if (flags.json) console.log(JSON.stringify(ix, null, 1));
806
877
  else console.log(ix.map(x => [`${x.name} ${x.kind} ${x.items} items ${(x.bytes / 2 ** 20).toFixed(1)} MB`, ...x.people.map(p =>
807
878
  ` ${p.who} ${p.phase} ${p.pages} pages caught up ${p.caught_up ? when(p.caught_up) : 'never'}${p.error ? ` ${p.retry_at ? `again ${when(p.retry_at)}` : 'stopped'}: ${p.error}` : ''}`)].join('\n')).join('\n\n') || 'No indexes.');
808
- } else if (cmd === 'runs' && args.length <= 1) {
879
+ } else if (cmd === 'runs' && args.length <= 1) await watch(async () => {
809
880
  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));
810
- if (flags.json) console.log(JSON.stringify(rows, null, 1));
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 ?? ''}`);
881
+ if (flags.json) return JSON.stringify(rows, null, 1);
882
+ return rows.length ? table(['START', 'PATH', 'RUN', 'OUTCOME', 'TIME', 'COST', 'STARTED BY', 'ERROR'], rows.map(r => [when(r.at), clip(r.path, PATH_COLS), String(r.run),
883
+ `${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 ? brief(r.error, TEXT_COLS) : '']), '') : 'No runs.';
884
+ });
885
+ else if (cmd === 'top' && !args.length) await watch(async () => {
886
+ const m = await get('/monitor');
887
+ if (flags.json) return JSON.stringify(m, null, 1);
888
+ else {
889
+ const h = m.host, at = (p ) => `${clip(p.path, PATH_COLS)} run ${p.run}`;
890
+ const procs = (ps ) => table(['PID', 'CPU', 'MEMORY', 'AGE', 'RUN', 'SCRIPT', 'COMMAND'], ps.map(p => [`${p.pid}${p.own ? '*' : ''}`, `${p.cpu}%`, mb(p.rss), took(p.age), at(p),
891
+ clip(p.script, TEXT_COLS / 2), clip(p.command, TEXT_COLS)]));
892
+ return [
893
+ `Host${h.cpus} CPUs, ${h.cpu}% busy, load ${h.load.map((l ) => l.toFixed(2)).join(' ')}, ${mb(h.memory.free)} free of ${mb(h.memory.total)}; the server ${h.server.cpu}% CPU, ${mb(h.server.rss)}`,
894
+ m.runs.length ? `Runs going (${m.runs.length})\n${table(['PATH', 'RUN', 'SERIES OWNER', 'FOR', 'PROCESSES', 'CPU', 'MEMORY'], m.runs.map((r ) => [clip(r.path, PATH_COLS), String(r.run), r.runner,
895
+ took((Date.parse(m.at) - Date.parse(r.since)) / 1000), String(r.procs), `${r.cpu}%`, mb(r.rss)]))}` : 'No run is going.',
896
+ ...(m.runs.length ? [`Top ${m.cpu.length} by CPU\n${procs(m.cpu)}`, `Top ${m.memory.length} by memory\n${procs(m.memory)}`,
897
+ "* the sandbox's own, its bwrap, Pi or its socket: rf interrupt PATH stops the run; rf kill PID ends any other, with all it started"] : []),
898
+ ].join('\n\n');
899
+ }
900
+ });
901
+ else if (cmd === 'kill' && args.length === 1 && /^\d+$/.test(args[0])) {
902
+ if (flags.start !== undefined && !/^\d+$/.test(String(flags.start))) throw new Error('--start: a whole number, as rf top --json shows a process');
903
+ const k = await (await post('/monitor/kill', { pid: Number(args[0]), ...(flags.start !== undefined && { start: Number(flags.start) }) })).json();
904
+ const more = k.pids.length - 1;
905
+ console.log(`killed ${args[0]} (${k.script})${more ? ` and the ${more} it started` : ''}, of ${k.path} run ${k.run}, with ${k.signal}; its agent hears of it`);
812
906
  } else if (cmd === 'costs' && args.length <= 1) {
813
907
  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'}`;
814
908
  // A run that was cut is carried on by the next, so it adds its cost, not a run.