bare-agent 0.59.0 → 0.60.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.
@@ -25,48 +25,12 @@
25
25
 
26
26
  const { Loop } = require('./loop');
27
27
  const { HaltError } = require('./errors');
28
+ const { classifySystem, SCAN_WINDOW, SCAN_PASSES } = require('./recurse-prompts');
28
29
 
29
- // §9.2.1 LOCKED defaults. WINDOW is the one calibrated number (RECALL knee ≈ 8, per-model — calibrate via the
30
- // active half-window probe, NOT context size); PASSES=2 (shuffled-boundary union → recall ~0.91, precision
31
- // ~0.98). KNN_K is litectx's embeddings-nominate cap for the search handle.
32
- const SCAN_WINDOW = 8;
33
- const SCAN_PASSES = 2;
30
+ // KNN_K is litectx's embeddings-nominate cap for the search handle (SCAN_WINDOW/SCAN_PASSES/classifySystem live in
31
+ // recurse-prompts.js — shared with the recurse() classify tool).
34
32
  const KNN_K = 8;
35
33
 
36
- // Completeness-contract guard (RC-9 applied to retrieval): a goal/contract implying COMPLETENESS must never be
37
- // answered by a capped `search` (which cannot count). Auto-detection may only UPGRADE to scan (the safe
38
- // direction), NEVER silently downgrade. Deliberately broad on the "how many / all" family the PRD names.
39
- const COMPLETENESS_RE =
40
- /\b(all|every|each|how many|count|counts|counting|total|number of|list all|exhaustive|complete(?:ly)?)\b/i;
41
-
42
- /**
43
- * Does this text imply a completeness ("all / every / count / how many") ask? Used to upgrade a capped search
44
- * to a scan (the only complete path). Conservative by design — a false positive only costs a thorough scan.
45
- * @param {unknown} text
46
- * @returns {boolean}
47
- */
48
- function impliesCompleteness(text) {
49
- return typeof text === 'string' && COMPLETENESS_RE.test(text);
50
- }
51
-
52
- /**
53
- * The §9.2-validated classify system prompt, GENERALIZED from the POC's hardcoded "SPORTS news" predicate to
54
- * an arbitrary one. The load-bearing wording is verbatim ("Examine EACH item individually", "Output ONLY the
55
- * IDs", "Comma-separated. If none, output 'none'. No count, no prose.") — the predicate is the only variable.
56
- * It MUST return ids, not a count: counting is CODE's job (RC-5 / §9.1), so the judge never does arithmetic.
57
- * @param {string} predicate - The task/goal the items are judged against.
58
- * @returns {string}
59
- */
60
- function classifySystem(predicate) {
61
- return (
62
- 'You are a precise classifier. Examine EACH item individually. Each item is shown on its own line as ' +
63
- '`<id> => <text>`. Output ONLY the IDs of the items that match the predicate below — copy each matching ' +
64
- 'item\'s <id> VERBATIM (the exact characters before " => "; an id may itself contain ":" — keep all of ' +
65
- 'it). Comma-separated. If none, output "none". No count, no prose.\n\nPREDICATE: ' +
66
- predicate
67
- );
68
- }
69
-
70
34
  /**
71
35
  * @typedef {object} Slice
72
36
  * @property {string} id - Stable, word-like id (no whitespace/commas — it is echoed back by the judge).
@@ -183,17 +147,17 @@ function normalizeCorpus(corpus) {
183
147
  /**
184
148
  * The `search` handle tool (RC-5 needle path): litectx `recall` — embeddings ON, `fact`/`episode` (the
185
149
  * KNN-nominate kinds), capped at `KNN_K`. For FINDING the relevant few; the description tells the worker it
186
- * CANNOT count (the completeness guard catches a "how many" ask before this tool is ever offered). Returns the
150
+ * CANNOT count (use recurse()'s built-in `classify` for "how many"). Returns the
187
151
  * matched items' bodies as text the worker reads; never the whole corpus.
188
152
  * @param {{recall: Function}} litectx
189
153
  * @param {{kinds?: string[], n?: number}} [opts]
190
154
  * @returns {ToolDef}
191
155
  * @category integration
192
156
  * @when you want to give a recurse worker a needle-search handle over litectx (embeddings recall for the relevant few) — for FINDING, never counting
193
- * @fails returns matched bodies only and CANNOT count (the completeness guard blocks a "how many" ask before it is offered); a dead window yields nothing, never a fabricated hit.
157
+ * @fails returns matched bodies only and CANNOT count (use classify for "how many"); a dead window yields nothing, never a fabricated hit.
194
158
  * @example
195
159
  * const tool = buildSearchTool(litectx, { n: 8 });
196
- * await recurse(task, ctx, { retrieval: 'search', tools: [tool] });
160
+ * await recurse(task, ctx, { tools: [tool] });
197
161
  */
198
162
  function buildSearchTool(litectx, opts = {}) {
199
163
  const kinds = Array.isArray(opts.kinds) && opts.kinds.length ? opts.kinds : ['fact', 'episode'];
@@ -234,7 +198,7 @@ function buildSearchTool(litectx, opts = {}) {
234
198
  * @fails only as good as a lexical rule; complete over the slices it is given (no recall cap) but matches nothing outside them.
235
199
  * @example
236
200
  * const tool = buildExactTool(corpus);
237
- * await recurse(task, ctx, { retrieval: 'exact', tools: [tool] });
201
+ * await recurse(task, ctx, { input: corpus, tools: [tool] });
238
202
  */
239
203
  function buildExactTool(corpus) {
240
204
  const slices = normalizeCorpus(corpus);
@@ -354,11 +318,11 @@ const ENUM_PAGE = 200;
354
318
  * @param {{kind?: 'fact'|'episode', pageSize?: number}} [opts]
355
319
  * @returns {() => Promise<Slice[]>}
356
320
  * @category integration
357
- * @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding scan/partition
321
+ * @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding recurse({ input })
358
322
  * @fails never ingests a fresh corpus (strictly worse than scanning an in-hand array); returns an async source materialized once and cached.
359
323
  * @example
360
324
  * const corpus = litectxCorpus(litectx, { kind: 'fact' });
361
- * await recurse(task, ctx, { mode: 'partition', corpus });
325
+ * await recurse(task, ctx, { input: corpus, kind: 'count' });
362
326
  */
363
327
  function litectxCorpus(litectx, opts = {}) {
364
328
  const kind = opts.kind === 'episode' ? 'episode' : 'fact'; // enumerate v1 is the memory axis (fact/episode)
@@ -377,18 +341,4 @@ function litectxCorpus(litectx, opts = {}) {
377
341
  };
378
342
  }
379
343
 
380
- module.exports = {
381
- scanCount,
382
- judgeWindow,
383
- classifySystem,
384
- impliesCompleteness,
385
- normalizeCorpus,
386
- buildSearchTool,
387
- buildExactTool,
388
- buildScanTool,
389
- litectxCorpus,
390
- rotate,
391
- SCAN_WINDOW,
392
- SCAN_PASSES,
393
- KNN_K,
394
- };
344
+ module.exports = { buildSearchTool, buildExactTool, buildScanTool, litectxCorpus, scanCount, judgeWindow, normalizeCorpus, rotate, KNN_K };
@@ -0,0 +1,111 @@
1
+ export type Counter = {
2
+ limits: ResolvedLimits;
3
+ unbraked: boolean;
4
+ /**
5
+ * - the top counter (only its return carries `metrics`).
6
+ */
7
+ isRoot: boolean;
8
+ /**
9
+ * - count ONE generate; throws a `brake:maxCalls` HaltError at the cap (before spend).
10
+ */
11
+ take: () => void;
12
+ /**
13
+ * - meter a finished call.
14
+ */
15
+ record: (usage: any, result: any, model: string | null, rates?: any) => void;
16
+ /**
17
+ * - a view that can only TIGHTEN: min(parent remaining, requested).
18
+ */
19
+ child: (requested?: number) => Counter;
20
+ /**
21
+ * - throws `brake:maxWidth` when a fan-out is wider than maxWidth.
22
+ */
23
+ checkWidth: (n: number) => void;
24
+ /**
25
+ * - false at/after maxDepth (stop OFFERING spawn).
26
+ */
27
+ canSpawn: (depth: number) => boolean;
28
+ metrics: () => {
29
+ calls: number;
30
+ tokens: {
31
+ input: number;
32
+ output: number;
33
+ cacheCreation: number;
34
+ cacheRead: number;
35
+ };
36
+ costUsd: number | null;
37
+ };
38
+ };
39
+ export type ResolvedLimits = {
40
+ maxDepth: number;
41
+ maxCalls: number;
42
+ maxWidth: number;
43
+ maxRounds: number;
44
+ /**
45
+ * - true for `limits:'none'` (caps are Infinity; every return carries `unbraked:true`).
46
+ */
47
+ unbraked: boolean;
48
+ };
49
+ /**
50
+ * Validate + default the caller's `limits`. Undefined/null => brakes ON at the defaults; `'none'` => unbraked.
51
+ * `maxCalls` is TIGHTEN-ONLY: effective = min(formula, caller). Depth/width/rounds are caller-settable.
52
+ * Errors name the problem by type, never echo the offending value.
53
+ * @param {any} limits
54
+ * @param {{items?: number, window?: number, passes?: number, verifyCalls?: number}} [sizing] - feeds the formula.
55
+ * @returns {ResolvedLimits}
56
+ */
57
+ export function resolveLimits(limits: any, sizing?: {
58
+ items?: number;
59
+ window?: number;
60
+ passes?: number;
61
+ verifyCalls?: number;
62
+ }): ResolvedLimits;
63
+ /**
64
+ * Formula cap on LLM calls, computed by code from the caller's own sizing (never a guess at the model).
65
+ * @param {{items?: number, window?: number, passes?: number, maxRounds?: number, verifyCalls?: number}} [p]
66
+ * @returns {number}
67
+ */
68
+ export function formulaCap({ items, window, passes, maxRounds, verifyCalls }?: {
69
+ items?: number;
70
+ window?: number;
71
+ passes?: number;
72
+ maxRounds?: number;
73
+ verifyCalls?: number;
74
+ }): number;
75
+ /**
76
+ * @typedef {object} Counter
77
+ * @property {ResolvedLimits} limits
78
+ * @property {boolean} unbraked
79
+ * @property {boolean} isRoot - the top counter (only its return carries `metrics`).
80
+ * @property {() => void} take - count ONE generate; throws a `brake:maxCalls` HaltError at the cap (before spend).
81
+ * @property {(usage: any, result: any, model: string|null, rates?: any) => void} record - meter a finished call.
82
+ * @property {(requested?: number) => Counter} child - a view that can only TIGHTEN: min(parent remaining, requested).
83
+ * @property {(n: number) => void} checkWidth - throws `brake:maxWidth` when a fan-out is wider than maxWidth.
84
+ * @property {(depth: number) => boolean} canSpawn - false at/after maxDepth (stop OFFERING spawn).
85
+ * @property {() => {calls: number, tokens: {input: number, output: number, cacheCreation: number, cacheRead: number}, costUsd: number|null}} metrics
86
+ */
87
+ /**
88
+ * Create the shared counter for one run. Keep it in a closure: tools and the model only ever hold a wrapped provider.
89
+ * @param {ResolvedLimits} limits
90
+ * @param {{rates?: any}} [opts]
91
+ * @returns {Counter}
92
+ */
93
+ export function makeCounter(limits: ResolvedLimits, { rates }?: {
94
+ rates?: any;
95
+ }): Counter;
96
+ /**
97
+ * Wrap a provider so every `generate` is counted against `counter` BEFORE the inner call. The wrapper inherits
98
+ * the inner provider (prototype chain) so `model`, `ownsCycle`, `policy` etc. survive; only `generate` is replaced.
99
+ * `maxRounds` (optional) bounds the calls through THIS wrapper (one node's rounds), brake `maxRounds`.
100
+ * @template {{generate: Function}} P
101
+ * @param {P} provider
102
+ * @param {Counter} counter
103
+ * @param {{maxRounds?: number, rates?: any}} [opts]
104
+ * @returns {P}
105
+ */
106
+ export function countingProvider<P extends {
107
+ generate: Function;
108
+ }>(provider: P, counter: Counter, { maxRounds, rates }?: {
109
+ maxRounds?: number;
110
+ rates?: any;
111
+ }): P;
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ // recurse() v2 brakes (docs/product/rlm-prd.md §0.1): counting-only structural limits. Money, tokens and
4
+ // wall-clock stay with bareguard — this module only meters CALLS. ONE shared counter lives in a closure the
5
+ // model never sees; every `generate` in the tree (worker, sub-call, judge, verify) crosses a wrapped provider.
6
+
7
+ const { HaltError, ValidationError } = require('./errors');
8
+ const { resolveRoundCost } = require('./loop');
9
+
10
+ /**
11
+ * @typedef {object} ResolvedLimits
12
+ * @property {number} maxDepth
13
+ * @property {number} maxCalls
14
+ * @property {number} maxWidth
15
+ * @property {number} maxRounds
16
+ * @property {boolean} unbraked - true for `limits:'none'` (caps are Infinity; every return carries `unbraked:true`).
17
+ */
18
+
19
+ const DEFAULTS = { maxDepth: 1, maxWidth: 16, maxRounds: 20 };
20
+ const KEYS = ['maxDepth', 'maxCalls', 'maxWidth', 'maxRounds'];
21
+ const HEADROOM = 1.25;
22
+
23
+ /**
24
+ * Formula cap on LLM calls, computed by code from the caller's own sizing (never a guess at the model).
25
+ * @param {{items?: number, window?: number, passes?: number, maxRounds?: number, verifyCalls?: number}} [p]
26
+ * @returns {number}
27
+ */
28
+ function formulaCap({ items = 0, window = 8, passes = 2, maxRounds = DEFAULTS.maxRounds, verifyCalls = 0 } = {}) {
29
+ return Math.ceil((Math.ceil(items / window) * passes + maxRounds) * HEADROOM) + verifyCalls;
30
+ }
31
+
32
+ /**
33
+ * Validate + default the caller's `limits`. Undefined/null => brakes ON at the defaults; `'none'` => unbraked.
34
+ * `maxCalls` is TIGHTEN-ONLY: effective = min(formula, caller). Depth/width/rounds are caller-settable.
35
+ * Errors name the problem by type, never echo the offending value.
36
+ * @param {any} limits
37
+ * @param {{items?: number, window?: number, passes?: number, verifyCalls?: number}} [sizing] - feeds the formula.
38
+ * @returns {ResolvedLimits}
39
+ */
40
+ function resolveLimits(limits, sizing = {}) {
41
+ if (limits === 'none') {
42
+ return { maxDepth: Infinity, maxCalls: Infinity, maxWidth: Infinity, maxRounds: Infinity, unbraked: true };
43
+ }
44
+ if (limits != null && (typeof limits !== 'object' || Array.isArray(limits))) {
45
+ throw new ValidationError(`recurse: limits must be an object or 'none', got ${Array.isArray(limits) ? 'array' : typeof limits}`);
46
+ }
47
+ const given = limits || {};
48
+ for (const k of Object.keys(given)) {
49
+ if (!KEYS.includes(k)) throw new ValidationError('recurse: limits has an unknown key');
50
+ const v = given[k];
51
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
52
+ throw new ValidationError(`recurse: limits.${k} must be a finite number >= 0, got ${typeof v}${typeof v === 'number' ? ' (not finite or negative)' : ''}`);
53
+ }
54
+ }
55
+ const maxRounds = given.maxRounds ?? DEFAULTS.maxRounds;
56
+ const cap = formulaCap({ ...sizing, maxRounds });
57
+ return {
58
+ maxDepth: given.maxDepth ?? DEFAULTS.maxDepth,
59
+ maxCalls: given.maxCalls == null ? cap : Math.min(cap, given.maxCalls),
60
+ maxWidth: given.maxWidth ?? DEFAULTS.maxWidth,
61
+ maxRounds,
62
+ unbraked: false,
63
+ };
64
+ }
65
+
66
+ const trip = (name) => new HaltError(`[brake:${name}]`, { rule: `brake:${name}` });
67
+
68
+ /**
69
+ * @typedef {object} Counter
70
+ * @property {ResolvedLimits} limits
71
+ * @property {boolean} unbraked
72
+ * @property {boolean} isRoot - the top counter (only its return carries `metrics`).
73
+ * @property {() => void} take - count ONE generate; throws a `brake:maxCalls` HaltError at the cap (before spend).
74
+ * @property {(usage: any, result: any, model: string|null, rates?: any) => void} record - meter a finished call.
75
+ * @property {(requested?: number) => Counter} child - a view that can only TIGHTEN: min(parent remaining, requested).
76
+ * @property {(n: number) => void} checkWidth - throws `brake:maxWidth` when a fan-out is wider than maxWidth.
77
+ * @property {(depth: number) => boolean} canSpawn - false at/after maxDepth (stop OFFERING spawn).
78
+ * @property {() => {calls: number, tokens: {input: number, output: number, cacheCreation: number, cacheRead: number}, costUsd: number|null}} metrics
79
+ */
80
+
81
+ /**
82
+ * Create the shared counter for one run. Keep it in a closure: tools and the model only ever hold a wrapped provider.
83
+ * @param {ResolvedLimits} limits
84
+ * @param {{rates?: any}} [opts]
85
+ * @returns {Counter}
86
+ */
87
+ function makeCounter(limits, { rates } = {}) {
88
+ /** @type {{used: number, tokens: any, cost: number, unpriced: boolean, tripped: string|null}} */
89
+ const root = { used: 0, tokens: { input: 0, output: 0, cacheCreation: 0, cacheRead: 0 }, cost: 0, unpriced: false, tripped: null };
90
+ /** @param {{limit: number, used: number, parent: any}} node @returns {Counter} */
91
+ const view = (node) => {
92
+ const chain = () => { const c = []; for (let n = node; n; n = n.parent) c.push(n); return c; };
93
+ return {
94
+ limits,
95
+ unbraked: limits.unbraked,
96
+ isRoot: node.parent === null,
97
+ take() {
98
+ if (root.tripped) throw trip(root.tripped); // once tripped, every later call halts at zero spend
99
+ for (const n of chain()) {
100
+ if (n.used >= n.limit) { root.tripped = 'maxCalls'; throw trip('maxCalls'); }
101
+ }
102
+ for (const n of chain()) n.used++;
103
+ root.used++;
104
+ },
105
+ record(usage, result, model, r = rates) {
106
+ const { cost } = resolveRoundCost(result, model, usage || null, r || null);
107
+ if (cost === null) root.unpriced = true; else root.cost += cost;
108
+ if (usage) {
109
+ root.tokens.input += usage.inputTokens || 0;
110
+ root.tokens.output += usage.outputTokens || 0;
111
+ root.tokens.cacheCreation += usage.cacheCreationTokens || 0;
112
+ root.tokens.cacheRead += usage.cacheReadTokens || 0;
113
+ }
114
+ },
115
+ child(requested) {
116
+ const remaining = Math.max(0, node.limit - node.used);
117
+ const lim = typeof requested === 'number' && requested >= 0 ? Math.min(remaining, requested) : remaining;
118
+ return view({ limit: lim, used: 0, parent: node });
119
+ },
120
+ checkWidth(n) {
121
+ if (n > limits.maxWidth) { root.tripped = root.tripped || 'maxWidth'; throw trip('maxWidth'); }
122
+ },
123
+ canSpawn: (depth) => depth < limits.maxDepth,
124
+ // `root.used` is the whole tree's total regardless of which view reads it.
125
+ metrics: () => ({ calls: root.used, tokens: { ...root.tokens }, costUsd: root.unpriced ? null : root.cost }),
126
+ };
127
+ };
128
+ return view({ limit: limits.maxCalls, used: 0, parent: null });
129
+ }
130
+
131
+ /**
132
+ * Wrap a provider so every `generate` is counted against `counter` BEFORE the inner call. The wrapper inherits
133
+ * the inner provider (prototype chain) so `model`, `ownsCycle`, `policy` etc. survive; only `generate` is replaced.
134
+ * `maxRounds` (optional) bounds the calls through THIS wrapper (one node's rounds), brake `maxRounds`.
135
+ * @template {{generate: Function}} P
136
+ * @param {P} provider
137
+ * @param {Counter} counter
138
+ * @param {{maxRounds?: number, rates?: any}} [opts]
139
+ * @returns {P}
140
+ */
141
+ function countingProvider(provider, counter, { maxRounds = counter.limits.maxRounds, rates } = {}) {
142
+ let rounds = 0;
143
+ const wrapped = Object.create(provider);
144
+ wrapped.generate = async function generate(...args) {
145
+ if (++rounds > maxRounds) throw trip('maxRounds');
146
+ counter.take();
147
+ const r = await provider.generate(...args);
148
+ counter.record(r && r.usage, r, (r && r.model) || /** @type {any} */ (provider).model || null, rates);
149
+ return r;
150
+ };
151
+ return wrapped;
152
+ }
153
+
154
+ module.exports = { resolveLimits, formulaCap, makeCounter, countingProvider };
@@ -0,0 +1,43 @@
1
+ export type ToolDef = import("../types").ToolDef;
2
+ /**
3
+ * Build the env for ONE node. `ctx`/`opts` are the caller's; `child(prompt, piece)` runs a full recurse one level
4
+ * down (shared counter) and is only called while `counter.canSpawn(depth + 1)`.
5
+ * @param {{input: any, kind: string, node: any, counter: import('./recurse-brakes').Counter, depth: number, ctx: any, opts: any, provider: any, child: (prompt: string, piece: any) => Promise<any>}} r
6
+ * @returns {{tools: ToolDef[], state: {final: any, wrong: string|null}, setLoop: (l: any) => void}}
7
+ */
8
+ export function makeEnv({ input, kind, node, counter, depth, ctx, opts, provider, child }: {
9
+ input: any;
10
+ kind: string;
11
+ node: any;
12
+ counter: import("./recurse-brakes").Counter;
13
+ depth: number;
14
+ ctx: any;
15
+ opts: any;
16
+ provider: any;
17
+ child: (prompt: string, piece: any) => Promise<any>;
18
+ }): {
19
+ tools: ToolDef[];
20
+ state: {
21
+ final: any;
22
+ wrong: string | null;
23
+ };
24
+ setLoop: (l: any) => void;
25
+ };
26
+ /**
27
+ * Normalize the caller's `input`: strings pass through; `Slice[]` keeps well-formed `{id,text}` with a unique id that
28
+ * contains no whitespace/comma (the judge echoes ids back — such an id cannot be matched and would silently undercount).
29
+ * Everything else is DROPPED and COUNTED (`dropped`), never silently miscounted.
30
+ * @param {any} raw
31
+ * @returns {{input: string|Array<{id: string, text: string}>|null, dropped: number}}
32
+ */
33
+ export function normalizeInput(raw: any): {
34
+ input: string | Array<{
35
+ id: string;
36
+ text: string;
37
+ }> | null;
38
+ dropped: number;
39
+ };
40
+ /** Metadata line the root prompt shows INSTEAD of the input (type, size, 200-char prefix). */
41
+ export function describeInput(input: string | any[] | null): string | null;
42
+ export const KINDS: string[];
43
+ export function hasWork(v: any): boolean;