gcf-board 0.22.0 → 0.23.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.
@@ -1,17 +1,11 @@
1
1
  // The account's usage limits, asked of Claude's `/usage` (Board-PRD decision 39): what the top
2
2
  // bar shows over the last limit a run reported. The command is free (no model call) and answers
3
3
  // in a second or two; it still starts a claude process, so it is asked only while a page is open.
4
- import { spawn, spawnSync } from 'node:child_process';
5
- import os from 'node:os';
4
+ import { lastReading, limitsOf as sessionLimitsOf, readUsage, reasonOf as sessionReasonOf, } from 'gcf-session';
6
5
  import { broadcast, watched } from './events.js';
7
6
  /** How often an open page's bar is read again, and how long one ask may take. */
8
7
  export const USAGE_EVERY_MS = 5 * 60_000;
9
8
  const ASK_TIMEOUT_MS = 30_000;
10
- // No user or local settings, no MCP, no saved session: the user's hooks and plugins do not run
11
- // for a reading, and the operator's session list gets no entry per ask. The cwd is the temp
12
- // folder, whose project settings are no one's.
13
- const FLAGS = '-p "/usage" --output-format stream-json --verbose --no-session-persistence ' +
14
- '--setting-sources project --strict-mcp-config';
15
9
  let command = null;
16
10
  let askTimeout = ASK_TIMEOUT_MS;
17
11
  let last = null;
@@ -33,48 +27,14 @@ export function configureUsage(agent, timeoutMs = ASK_TIMEOUT_MS) {
33
27
  }
34
28
  /** The last reading, with the last ask's failure when the ask after it failed; null before any. */
35
29
  export const lastUsage = () => last;
36
- const isLimit = (l) => typeof l === 'object' &&
37
- l !== null &&
38
- typeof l.kind === 'string' &&
39
- typeof l.percent === 'number';
30
+ /** The limits of `/usage`'s answer (gcf-session `limitsOf`). */
31
+ export const limitsOf = (out) => sessionLimitsOf(out);
32
+ /** Why an ask failed (gcf-session `reasonOf`), with this board's ask time. */
33
+ export const reasonOf = (e, err) => sessionReasonOf(e, err, askTimeout);
40
34
  /**
41
- * The limits of `/usage`'s stream-json answer: its assistant event's
42
- * `usage_report.rate_limits.limits`; null when no line carries them (an API-key account has no
43
- * plan limits, an older claude no report).
44
- */
45
- export function limitsOf(out) {
46
- for (const line of out.split(/\r?\n/)) {
47
- let e;
48
- try {
49
- e = JSON.parse(line);
50
- }
51
- catch {
52
- continue;
53
- }
54
- const limits = e?.usage_report?.rate_limits?.limits;
55
- if (Array.isArray(limits))
56
- return limits.filter(isLimit);
57
- }
58
- return null;
59
- }
60
- /**
61
- * Why an ask failed: a timeout, else the last two lines of its stderr (cmd's "not recognized"
62
- * spans two), else the error itself.
63
- */
64
- export function reasonOf(e, err) {
65
- if (!e)
66
- return 'claude answered /usage without the plan limits (an API key has none)';
67
- // A stuck ask is told by its timeout, not by a warning it printed before it hung.
68
- if (e.killed)
69
- return `no answer in ${askTimeout / 1000} s`;
70
- const tail = err.trim();
71
- if (tail)
72
- return tail.split(/\r?\n/).slice(-2).join(' ').slice(0, 300);
73
- return e.message.slice(0, 300);
74
- }
75
- /**
76
- * Ask `/usage` now, once at a time: a second ask while one goes waits for it. A reading tells
77
- * every page (`quota`); a failed ask keeps the last reading and says why beside it.
35
+ * Ask `/usage` now, once at a time: a second ask while one goes waits for it. The reading goes to
36
+ * the account's `usage.json`, which the runs read too (Hold-Plan d10), and tells every page
37
+ * (`quota`); a failed ask keeps the last reading and says why beside it.
78
38
  */
79
39
  export function askUsage() {
80
40
  if (!command)
@@ -83,70 +43,50 @@ export function askUsage() {
83
43
  return asking;
84
44
  askedAt = Date.now();
85
45
  const mine = generation;
86
- asking = new Promise((resolve) => {
87
- let late = false;
88
- let out = '';
89
- let err = '';
90
- const windows = process.platform === 'win32';
91
- // Off Windows the shell leads a group of its own: a timeout signals the group, so a claude
92
- // the shell forked ends with it.
93
- const child = spawn(`${command} ${FLAGS}`, {
94
- shell: true,
95
- cwd: os.tmpdir(),
96
- windowsHide: true,
97
- detached: !windows,
98
- });
99
- // The answer is a few KB; a runaway one keeps its last 4 MB. Text, so a character split
100
- // between two chunks comes whole.
101
- const keep = (s, d) => (s + d).slice(-(4 << 20));
102
- child.stdout.setEncoding('utf8').on('data', (d) => (out = keep(out, d)));
103
- child.stderr.setEncoding('utf8').on('data', (d) => (err = keep(err, d)));
104
- let ended = false;
105
- // A spawn error is followed by a close: the first one tells.
106
- const done = (e) => {
107
- if (ended)
108
- return;
109
- ended = true;
110
- clearTimeout(timer);
111
- if (mine !== generation)
112
- return resolve();
113
- const limits = limitsOf(out);
114
- const at = new Date().toISOString();
115
- const why = e && late ? Object.assign(e, { killed: true }) : e;
116
- if (limits)
117
- last = { at, limits };
118
- else
119
- last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(why, err) } };
120
- asking = null;
121
- broadcast({ type: 'quota' });
122
- resolve();
123
- };
124
- child.on('error', done);
125
- child.on('close', (code, signal) => done(code === 0 ? null : new Error(`${command} /usage ended with ${code ?? signal}`)));
126
- // Not the shell alone: on Windows a killed shell leaves the claude under it running.
127
- const timer = setTimeout(() => {
128
- late = true;
129
- if (!child.pid)
130
- return;
131
- if (windows)
132
- spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
133
- else
134
- try {
135
- process.kill(-child.pid, 'SIGKILL');
136
- }
137
- catch {
138
- // The group ended on its own meanwhile.
139
- }
140
- // A process outside the tree that holds the pipes would hold the ask for good: the board
141
- // would read no quota until its restart.
142
- child.stdout.destroy();
143
- child.stderr.destroy();
144
- }, askTimeout).unref();
46
+ const agent = command;
47
+ // Through the account's lock and file (Codex review): a run's ask at the same time is the same.
48
+ asking = readUsage({ command: agent, maxAgeMs: 0, timeoutMs: askTimeout })
49
+ .then((reading) => reading,
50
+ // A folder or a lock the board cannot write: a failed ask, said beside the last reading.
51
+ (e) => ({
52
+ ...(last ?? { at: null, limits: [] }),
53
+ failed: { at: new Date().toISOString(), error: e.message.slice(0, 300) },
54
+ }))
55
+ .then((reading) => {
56
+ if (mine !== generation)
57
+ return;
58
+ last = reading;
59
+ asking = null;
60
+ broadcast({ type: 'quota' });
61
+ afterRead();
145
62
  });
146
63
  return asking;
147
64
  }
148
- /** Ask when a page is open and the last ask is older than `everyMs`. */
65
+ /** What else needs a reading with no page open: the automation standing on the reserve (d11). */
66
+ let needed = () => false;
67
+ export function needUsageWhen(fn) {
68
+ needed = fn;
69
+ }
70
+ /** What a new reading wakes: the queues and autopilots the reserve held (runs.ts). */
71
+ let afterRead = () => { };
72
+ export function onUsageRead(fn) {
73
+ afterRead = fn;
74
+ }
75
+ /**
76
+ * Ask when a page is open, or the automation stands on the reserve, and the last reading - this
77
+ * board's or a run's in `usage.json` - is older than `everyMs`.
78
+ */
149
79
  export function askIfDue(everyMs = USAGE_EVERY_MS, now = Date.now()) {
150
- if (command && watched() && now - askedAt >= everyMs)
80
+ if (!command || !(watched() || needed()))
81
+ return;
82
+ const kept = lastReading();
83
+ const keptAt = kept?.at ? Date.parse(kept.at) : 0;
84
+ if (keptAt > askedAt && now - keptAt < everyMs && !kept?.failed) {
85
+ last = kept;
86
+ askedAt = keptAt;
87
+ afterRead();
88
+ return;
89
+ }
90
+ if (now - askedAt >= everyMs)
151
91
  void askUsage();
152
92
  }