bare-agent 0.58.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.
- package/README.md +2 -2
- package/bareagent.context.md +32 -61
- package/index.d.ts +2 -5
- package/index.js +2 -5
- package/package.json +5 -1
- package/primitives.json +23 -14
- package/src/bareguard-adapter.js +2 -0
- package/src/{recurse-retrieval.d.ts → recurse-adapters.d.ts} +71 -89
- package/src/{recurse-retrieval.js → recurse-adapters.js} +10 -60
- package/src/recurse-brakes.d.ts +111 -0
- package/src/recurse-brakes.js +154 -0
- package/src/recurse-env.d.ts +43 -0
- package/src/recurse-env.js +233 -0
- package/src/recurse-finish.d.ts +46 -0
- package/src/recurse-finish.js +123 -0
- package/src/recurse-prompts.d.ts +38 -0
- package/src/recurse-prompts.js +69 -1
- package/src/recurse.d.ts +114 -503
- package/src/recurse.js +176 -1513
- package/src/refine-worker.d.ts +155 -0
- package/src/refine-worker.js +598 -0
- package/tools/shell.d.ts +31 -3
- package/tools/shell.js +142 -5
- package/src/recurse-synthesize.d.ts +0 -53
- package/src/recurse-synthesize.js +0 -106
|
@@ -10,101 +10,20 @@ export type Slice = {
|
|
|
10
10
|
};
|
|
11
11
|
export type Provider = import("../types").Provider;
|
|
12
12
|
export type ToolDef = import("../types").ToolDef;
|
|
13
|
-
/**
|
|
14
|
-
* SCAN — process every slice, LLM-judge each window, union matching ids across windows AND passes, CODE-count
|
|
15
|
-
* the union. The default reliability mechanism (§9.2.1): the only path that does not silently undercount.
|
|
16
|
-
* RC-9: a dead window is recorded in `missingSlices`, never folded into the count as a zero.
|
|
17
|
-
* @param {string} predicate - The task the slices are judged against.
|
|
18
|
-
* @param {Slice[]} corpus - The array slice-source (already validated/normalized by the caller).
|
|
19
|
-
* @param {object} opts
|
|
20
|
-
* @param {Provider} opts.provider
|
|
21
|
-
* @param {number} [opts.window]
|
|
22
|
-
* @param {number} [opts.passes]
|
|
23
|
-
* @param {object} [opts.ctx]
|
|
24
|
-
* @param {Function} [opts.onLlmResult]
|
|
25
|
-
* @param {Function} [opts.policy]
|
|
26
|
-
* @returns {Promise<{matchedIds: string[], count: number, missingSlices: string[], window: number, passes: number, scanned: number}>}
|
|
27
|
-
* @throws {HaltError} a governance cap halted a window judge.
|
|
28
|
-
*/
|
|
29
|
-
export function scanCount(predicate: string, corpus: Slice[], opts: {
|
|
30
|
-
provider: Provider;
|
|
31
|
-
window?: number | undefined;
|
|
32
|
-
passes?: number | undefined;
|
|
33
|
-
ctx?: object;
|
|
34
|
-
onLlmResult?: Function | undefined;
|
|
35
|
-
policy?: Function | undefined;
|
|
36
|
-
}): Promise<{
|
|
37
|
-
matchedIds: string[];
|
|
38
|
-
count: number;
|
|
39
|
-
missingSlices: string[];
|
|
40
|
-
window: number;
|
|
41
|
-
passes: number;
|
|
42
|
-
scanned: number;
|
|
43
|
-
}>;
|
|
44
|
-
/**
|
|
45
|
-
* @typedef {object} Slice
|
|
46
|
-
* @property {string} id - Stable, word-like id (no whitespace/commas — it is echoed back by the judge).
|
|
47
|
-
* @property {string} text - The item content shown to the judge.
|
|
48
|
-
*/
|
|
49
|
-
/**
|
|
50
|
-
* Judge ONE window: run an isolated Loop with the classify prompt over the window's items, and intersect the
|
|
51
|
-
* returned ids with the ids actually SHOWN this window (RC-2 — a window's judge can only "match" what it was
|
|
52
|
-
* given; a hallucinated id from another window is dropped). A governance HaltError propagates (the caller turns
|
|
53
|
-
* it into a clean incomplete); any other Loop fault marks the window DEAD (→ RC-9 missingSlices), never a
|
|
54
|
-
* silent zero that would undercount.
|
|
55
|
-
* @param {string} predicate
|
|
56
|
-
* @param {Slice[]} window
|
|
57
|
-
* @param {{provider: Provider, ctx?: object, onLlmResult?: Function, policy?: Function, nonce: number}} opts
|
|
58
|
-
* @returns {Promise<{ids: string[]|null, dead: boolean}>}
|
|
59
|
-
* @throws {HaltError}
|
|
60
|
-
*/
|
|
61
|
-
export function judgeWindow(predicate: string, window: Slice[], opts: {
|
|
62
|
-
provider: Provider;
|
|
63
|
-
ctx?: object;
|
|
64
|
-
onLlmResult?: Function;
|
|
65
|
-
policy?: Function;
|
|
66
|
-
nonce: number;
|
|
67
|
-
}): Promise<{
|
|
68
|
-
ids: string[] | null;
|
|
69
|
-
dead: boolean;
|
|
70
|
-
}>;
|
|
71
|
-
/**
|
|
72
|
-
* The §9.2-validated classify system prompt, GENERALIZED from the POC's hardcoded "SPORTS news" predicate to
|
|
73
|
-
* an arbitrary one. The load-bearing wording is verbatim ("Examine EACH item individually", "Output ONLY the
|
|
74
|
-
* IDs", "Comma-separated. If none, output 'none'. No count, no prose.") — the predicate is the only variable.
|
|
75
|
-
* It MUST return ids, not a count: counting is CODE's job (RC-5 / §9.1), so the judge never does arithmetic.
|
|
76
|
-
* @param {string} predicate - The task/goal the items are judged against.
|
|
77
|
-
* @returns {string}
|
|
78
|
-
*/
|
|
79
|
-
export function classifySystem(predicate: string): string;
|
|
80
|
-
/**
|
|
81
|
-
* Does this text imply a completeness ("all / every / count / how many") ask? Used to upgrade a capped search
|
|
82
|
-
* to a scan (the only complete path). Conservative by design — a false positive only costs a thorough scan.
|
|
83
|
-
* @param {unknown} text
|
|
84
|
-
* @returns {boolean}
|
|
85
|
-
*/
|
|
86
|
-
export function impliesCompleteness(text: unknown): boolean;
|
|
87
|
-
/**
|
|
88
|
-
* Normalize a raw slice-source into validated `{id, text}` slices (drops malformed entries — a slice with no
|
|
89
|
-
* string id/text cannot be judged or counted, so it is excluded rather than silently miscounted).
|
|
90
|
-
* @param {unknown} corpus
|
|
91
|
-
* @returns {Slice[]}
|
|
92
|
-
*/
|
|
93
|
-
export function normalizeCorpus(corpus: unknown): Slice[];
|
|
94
13
|
/**
|
|
95
14
|
* The `search` handle tool (RC-5 needle path): litectx `recall` — embeddings ON, `fact`/`episode` (the
|
|
96
15
|
* KNN-nominate kinds), capped at `KNN_K`. For FINDING the relevant few; the description tells the worker it
|
|
97
|
-
* CANNOT count (
|
|
16
|
+
* CANNOT count (use recurse()'s built-in `classify` for "how many"). Returns the
|
|
98
17
|
* matched items' bodies as text the worker reads; never the whole corpus.
|
|
99
18
|
* @param {{recall: Function}} litectx
|
|
100
19
|
* @param {{kinds?: string[], n?: number}} [opts]
|
|
101
20
|
* @returns {ToolDef}
|
|
102
21
|
* @category integration
|
|
103
22
|
* @when you want to give a recurse worker a needle-search handle over litectx (embeddings recall for the relevant few) — for FINDING, never counting
|
|
104
|
-
* @fails returns matched bodies only and CANNOT count (
|
|
23
|
+
* @fails returns matched bodies only and CANNOT count (use classify for "how many"); a dead window yields nothing, never a fabricated hit.
|
|
105
24
|
* @example
|
|
106
25
|
* const tool = buildSearchTool(litectx, { n: 8 });
|
|
107
|
-
* await recurse(task, ctx, {
|
|
26
|
+
* await recurse(task, ctx, { tools: [tool] });
|
|
108
27
|
*/
|
|
109
28
|
export function buildSearchTool(litectx: {
|
|
110
29
|
recall: Function;
|
|
@@ -124,7 +43,7 @@ export function buildSearchTool(litectx: {
|
|
|
124
43
|
* @fails only as good as a lexical rule; complete over the slices it is given (no recall cap) but matches nothing outside them.
|
|
125
44
|
* @example
|
|
126
45
|
* const tool = buildExactTool(corpus);
|
|
127
|
-
* await recurse(task, ctx, {
|
|
46
|
+
* await recurse(task, ctx, { input: corpus, tools: [tool] });
|
|
128
47
|
*/
|
|
129
48
|
export function buildExactTool(corpus: Slice[]): ToolDef;
|
|
130
49
|
/**
|
|
@@ -171,11 +90,11 @@ export function buildScanTool(corpus: Slice[] | (() => Promise<Slice[]>), opts:
|
|
|
171
90
|
* @param {{kind?: 'fact'|'episode', pageSize?: number}} [opts]
|
|
172
91
|
* @returns {() => Promise<Slice[]>}
|
|
173
92
|
* @category integration
|
|
174
|
-
* @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding
|
|
93
|
+
* @when you want a resident slice-source that paginates a litectx corpus via enumerate — for a corpus ALREADY in litectx, feeding recurse({ input })
|
|
175
94
|
* @fails never ingests a fresh corpus (strictly worse than scanning an in-hand array); returns an async source materialized once and cached.
|
|
176
95
|
* @example
|
|
177
96
|
* const corpus = litectxCorpus(litectx, { kind: 'fact' });
|
|
178
|
-
* await recurse(task, ctx, {
|
|
97
|
+
* await recurse(task, ctx, { input: corpus, kind: 'count' });
|
|
179
98
|
*/
|
|
180
99
|
export function litectxCorpus(litectx: {
|
|
181
100
|
enumerate: Function;
|
|
@@ -183,6 +102,71 @@ export function litectxCorpus(litectx: {
|
|
|
183
102
|
kind?: "fact" | "episode";
|
|
184
103
|
pageSize?: number;
|
|
185
104
|
}): () => Promise<Slice[]>;
|
|
105
|
+
/**
|
|
106
|
+
* SCAN — process every slice, LLM-judge each window, union matching ids across windows AND passes, CODE-count
|
|
107
|
+
* the union. The default reliability mechanism (§9.2.1): the only path that does not silently undercount.
|
|
108
|
+
* RC-9: a dead window is recorded in `missingSlices`, never folded into the count as a zero.
|
|
109
|
+
* @param {string} predicate - The task the slices are judged against.
|
|
110
|
+
* @param {Slice[]} corpus - The array slice-source (already validated/normalized by the caller).
|
|
111
|
+
* @param {object} opts
|
|
112
|
+
* @param {Provider} opts.provider
|
|
113
|
+
* @param {number} [opts.window]
|
|
114
|
+
* @param {number} [opts.passes]
|
|
115
|
+
* @param {object} [opts.ctx]
|
|
116
|
+
* @param {Function} [opts.onLlmResult]
|
|
117
|
+
* @param {Function} [opts.policy]
|
|
118
|
+
* @returns {Promise<{matchedIds: string[], count: number, missingSlices: string[], window: number, passes: number, scanned: number}>}
|
|
119
|
+
* @throws {HaltError} a governance cap halted a window judge.
|
|
120
|
+
*/
|
|
121
|
+
export function scanCount(predicate: string, corpus: Slice[], opts: {
|
|
122
|
+
provider: Provider;
|
|
123
|
+
window?: number | undefined;
|
|
124
|
+
passes?: number | undefined;
|
|
125
|
+
ctx?: object;
|
|
126
|
+
onLlmResult?: Function | undefined;
|
|
127
|
+
policy?: Function | undefined;
|
|
128
|
+
}): Promise<{
|
|
129
|
+
matchedIds: string[];
|
|
130
|
+
count: number;
|
|
131
|
+
missingSlices: string[];
|
|
132
|
+
window: number;
|
|
133
|
+
passes: number;
|
|
134
|
+
scanned: number;
|
|
135
|
+
}>;
|
|
136
|
+
/**
|
|
137
|
+
* @typedef {object} Slice
|
|
138
|
+
* @property {string} id - Stable, word-like id (no whitespace/commas — it is echoed back by the judge).
|
|
139
|
+
* @property {string} text - The item content shown to the judge.
|
|
140
|
+
*/
|
|
141
|
+
/**
|
|
142
|
+
* Judge ONE window: run an isolated Loop with the classify prompt over the window's items, and intersect the
|
|
143
|
+
* returned ids with the ids actually SHOWN this window (RC-2 — a window's judge can only "match" what it was
|
|
144
|
+
* given; a hallucinated id from another window is dropped). A governance HaltError propagates (the caller turns
|
|
145
|
+
* it into a clean incomplete); any other Loop fault marks the window DEAD (→ RC-9 missingSlices), never a
|
|
146
|
+
* silent zero that would undercount.
|
|
147
|
+
* @param {string} predicate
|
|
148
|
+
* @param {Slice[]} window
|
|
149
|
+
* @param {{provider: Provider, ctx?: object, onLlmResult?: Function, policy?: Function, nonce: number}} opts
|
|
150
|
+
* @returns {Promise<{ids: string[]|null, dead: boolean}>}
|
|
151
|
+
* @throws {HaltError}
|
|
152
|
+
*/
|
|
153
|
+
export function judgeWindow(predicate: string, window: Slice[], opts: {
|
|
154
|
+
provider: Provider;
|
|
155
|
+
ctx?: object;
|
|
156
|
+
onLlmResult?: Function;
|
|
157
|
+
policy?: Function;
|
|
158
|
+
nonce: number;
|
|
159
|
+
}): Promise<{
|
|
160
|
+
ids: string[] | null;
|
|
161
|
+
dead: boolean;
|
|
162
|
+
}>;
|
|
163
|
+
/**
|
|
164
|
+
* Normalize a raw slice-source into validated `{id, text}` slices (drops malformed entries — a slice with no
|
|
165
|
+
* string id/text cannot be judged or counted, so it is excluded rather than silently miscounted).
|
|
166
|
+
* @param {unknown} corpus
|
|
167
|
+
* @returns {Slice[]}
|
|
168
|
+
*/
|
|
169
|
+
export function normalizeCorpus(corpus: unknown): Slice[];
|
|
186
170
|
/**
|
|
187
171
|
* Deterministic rotation by `k` — the shuffled-boundary mechanism for multi-pass union WITHOUT an RNG (keeps
|
|
188
172
|
* RC-3 determinism: same corpus + same passes ⇒ identical scan). Rotating the array changes which items share a
|
|
@@ -191,6 +175,4 @@ export function litectxCorpus(litectx: {
|
|
|
191
175
|
* @template T @param {T[]} arr @param {number} k @returns {T[]}
|
|
192
176
|
*/
|
|
193
177
|
export function rotate<T>(arr: T[], k: number): T[];
|
|
194
|
-
export const SCAN_WINDOW: 8;
|
|
195
|
-
export const SCAN_PASSES: 2;
|
|
196
178
|
export const KNN_K: 8;
|
|
@@ -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
|
-
//
|
|
30
|
-
//
|
|
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 (
|
|
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 (
|
|
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, {
|
|
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, {
|
|
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
|
|
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, {
|
|
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;
|