barebox 0.13.0 → 0.15.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.
package/src/holds.js CHANGED
@@ -119,6 +119,8 @@ const MAX_WAITING_PER_AGENT = 16;
119
119
  * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
120
120
  * @property {{ kind: 'pay'|'send'|string, entry: string }} [floor] present when the request hit a domain the user listed in config `floor` (kind: which list, entry: the matching entry)
121
121
  * @property {import('./effect.js').Effect} [effect] present on a floor request with a body: the recipient, amount and currency fields found in it (values masked for card numbers), or why it was not read
122
+ * @property {string} [keyLast4] present on a model call whose key is not this run's: the key's last 4 characters (never more)
123
+ * @property {'none'|'other'} [modelKey] present on a model call whose key is not this run's: 'none' (no key header) or 'other' (a key, possibly too short for a last 4)
122
124
  * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
123
125
  * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
124
126
  */
@@ -130,20 +132,32 @@ const MAX_WAITING_PER_AGENT = 16;
130
132
  */
131
133
 
132
134
  /**
133
- * Atomic write: tmp file + rename, so readers never see a partial payload.
135
+ * Write `text` to a fresh 0600 temp file next to `file` (parent made on demand).
136
+ * The caller renames or links it into place.
134
137
  *
135
- * @param {string} file destination path
138
+ * @param {string} file destination path the temp file sits beside
136
139
  * @param {string} text content
137
- * @returns {void}
140
+ * @returns {string} path of the temp file
138
141
  */
139
- export function writeFileAtomic(file, text) {
142
+ export function writeTmpFile(file, text) {
140
143
  fs.mkdirSync(path.dirname(file), { recursive: true });
141
144
  const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
142
145
  // 0600, not the 0644 default: asks carry the audit trail and unredacted
143
146
  // body previews, and answers carry the decision. (Umask can only remove
144
147
  // bits from 0600, never add group/other access.)
145
148
  fs.writeFileSync(tmp, text, { mode: 0o600 });
146
- fs.renameSync(tmp, file);
149
+ return tmp;
150
+ }
151
+
152
+ /**
153
+ * Atomic write: tmp file + rename, so readers never see a partial payload.
154
+ *
155
+ * @param {string} file destination path
156
+ * @param {string} text content
157
+ * @returns {void}
158
+ */
159
+ export function writeFileAtomic(file, text) {
160
+ fs.renameSync(writeTmpFile(file, text), file);
147
161
  }
148
162
 
149
163
  let consumeN = 0;
@@ -236,8 +250,8 @@ export function normalizeDecision(input, { approveAlias = false } = {}) {
236
250
  * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
237
251
  * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
238
252
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
239
- * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
240
- * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
253
+ * @param {(entry: object, reason: string, answered: boolean, timedOut: boolean) => void} opts.onDeny refuse the parked request; `answered`: a person's answer or the hold timeout ended it (not a cancel, a close or a channel failure); `timedOut`: the hold timeout ended it (so `answered && !timedOut` is a person's answer)
254
+ * @returns {{ add: (entry: object) => string|null, dropBody: (id: string) => void, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void }) => { state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }, abandon: (id: string) => void, abandonSocket: (sock: object) => void, wait: (agent: string) => (() => void)|null, pending: () => HeldRequest[], close: () => void }} queue handle
241
255
  */
242
256
  export function createHolds({ log, timeoutMs = 120000,
243
257
  maxBody = DEFAULT_HOLD_MAX_BODY, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
@@ -309,7 +323,9 @@ export function createHolds({ log, timeoutMs = 120000,
309
323
  * @type {Map<string, { holder: object|null, line: Array<object> }>}
310
324
  */
311
325
  const slots = new Map();
312
- /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
326
+ /** Requests waiting behind another request's open model-key ask, by agent. @type {Map<string, number>} */
327
+ const waits = new Map();
328
+ /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }>} */
313
329
  const handleState = new WeakMap();
314
330
 
315
331
  /**
@@ -337,7 +353,7 @@ export function createHolds({ log, timeoutMs = 120000,
337
353
  if (!s.holder && s.line.length === 0) slots.delete(agent);
338
354
  }
339
355
  }
340
- st.onExpire(reason);
356
+ st.onExpire(reason, true, true);
341
357
  }
342
358
 
343
359
  /**
@@ -387,6 +403,8 @@ export function createHolds({ log, timeoutMs = 120000,
387
403
  truncated: entry.bodyBytes > ASK_BODY_LIMIT,
388
404
  ...(entry.floor ? { floor: entry.floor } : {}),
389
405
  ...(entry.effect ? { effect: entry.effect } : {}),
406
+ ...(entry.keyLast4 ? { keyLast4: entry.keyLast4 } : {}),
407
+ ...(entry.modelKey ? { modelKey: entry.modelKey } : {}),
390
408
  waitingSec: 0,
391
409
  // ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
392
410
  expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
@@ -412,7 +430,7 @@ export function createHolds({ log, timeoutMs = 120000,
412
430
  try { fs.unlinkSync(paths.heldFile(id)); } catch {}
413
431
  }
414
432
 
415
- function settle(id, approved, reason) {
433
+ function settle(id, approved, reason, answered = false, timedOut = false) {
416
434
  const h = queue.get(id);
417
435
  if (!h) return `unknown ${id}`;
418
436
  queue.delete(id);
@@ -426,7 +444,7 @@ export function createHolds({ log, timeoutMs = 120000,
426
444
  } else {
427
445
  dropBody(id);
428
446
  log({ ev: 'decide', id, agent: h.agent, decision, reason });
429
- onDeny(h, reason);
447
+ onDeny(h, reason, answered, timedOut);
430
448
  }
431
449
  onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
432
450
  return approved ? `approved ${id}` : `denied ${id}`;
@@ -460,15 +478,17 @@ export function createHolds({ log, timeoutMs = 120000,
460
478
  if (!useFiles) {
461
479
  /** @type {{ decision?: unknown, reason?: unknown } | null} */
462
480
  let raw = null;
481
+ let failed = false;
463
482
  try {
464
483
  raw = await onAsk(ask);
465
484
  } catch (e) {
485
+ failed = true;
466
486
  const msg = e instanceof Error ? e.message : String(e);
467
487
  raw = { decision: 'deny', reason: `onAsk failed: ${msg}` };
468
488
  }
469
489
  const norm = normalizeDecision(raw);
470
490
  if (norm && norm.decision === 'allow') settle(entry.id, true, '');
471
- else settle(entry.id, false, norm?.reason ?? 'denied');
491
+ else settle(entry.id, false, norm?.reason ?? 'denied', !failed && norm !== null);
472
492
  }
473
493
  }
474
494
 
@@ -507,7 +527,7 @@ export function createHolds({ log, timeoutMs = 120000,
507
527
  log({ ev: 'stale-answer', id, note: 'unknown or already-settled id; ignored' });
508
528
  continue;
509
529
  }
510
- settle(id, norm.decision === 'allow', norm.reason ?? '');
530
+ settle(id, norm.decision === 'allow', norm.reason ?? '', true);
511
531
  }
512
532
  }
513
533
 
@@ -525,7 +545,7 @@ export function createHolds({ log, timeoutMs = 120000,
525
545
  * parks nothing and returns `null`. Without `slot`, parks exactly as
526
546
  * before, without limit.
527
547
  *
528
- * The entry also carries `floor` and `effect` for a floor request (ask file only).
548
+ * The entry also carries `floor` and `effect` for a floor request, and `keyLast4` / `modelKey` for a model call with another key (ask file only).
529
549
  * It carries the masked `preview` and the full `bodyBytes`, never
530
550
  * the body itself (the proxy spooled it to `heldFile(id)`). `finish` is
531
551
  * the proxy's resolver for the request's pending ask: the queue never
@@ -534,7 +554,7 @@ export function createHolds({ log, timeoutMs = 120000,
534
554
  * @param {object} entry queue entry
535
555
  * @returns {string|null} hold id, or null for a finished slot
536
556
  */
537
- add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, sock, note, letter, finish, slot, arrivedAt }) {
557
+ add({ agent, method, url, preview = '', bodyBytes = 0, effect, floor, keyLast4, modelKey, sock, note, letter, finish, slot, arrivedAt }) {
538
558
  const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
539
559
  const s = slots.get(agent);
540
560
  if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
@@ -542,10 +562,10 @@ export function createHolds({ log, timeoutMs = 120000,
542
562
  const ms = deadlineMs();
543
563
  const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
544
564
  const entry = {
545
- id, agent, method, url, preview, bodyBytes, effect, floor, sock, note, letter, finish, t0,
565
+ id, agent, method, url, preview, bodyBytes, effect, floor, keyLast4, modelKey, sock, note, letter, finish, t0,
546
566
  slot: null,
547
567
  timer: ms === null ? null
548
- : setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
568
+ : setTimeout(() => settle(id, false, 'hold timeout', true, true), Math.max(0, ms - (Date.now() - t0))),
549
569
  };
550
570
  // Unref: a parked `never` hold must not keep the process alive by itself.
551
571
  if (entry.timer?.unref) entry.timer.unref();
@@ -566,7 +586,7 @@ export function createHolds({ log, timeoutMs = 120000,
566
586
  /**
567
587
  * Ask for this agent's hold slot before reading a held request's body.
568
588
  * @param {string} agent
569
- * @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
589
+ * @param {{ onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void }} cbs
570
590
  * The handle's `id` is the id its hold will have (empty when `full`), so
571
591
  * the body file can be named before the hold parks.
572
592
  * @returns {{ state: 'now'|'queued'|'full', id: string, arrivedAt: number, cancel: () => void }}
@@ -577,7 +597,7 @@ export function createHolds({ log, timeoutMs = 120000,
577
597
  // receives that same object as `slot`, so holder comparisons use it.
578
598
  // The one deadline timer lives here, armed below for 'now' and
579
599
  // 'queued' alike; expiry runs through `expireReservation` only.
580
- /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
600
+ /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string, answered?: boolean, timedOut?: boolean) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean, id: string }} */
581
601
  const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false, id: '' };
582
602
  const s0 = slots.get(agent);
583
603
  /** @type {'now'|'queued'|'full'} */
@@ -635,7 +655,7 @@ export function createHolds({ log, timeoutMs = 120000,
635
655
  removeAskFile(id);
636
656
  dropBody(id);
637
657
  log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
638
- onDeny(h, 'client gone');
658
+ onDeny(h, 'client gone', false, false);
639
659
  onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
640
660
  },
641
661
 
@@ -647,6 +667,29 @@ export function createHolds({ log, timeoutMs = 120000,
647
667
 
648
668
  dropBody,
649
669
 
670
+ /**
671
+ * A place among the agent's waiters (requests waiting behind an open model-key ask), bounded
672
+ * by the same MAX_WAITING_PER_AGENT as the hold line. The one owner of that count.
673
+ *
674
+ * @param {string} agent agent name
675
+ * @returns {(() => void)|null} the release (idempotent), or null when the agent already has the maximum waiting
676
+ */
677
+ wait(agent) {
678
+ const n = waits.get(agent) ?? 0;
679
+ if (n >= MAX_WAITING_PER_AGENT) {
680
+ log({ ev: 'hold-queue-full', agent, waiting: true });
681
+ return null;
682
+ }
683
+ waits.set(agent, n + 1);
684
+ let done = false;
685
+ return () => {
686
+ if (done) return;
687
+ done = true;
688
+ const left = (waits.get(agent) ?? 1) - 1;
689
+ if (left > 0) waits.set(agent, left); else waits.delete(agent);
690
+ };
691
+ },
692
+
650
693
  pending() { return [...queue.values()].map(pub); },
651
694
 
652
695
  close() {
package/src/launcher.js CHANGED
@@ -268,7 +268,7 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
268
268
  // same real path, so it is subsumed here.
269
269
  const same = bases.findIndex(([realBase]) => realRt === realBase);
270
270
  if (same >= 0) {
271
- const what = same === 0 ? 'HOME' : same === 1 ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
271
+ const what = roots[same] === home ? 'HOME' : roots[same] === proj ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
272
272
  throw new Error(`launch: runtime must not be ${what} itself (its sockets cannot be hidden there)`);
273
273
  }
274
274
  // Mask the sandbox-visible spelling join(root, relative(realRoot, realRt)):
package/src/lists.js CHANGED
@@ -16,7 +16,7 @@ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
16
16
  * @param {string} host a hostname
17
17
  * @returns {string} the host without one trailing dot
18
18
  */
19
- const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
19
+ export const stripDot = (host) => (host.endsWith('.') ? host.slice(0, -1) : host);
20
20
 
21
21
  /**
22
22
  * The one place a request URL is normalised: one trailing dot is stripped from the
package/src/policy.js CHANGED
@@ -34,6 +34,8 @@ const TOOLS = {
34
34
  'http.PUT': 'x',
35
35
  'http.PATCH': 'x',
36
36
  'http.DELETE': 'x',
37
+ // M14: the first-contact host ask is a flag ask (`newHost`), never a letter ask.
38
+ 'net.host': 'r',
37
39
  };
38
40
 
39
41
  /** Built-in model-call endpoints (`POST`, `r`), as endpoint-list entries. */
@@ -44,6 +46,8 @@ const MODEL_PATHS = [
44
46
  'POST api.openai.com/v1/responses',
45
47
  'POST api.openai.com/v1/embeddings',
46
48
  ];
49
+ /** Hosts of the built-in model endpoints: never a first-contact host ask (M14). */
50
+ export const MODEL_HOSTS = new Set(MODEL_PATHS.map((e) => e.slice(e.indexOf(' ') + 1).split('/')[0]));
47
51
  /** The endpoints of one local model server (`host:port`), as list entries. */
48
52
  const LOCAL_LLM_PATHS = ['/api/chat', '/api/generate', '/api/embed',
49
53
  '/v1/chat/completions', '/v1/completions'];
@@ -140,7 +144,7 @@ export function toolFor(matcher, tools, method, url, models) {
140
144
  }
141
145
 
142
146
  /** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
143
- const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
147
+ const FLAGS = { cardLike: { true: 'ask' }, newHost: { true: 'ask' }, paymentPath: { true: 'ask' }, floor: { pay: 'ask', send: 'ask' } };
144
148
 
145
149
  /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
146
150
  const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
package/src/prompt.js CHANGED
@@ -8,6 +8,7 @@
8
8
  // question open is dropped (so a `y` typed during h1 never approves h2), and
9
9
  // once a hold is decided elsewhere nothing is written for it.
10
10
  import { safe } from './runtime.js';
11
+ import { maskCards } from './cardscan.js';
11
12
  import { isEndpoint } from './lists.js';
12
13
  import { LIST_MAX } from './effect.js';
13
14
 
@@ -29,7 +30,7 @@ export const ANSI = { bold: '\x1b[1m', dim: '\x1b[2m', red: '\x1b[31m', green: '
29
30
  */
30
31
  export const paint = (on, codes, text) => (on ? `${codes}${text}${ANSI.reset}` : text);
31
32
 
32
- /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect }} AskRecord */
33
+ /** @typedef {{ id: string, agent?: string, method: string, url: string, rule: string, letter: string, bodyPreview?: string, expiresAt?: string|null, floor?: { kind: string, entry: string }, effect?: import('./effect.js').Effect, keyLast4?: string, modelKey?: 'none'|'other' }} AskRecord */
33
34
 
34
35
  /**
35
36
  * The `To:` / `Amount:` / `Currency:` lines of a floor request, or one `Effect:` line saying why none was read.
@@ -45,6 +46,7 @@ export function effectLines(effect, color) {
45
46
  if (effect.notRead !== null) return [` ${paint(color, bold, 'Effect:')} not read (${safe(effect.notRead)})`];
46
47
  /** @type {[string, { path: string, value: string }[]][]} */
47
48
  const rows = [['To:', effect.recipient], ['Amount:', effect.amount], ['Currency:', effect.currency]];
49
+ if (rows.every(([, f]) => !f.length)) return [` ${paint(color, bold, 'Effect:')} body read, no recipient, amount or currency field recognised`];
48
50
  return rows.filter(([, f]) => f.length).map(([label, f]) => {
49
51
  const shown = f.length > LIST_MAX
50
52
  ? `more than ${LIST_MAX} fields (not listed: too many to tell the real one)`
@@ -53,6 +55,26 @@ export function effectLines(effect, color) {
53
55
  });
54
56
  }
55
57
 
58
+ /** The most characters of a new host's URL path and query a question shows. */
59
+ const URL_CHARS = 200;
60
+
61
+ /**
62
+ * The URL of an ask, sanitized. For a first-contact host ask (`flags.newHost`) everything after the
63
+ * scheme (userinfo, host, path and query) has card numbers masked, then is cut to 200 characters and the
64
+ * full length is added, so a long URL is visible but bounded. The question's header line shows the true host.
65
+ *
66
+ * @param {AskRecord} ask the parked request
67
+ * @returns {string} the URL text, safe for a terminal
68
+ */
69
+ export function askUrl(ask) {
70
+ if (safe(ask.rule) !== 'flags.newHost') return safe(ask.url);
71
+ const url = String(ask.url ?? '');
72
+ const head = /^[a-z][a-z0-9+.-]*:\/\//i.exec(url)?.[0] ?? '';
73
+ // Mask card numbers before the cut, so a number the cut would split is still masked.
74
+ const rest = maskCards(url.slice(head.length));
75
+ return safe(rest.length > URL_CHARS ? `${head}${rest.slice(0, URL_CHARS)}… (${url.length} chars)` : `${head}${rest}`);
76
+ }
77
+
56
78
  /**
57
79
  * The ` floor=<kind> entry=<entry>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); empty without a floor hit.
58
80
  *
@@ -63,6 +85,17 @@ export function floorTail(ask) {
63
85
  return ask.floor ? ` floor=${safe(ask.floor.kind)} entry=${safe(ask.floor.entry)}` : '';
64
86
  }
65
87
 
88
+ /**
89
+ * The ` key=…<last 4>` tail of a one-line ask (`sbx pending`, the non-terminal `ask` line); ` key=none` or ` key=other` when there is no last 4 to show; empty unless the ask is a model call with another key.
90
+ *
91
+ * @param {AskRecord} ask the parked request
92
+ * @returns {string} the tail, or ''
93
+ */
94
+ export function keyTail(ask) {
95
+ if (ask.keyLast4) return ` key=…${safe(ask.keyLast4)}`;
96
+ return ask.modelKey ? ` key=${ask.modelKey}` : '';
97
+ }
98
+
66
99
  /**
67
100
  * Plain-language lines for one ask record. Every agent-controlled byte goes
68
101
  * through `safe()`.
@@ -84,8 +117,12 @@ export function questionLines(ask, now = Date.now(), color = false) {
84
117
  const rule = safe(ask.rule);
85
118
  const why = rule === 'flags.floor' && ask.floor
86
119
  ? `${ask.floor.kind === 'send' ? 'a send' : 'a payment'} to ${isEndpoint(ask.floor.entry) ? 'an endpoint' : 'a domain'} you listed (${safe(ask.floor.entry)})`
120
+ : rule === 'flags.newHost' ? 'a host new in this run (allow means for this run only)'
87
121
  : rule === 'flags.cardLike' ? 'it contains what looks like a card number'
88
122
  : rule === 'flags.paymentPath' ? 'the address looks like a payment'
123
+ : ask.keyLast4 ? `a model call with a key that is not this run's (…${safe(ask.keyLast4)})`
124
+ : ask.modelKey === 'none' ? 'a model call with no key'
125
+ : ask.modelKey ? "a model call with a key that is not this run's"
89
126
  : ask.letter === 'w' ? 'a change (reversible: the vendor says it can be undone)'
90
127
  : ask.letter === 'x' ? "a change barebox can't undo"
91
128
  : rule;
@@ -97,7 +134,7 @@ export function questionLines(ask, now = Date.now(), color = false) {
97
134
  const lines = [
98
135
  head,
99
136
  ` ${paint(color, bold, 'Why:')} ${why}`,
100
- ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${safe(ask.url)}`)}`,
137
+ ` ${paint(color, bold, 'URL:')} ${paint(color, cyan, `${method} ${askUrl(ask)}`)}`,
101
138
  ];
102
139
  lines.push(...effectLines(ask.effect, color));
103
140
  const body = safe(ask.bodyPreview).slice(0, BODY_CHARS);