fwdloop 0.15.0 → 0.17.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 -0
- package/bin/fwdloop +113 -36
- package/package.json +2 -2
- package/src/authoring.js +27 -15
- package/src/catalogue.json +9 -3
- package/src/closers.js +5 -0
- package/src/config.js +66 -4
- package/src/ctx-tools.js +245 -0
- package/src/declaration.js +25 -1
- package/src/draft-steps.js +138 -0
- package/src/drafter.js +81 -18
- package/src/draftspend.js +109 -3
- package/src/flowmodel.js +30 -0
- package/src/input-facts.js +12 -3
- package/src/keysfile.js +51 -16
- package/src/liveness.js +34 -10
- package/src/model-step.js +13 -11
- package/src/monthly.js +9 -1
- package/src/panel/author.js +170 -43
- package/src/panel/authorcard.js +32 -20
- package/src/panel/authorflows.js +34 -19
- package/src/panel/authorresume.js +11 -9
- package/src/panel/authorstart.js +11 -9
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +20 -8
- package/src/panel/index.html +584 -182
- package/src/panel/resume.js +3 -3
- package/src/panel/server.js +12 -6
- package/src/panel/settings.js +138 -80
- package/src/panel/spawn.js +15 -9
- package/src/plain-checks.js +51 -0
- package/src/primitives.js +34 -3
- package/src/provider.js +148 -181
- package/src/providershapes.js +7 -7
- package/src/run-store.js +47 -0
- package/src/runner.js +40 -22
- package/src/setup.js +3 -0
- package/src/thinking.js +55 -0
- package/src/version.js +13 -0
- package/types/authoring.d.ts +11 -6
- package/types/closers.d.ts +2 -0
- package/types/config.d.ts +9 -1
- package/types/ctx-tools.d.ts +18 -0
- package/types/draft-steps.d.ts +47 -0
- package/types/drafter.d.ts +15 -12
- package/types/draftspend.d.ts +56 -0
- package/types/flowmodel.d.ts +16 -0
- package/types/input-facts.d.ts +6 -1
- package/types/keysfile.d.ts +23 -6
- package/types/liveness.d.ts +7 -1
- package/types/model-step.d.ts +1 -1
- package/types/monthly.d.ts +1 -0
- package/types/panel/author.d.ts +47 -9
- package/types/panel/authorcard.d.ts +33 -10
- package/types/panel/authorflows.d.ts +32 -9
- package/types/panel/authorresume.d.ts +2 -1
- package/types/panel/authorstart.d.ts +16 -6
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/data.d.ts +2 -2
- package/types/panel/resume.d.ts +2 -1
- package/types/panel/server.d.ts +6 -2
- package/types/panel/settings.d.ts +3 -1
- package/types/panel/spawn.d.ts +13 -4
- package/types/plain-checks.d.ts +22 -0
- package/types/primitives.d.ts +0 -6
- package/types/provider.d.ts +100 -284
- package/types/providershapes.d.ts +3 -4
- package/types/run-store.d.ts +11 -0
- package/types/runner.d.ts +2 -4
- package/types/setup.d.ts +8 -0
- package/types/thinking.d.ts +25 -0
- package/types/version.d.ts +2 -0
package/src/config.js
CHANGED
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
// Shape (unknown top-level fields are kept, never dropped):
|
|
5
5
|
// { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
|
|
6
6
|
// "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
|
|
7
|
-
// "providers": { "<
|
|
7
|
+
// "providers": { "<KEY_NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } }, // each optional; a row is a key name from the keys file (M4d amendment 6). An older file's "model" is tolerated and read by nothing.
|
|
8
|
+
// "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } } // M4d amendment 3 C: a price per model
|
|
9
|
+
// A models line's price is a PAIR or nothing (`modelsProblem` is the one rule): 0 / 0 typed is a chosen price, a
|
|
10
|
+
// ticked line needs both, a half pair is refused. A slot with no list is migrated on READ (`effectiveModels` in
|
|
11
|
+
// src/provider.js); the file is only rewritten when the person saves.
|
|
8
12
|
// A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
|
|
9
13
|
// naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
|
|
10
14
|
// Key VALUES never live here (keys file / shell only): a secret-shaped string is refused on write.
|
|
@@ -84,7 +88,7 @@ function secretPaths(node, at, out) {
|
|
|
84
88
|
}
|
|
85
89
|
}
|
|
86
90
|
|
|
87
|
-
export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl']);
|
|
91
|
+
export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl', 'legacyMaxTokens']);
|
|
88
92
|
|
|
89
93
|
/** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
|
|
90
94
|
export function providerFieldProblem(field, v) {
|
|
@@ -92,6 +96,8 @@ export function providerFieldProblem(field, v) {
|
|
|
92
96
|
if (typeof v !== 'string' || v.length === 0 || v.length > 200 || /\s/.test(v)) return 'must be a model id: 1 to 200 characters, no spaces';
|
|
93
97
|
} else if (field === 'shape') {
|
|
94
98
|
if (!SHAPE_IDS.includes(v)) return `must be one of ${SHAPE_IDS.join(', ')}`;
|
|
99
|
+
} else if (field === 'legacyMaxTokens') {
|
|
100
|
+
if (typeof v !== 'boolean') return 'must be true or false';
|
|
95
101
|
} else if (field === 'baseUrl') {
|
|
96
102
|
if (typeof v !== 'string' || !(v === '' || /^https?:\/\/\S+$/.test(v))) return 'must be empty (the default) or an http(s) address';
|
|
97
103
|
} else return 'is not a provider field';
|
|
@@ -103,6 +109,45 @@ export const cleanBaseUrl = (v) => v.replace(/\/+$/, '');
|
|
|
103
109
|
|
|
104
110
|
const isPrice = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
|
|
105
111
|
|
|
112
|
+
/**
|
|
113
|
+
* THE one rule for a slot's model lines (M4d amendment 3 items 7-8), used by config validation and the Settings
|
|
114
|
+
* route. A price is a PAIR (`inPerM` and `outPerM`, each a finite number >= 0 — 0 / 0 typed is a chosen price,
|
|
115
|
+
* recorded so it is never unknown) or neither (null / absent). A ticked line (`use`) needs both. Plain words, or null.
|
|
116
|
+
* @param {any} list
|
|
117
|
+
* @returns {string|null}
|
|
118
|
+
*/
|
|
119
|
+
export function modelsProblem(list) {
|
|
120
|
+
if (!Array.isArray(list)) return 'The model list must be a list of lines.';
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
for (const line of list) {
|
|
123
|
+
if (line === null || typeof line !== 'object' || Array.isArray(line)) return 'Each model line must be an object.';
|
|
124
|
+
const bad = providerFieldProblem('model', line.model);
|
|
125
|
+
if (bad) return `The model name ${bad}.`;
|
|
126
|
+
if (seen.has(line.model)) return `The model "${line.model}" is listed twice.`;
|
|
127
|
+
seen.add(line.model);
|
|
128
|
+
if (typeof line.use !== 'boolean') return 'Use must be on or off.';
|
|
129
|
+
const has = (f) => line[f] !== undefined && line[f] !== null;
|
|
130
|
+
const isNum = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
|
131
|
+
if (has('inPerM') !== has('outPerM')) return 'Fill both price boxes or clear both.';
|
|
132
|
+
if (has('inPerM') && !(isNum(line.inPerM) && isNum(line.outPerM))) return 'A price must be a number, 0 or more.';
|
|
133
|
+
if (line.use && !has('inPerM')) return 'Fill both prices to tick this model.';
|
|
134
|
+
// `thinkingOff` is an older file's field (M4d amendment 5): tolerated so the file loads, read by nothing, dropped on the next save of the list (amendment 7).
|
|
135
|
+
for (const k of Object.keys(line)) if (!['model', 'use', 'inPerM', 'outPerM', 'thinkingOff'].includes(k)) return `A model line has no "${k}" field.`;
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** @param {any} models */
|
|
141
|
+
function validateModels(models) {
|
|
142
|
+
if (models === undefined) return;
|
|
143
|
+
if (models === null || typeof models !== 'object' || Array.isArray(models)) throw new ConfigError('models must be an object of provider slots');
|
|
144
|
+
for (const [slot, list] of Object.entries(models)) {
|
|
145
|
+
if (!SLOT_RE.test(slot)) throw new ConfigError(`models: "${slot}" is not a provider slot name`);
|
|
146
|
+
const problem = modelsProblem(list);
|
|
147
|
+
if (problem) throw new ConfigError(`models.${slot}: ${problem}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
106
151
|
/** @param {any} providers */
|
|
107
152
|
function validateProviders(providers) {
|
|
108
153
|
if (providers === undefined) return;
|
|
@@ -129,6 +174,7 @@ function validateDoc(doc) {
|
|
|
129
174
|
throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
|
|
130
175
|
}
|
|
131
176
|
validateProviders(doc.providers);
|
|
177
|
+
validateModels(doc.models);
|
|
132
178
|
if (doc.prices === undefined) return;
|
|
133
179
|
if (doc.prices === null || typeof doc.prices !== 'object' || Array.isArray(doc.prices)) {
|
|
134
180
|
throw new ConfigError('prices must be an object of provider slots');
|
|
@@ -177,7 +223,7 @@ export function readConfig(opts = {}) {
|
|
|
177
223
|
|
|
178
224
|
/**
|
|
179
225
|
* Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
|
|
180
|
-
* per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
|
|
226
|
+
* per slot, then per field; `models.<slot>` is replaced whole (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
|
|
181
227
|
* clears the field). Everything is validated before anything is written; a refusal leaves the file
|
|
182
228
|
* untouched.
|
|
183
229
|
* @param {Record<string, any>} patch
|
|
@@ -189,7 +235,7 @@ export function updateConfig(patch, opts = {}) {
|
|
|
189
235
|
/** @type {Record<string, any>} */
|
|
190
236
|
const next = { ...cur };
|
|
191
237
|
for (const [k, v] of Object.entries(patch)) {
|
|
192
|
-
if (k === 'prices' || k === 'providers') continue;
|
|
238
|
+
if (k === 'prices' || k === 'providers' || k === 'models') continue;
|
|
193
239
|
if (v === null) delete next[k];
|
|
194
240
|
else next[k] = v;
|
|
195
241
|
}
|
|
@@ -239,6 +285,22 @@ export function updateConfig(patch, opts = {}) {
|
|
|
239
285
|
else next.providers = providers;
|
|
240
286
|
}
|
|
241
287
|
}
|
|
288
|
+
if (patch.models !== undefined) {
|
|
289
|
+
const p = patch.models;
|
|
290
|
+
if (p === null) {
|
|
291
|
+
delete next.models;
|
|
292
|
+
} else {
|
|
293
|
+
if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('models must be an object of provider slots');
|
|
294
|
+
// a slot's list is replaced whole (`null` clears the slot); other slots are kept
|
|
295
|
+
const models = { ...(next.models ?? {}) };
|
|
296
|
+
for (const [slot, list] of Object.entries(p)) {
|
|
297
|
+
if (list === null) delete models[slot];
|
|
298
|
+
else models[slot] = list;
|
|
299
|
+
}
|
|
300
|
+
if (Object.keys(models).length === 0) delete next.models;
|
|
301
|
+
else next.models = models;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
242
304
|
validateDoc(next);
|
|
243
305
|
/** @type {string[]} */
|
|
244
306
|
const leaks = [];
|
package/src/ctx-tools.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// M7 piece 3 (docs/wiki/the-module-ladder.md, "M7 scope — SIGNED", items 1-3): the
|
|
2
|
+
// in-run tools a step can use only if it is granted: recall, get, recent, related,
|
|
3
|
+
// impact, compress, peek, stash. Each is a litectx call over THIS run's store
|
|
4
|
+
// (src/run-store.js), so nothing carries into the next run.
|
|
5
|
+
//
|
|
6
|
+
// borrowed-from: bareloop src/tools.js@dc06660 (createCtxTools: ctx_recall, ctx_get,
|
|
7
|
+
// ctx_impact, ctx_related, ctx_recent, ctx_compress, ctx_stash, ctx_peek and
|
|
8
|
+
// ISOLATE_MAX_BYTES = 64 KB; the readouts are bareloop's). Adjusted to fwdloop's shape:
|
|
9
|
+
// - named by bare verb, like read/write (src/primitives.js);
|
|
10
|
+
// - the store is per run and opened per call (src/run-store.js), the index root is
|
|
11
|
+
// the run dir, and any path a tool is handed goes through the SAME read gate as
|
|
12
|
+
// `read` first (`gatePath`), so the deny rules apply through every door;
|
|
13
|
+
// - `get` also reads a stashed item by id (the catalogue's words for it);
|
|
14
|
+
// - no spine `emit`: model-step already tallies each tool a step called;
|
|
15
|
+
// - `remember`/`forget` are NOT here: memory lasts one run (PRD: no learning
|
|
16
|
+
// between flows), so they stay refused.
|
|
17
|
+
// - redactSecrets is bareloop's src/validate.js@07215d6 inventory (SECRET_PATTERNS).
|
|
18
|
+
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { createRequire } from 'node:module';
|
|
21
|
+
import { redact } from 'bareguard';
|
|
22
|
+
import { withRunStore } from './run-store.js';
|
|
23
|
+
|
|
24
|
+
const require = createRequire(import.meta.url);
|
|
25
|
+
const { compress: compressNode, StalePointerError } = require('litectx');
|
|
26
|
+
|
|
27
|
+
/** One stashed item holds at most this many bytes (measured after secrets are masked,
|
|
28
|
+
* because that is what enters the store). Bareloop's number, signed in M7 item 3. */
|
|
29
|
+
export const ISOLATE_MAX_BYTES = 65536;
|
|
30
|
+
|
|
31
|
+
const SECRET_PATTERNS = [
|
|
32
|
+
/(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
|
|
33
|
+
/(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
|
|
34
|
+
/(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
|
|
35
|
+
/(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
|
|
36
|
+
/(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
|
|
37
|
+
/(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
/** Mask known secret shapes. @param {unknown} raw */
|
|
41
|
+
const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
|
|
42
|
+
|
|
43
|
+
const LINE_SPACE = 'Line numbers are 0-based; copy them between recall and get as printed.';
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {object} o
|
|
47
|
+
* @param {string} o.runDir
|
|
48
|
+
* @param {(verb: string, rawPath: unknown) => Promise<string>} o.gatePath - the read gate; resolves a model-given path to the absolute path it judged, or throws GateRefusal.
|
|
49
|
+
* @returns {Record<string, {name: string, description: string, parameters: object, execute: (args: any) => Promise<string>}>}
|
|
50
|
+
*/
|
|
51
|
+
export function makeCtxTools({ runDir, gatePath }) {
|
|
52
|
+
const root = path.resolve(runDir);
|
|
53
|
+
/** Run `fn(lc)` on this run's store, with the run's indexed text brought up to date first. A store failure is
|
|
54
|
+
* a refusal RESULT naming the cause, never a throw, so it costs one round instead of the run. */
|
|
55
|
+
const indexed = (/** @type {string} */ tool, /** @type {(lc: any) => Promise<string>|string} */ fn) => async () => {
|
|
56
|
+
try {
|
|
57
|
+
return await withRunStore(runDir, async (lc) => { await lc.index(); return fn(lc); });
|
|
58
|
+
} catch (e) {
|
|
59
|
+
return `${tool} failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
/** A path the gate approved, as litectx spells it: relative to the run dir. @param {string} verb @param {unknown} raw */
|
|
63
|
+
const relOf = async (verb, raw) => {
|
|
64
|
+
const abs = await gatePath(verb, raw);
|
|
65
|
+
return path.relative(root, abs);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
recall: {
|
|
70
|
+
name: 'recall',
|
|
71
|
+
description: 'Search this run\'s code and markdown files only (its frozen inputs and its out folder; a CSV or Word file is not searched) for a name or phrase. '
|
|
72
|
+
+ `Returns POINTERS (path, symbol, line range), not the text; pass one to get to read that part. ${LINE_SPACE}`,
|
|
73
|
+
parameters: {
|
|
74
|
+
type: 'object',
|
|
75
|
+
properties: {
|
|
76
|
+
query: { type: 'string', description: 'A symbol name or a phrase.' },
|
|
77
|
+
n: { type: 'integer', description: 'Max pointers (default 5, max 20).' },
|
|
78
|
+
},
|
|
79
|
+
required: ['query'],
|
|
80
|
+
},
|
|
81
|
+
execute: async ({ query, n }) => indexed('recall', async (lc) => {
|
|
82
|
+
const cap = Math.min(Math.max(Number(n) || 5, 1), 20);
|
|
83
|
+
const grouped = await lc.recall(String(query), { kind: ['code', 'doc'], n: cap });
|
|
84
|
+
const hits = [...(grouped.code ?? []), ...(grouped.doc ?? [])].slice(0, cap);
|
|
85
|
+
const lines = hits.map((/** @type {any} */ h) => (h.chunk
|
|
86
|
+
? `${h.path}\t${h.chunk.symbol ?? '(anonymous)'}\t${h.chunk.nodeType}\tlines ${h.chunk.startLine}-${h.chunk.endLine}`
|
|
87
|
+
: `${h.path}\t(whole file — no chunk)`));
|
|
88
|
+
return lines.length ? lines.join('\n') : 'no hits';
|
|
89
|
+
})(),
|
|
90
|
+
},
|
|
91
|
+
get: {
|
|
92
|
+
name: 'get',
|
|
93
|
+
description: 'Read ONE thing back: a stashed item by its id, or one chunk of a file by the path and line range recall gave you '
|
|
94
|
+
+ `(code plus its doc-comment, without the rest of the file). A range that is not a chunk boundary is refused. ${LINE_SPACE}`,
|
|
95
|
+
parameters: {
|
|
96
|
+
type: 'object',
|
|
97
|
+
properties: {
|
|
98
|
+
id: { type: 'string', description: 'The key a payload was stashed under.' },
|
|
99
|
+
path: { type: 'string', description: 'Path exactly as recall printed it.' },
|
|
100
|
+
startLine: { type: 'integer', description: 'From recall.' },
|
|
101
|
+
endLine: { type: 'integer', description: 'From recall.' },
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
execute: async (args) => {
|
|
105
|
+
if (typeof args?.id === 'string') {
|
|
106
|
+
const key = redactSecrets(args.id);
|
|
107
|
+
return indexed('get', (lc) => (lc.peek(key) ? String(lc.get(key)?.text ?? '') : `nothing stashed under "${key}"`))();
|
|
108
|
+
}
|
|
109
|
+
if (typeof args?.path !== 'string') return 'get: give either an id (a stashed item) or a path with startLine and endLine';
|
|
110
|
+
const rel = await relOf('get', args.path);
|
|
111
|
+
return indexed('get', (lc) => {
|
|
112
|
+
try {
|
|
113
|
+
const item = lc.get(rel, { startLine: Number(args.startLine), endLine: Number(args.endLine) });
|
|
114
|
+
return item?.text || `no chunk at ${args.startLine}-${args.endLine} in "${rel}" — copy a line range from recall, do not compute one`;
|
|
115
|
+
} catch (e) {
|
|
116
|
+
if (e instanceof StalePointerError) return `stale pointer: ${e.message}`;
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
impact: {
|
|
123
|
+
name: 'impact',
|
|
124
|
+
description: 'Before changing a function, see what depends on it: callers, importers and mention sites in code and markdown files only (a CSV or Word file has none). '
|
|
125
|
+
+ `${LINE_SPACE}`,
|
|
126
|
+
parameters: {
|
|
127
|
+
type: 'object',
|
|
128
|
+
properties: { symbol: { type: 'string', description: 'A function, class or identifier name.' } },
|
|
129
|
+
required: ['symbol'],
|
|
130
|
+
},
|
|
131
|
+
execute: async ({ symbol }) => indexed('impact', async (lc) => {
|
|
132
|
+
const imp = await lc.impact(String(symbol));
|
|
133
|
+
if (!imp) return `no indexed symbol "${symbol}" — check the spelling with recall first`;
|
|
134
|
+
const lines = [];
|
|
135
|
+
for (const d of imp.defs ?? []) lines.push(`defined\t${d.path}:${d.startLine}`);
|
|
136
|
+
for (const c of imp.callers ?? []) lines.push(`called by\t${c.path}:${c.line}${c.symbol ? ` (in ${c.symbol})` : ''}`);
|
|
137
|
+
for (const c of imp.callees ?? []) lines.push(`calls\t${c}`);
|
|
138
|
+
lines.push(`risk ${imp.risk} — ${imp.confirmed} confirmed caller(s), ${imp.mentions} mention(s)`);
|
|
139
|
+
// the hedges are the other half of the count: "low risk, 0 callers" alone reads as a licence
|
|
140
|
+
for (const h of imp.hedges ?? []) lines.push(`caveat\t${h}`);
|
|
141
|
+
return lines.join('\n');
|
|
142
|
+
})(),
|
|
143
|
+
},
|
|
144
|
+
related: {
|
|
145
|
+
name: 'related',
|
|
146
|
+
description: 'Walk the import links around one code or markdown file: what it imports and what imports it (one hop). Code and markdown files only.',
|
|
147
|
+
parameters: {
|
|
148
|
+
type: 'object',
|
|
149
|
+
properties: { path: { type: 'string', description: 'A path inside this run, e.g. "out/helper.js".' } },
|
|
150
|
+
required: ['path'],
|
|
151
|
+
},
|
|
152
|
+
execute: async ({ path: p }) => {
|
|
153
|
+
const rel = await relOf('related', p);
|
|
154
|
+
return indexed('related', (lc) => {
|
|
155
|
+
const r = lc.related(rel, { dir: 'both', hops: 1 });
|
|
156
|
+
if (!r || !r.items.length) return `no import edges recorded for "${rel}" — the file is isolated or the path is not indexed`;
|
|
157
|
+
return r.items.map((/** @type {any} */ i) => `${i.via === 'in' ? 'imported by' : 'imports'}\t${i.id}`).join('\n');
|
|
158
|
+
})();
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
recent: {
|
|
162
|
+
name: 'recent',
|
|
163
|
+
description: 'List recently changed functions among this run\'s code files, most recent first. A run is not a git repository, so it finds nothing inside a run.',
|
|
164
|
+
parameters: { type: 'object', properties: {} },
|
|
165
|
+
execute: async () => indexed('recent', (lc) => {
|
|
166
|
+
const rows = lc.recentActivity() ?? [];
|
|
167
|
+
return rows.length
|
|
168
|
+
? rows.map((/** @type {any} */ r) => `${r.id ?? r.symbol}\t${r.kind ?? ''}\tedits ${r.edits ?? '?'}`).join('\n')
|
|
169
|
+
: 'no recent edit activity recorded';
|
|
170
|
+
})(),
|
|
171
|
+
},
|
|
172
|
+
compress: {
|
|
173
|
+
name: 'compress',
|
|
174
|
+
description: 'Read a function\'s SIGNATURE: its declaration head plus doc-comment, with the body left out. '
|
|
175
|
+
+ 'Far cheaper than the body when you only need what it is. Code only; give the path and the symbol name.',
|
|
176
|
+
parameters: {
|
|
177
|
+
type: 'object',
|
|
178
|
+
properties: {
|
|
179
|
+
path: { type: 'string', description: 'A path inside this run.' },
|
|
180
|
+
symbol: { type: 'string', description: 'The function or class name inside that file.' },
|
|
181
|
+
},
|
|
182
|
+
required: ['path', 'symbol'],
|
|
183
|
+
},
|
|
184
|
+
execute: async ({ path: p, symbol }) => {
|
|
185
|
+
const rel = await relOf('compress', p);
|
|
186
|
+
return indexed('compress', async (lc) => {
|
|
187
|
+
const node = lc.getNode(rel);
|
|
188
|
+
const chunk = node?.chunks.find((/** @type {any} */ c) => c.symbol === String(symbol));
|
|
189
|
+
if (!chunk) return `no symbol "${symbol}" in "${rel}" — recall the name to find where it lives`;
|
|
190
|
+
const file = lc.get(rel);
|
|
191
|
+
if (!file?.text) return `"${rel}" has no readable body in the index`;
|
|
192
|
+
const body = file.text.split('\n').slice(chunk.startLine, chunk.endLine + 1).join('\n');
|
|
193
|
+
return compressNode({ text: body, format: node.format, symbol: String(symbol) }, { level: 'signature' });
|
|
194
|
+
})();
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
stash: {
|
|
198
|
+
name: 'stash',
|
|
199
|
+
description: 'Park a bulky payload OUT of your context under a key; it costs nothing per round while parked. Check it later with peek or read it back with get. '
|
|
200
|
+
+ `A payload over ${ISOLATE_MAX_BYTES} bytes is refused unparked. It lasts this run only.`,
|
|
201
|
+
parameters: {
|
|
202
|
+
type: 'object',
|
|
203
|
+
properties: {
|
|
204
|
+
id: { type: 'string', description: 'The key to park under.' },
|
|
205
|
+
text: { type: 'string', description: 'The payload.' },
|
|
206
|
+
},
|
|
207
|
+
required: ['id', 'text'],
|
|
208
|
+
},
|
|
209
|
+
execute: async ({ id, text }) => {
|
|
210
|
+
// masked BEFORE anything else touches it, and the cap is measured on the masked
|
|
211
|
+
// body: that is the one that enters the store
|
|
212
|
+
const key = redactSecrets(id);
|
|
213
|
+
const body = redactSecrets(text);
|
|
214
|
+
const size = Buffer.byteLength(body);
|
|
215
|
+
if (size > ISOLATE_MAX_BYTES) {
|
|
216
|
+
return `stash: text is ${size} bytes — the limit is ${ISOLATE_MAX_BYTES} bytes per payload. Nothing was parked. Park the part you need later, or write the bulk to a file and stash its path.`;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
await withRunStore(runDir, (lc) => lc.stash(key, body));
|
|
220
|
+
} catch (e) {
|
|
221
|
+
return `stash failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
|
|
222
|
+
}
|
|
223
|
+
return `parked ${size} bytes under "${key}"`;
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
peek: {
|
|
227
|
+
name: 'peek',
|
|
228
|
+
description: 'Look at the head and tail of a stashed payload WITHOUT loading all of it.',
|
|
229
|
+
parameters: {
|
|
230
|
+
type: 'object',
|
|
231
|
+
properties: { id: { type: 'string', description: 'The key it was stashed under.' } },
|
|
232
|
+
required: ['id'],
|
|
233
|
+
},
|
|
234
|
+
execute: async ({ id }) => {
|
|
235
|
+
const key = redactSecrets(id);
|
|
236
|
+
try {
|
|
237
|
+
const p = await withRunStore(runDir, (lc) => lc.peek(key));
|
|
238
|
+
return p ? `stash "${key}": ${p.bytes} bytes\nhead: ${p.head}\ntail: ${p.tail}` : `nothing stashed under "${key}"`;
|
|
239
|
+
} catch (e) {
|
|
240
|
+
return `peek failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
}
|
package/src/declaration.js
CHANGED
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
// No `new RegExp` anywhere in this file — a test in test/signed-text.test.js
|
|
37
37
|
// greps all of src/ for that, and it must keep passing with this file added.
|
|
38
38
|
|
|
39
|
-
import { buildSoftgreenRubric } from './closers.js';
|
|
39
|
+
import { buildSoftgreenRubric, isCellsPath } from './closers.js';
|
|
40
40
|
|
|
41
41
|
/** @typedef {import('./types.js').Arbiter} Arbiter */
|
|
42
42
|
/** @typedef {import('./types.js').SignedLine} SignedLine */
|
|
@@ -442,6 +442,9 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
442
442
|
const safeArbiter = /** @type {Arbiter} */ (arbiter);
|
|
443
443
|
const skills = Array.isArray(safeArbiter.skills) ? safeArbiter.skills : [];
|
|
444
444
|
const sourceRoles = Array.isArray(safeArbiter.sources) ? safeArbiter.sources.map((s) => s?.role) : [];
|
|
445
|
+
// M4d amendment 8: the inputs with cells (a spreadsheet file). A step may read one by its role; a green step must.
|
|
446
|
+
const cellsRoles = Array.isArray(safeArbiter.sources)
|
|
447
|
+
? safeArbiter.sources.filter((s) => s?.kind === 'file' && isCellsPath(s.path)).map((s) => s.role) : [];
|
|
445
448
|
const asks = Array.isArray(safeArbiter.asks) ? safeArbiter.asks : [];
|
|
446
449
|
const askLines = asks.map((a) => a.line);
|
|
447
450
|
const sends = Array.isArray(safeArbiter.sends) ? safeArbiter.sends : [];
|
|
@@ -633,12 +636,15 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
633
636
|
// walkable chain — every read must have been emitted by an EARLIER step
|
|
634
637
|
if (reads !== null && emits !== null) {
|
|
635
638
|
for (const readId of reads) {
|
|
639
|
+
if (cellsRoles.includes(readId) && !declaredEmits.has(readId)) continue; // an input with cells, frozen at run start (M4d amendment 8)
|
|
636
640
|
if (readId === emits || !declaredEmits.has(readId)) {
|
|
637
641
|
reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
|
|
638
642
|
}
|
|
639
643
|
}
|
|
640
644
|
}
|
|
645
|
+
const earlierEmits = [...declaredEmits]; // outputs of EARLIER steps, in order (the nearest is last)
|
|
641
646
|
if (emits !== null) declaredEmits.add(emits);
|
|
647
|
+
if (fitJobLine === true && emits !== null && cellsRoles.includes(emits)) reds.push(`declaration: ${label}.emits "${emits}" is also a signed input — one id, one meaning`);
|
|
642
648
|
|
|
643
649
|
// fromLine + class derivation — the key itself is required (value may be
|
|
644
650
|
// null, meaning "no line"; the key being entirely absent is not the same
|
|
@@ -693,6 +699,24 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
693
699
|
reds.push(`declaration: step ${i + 1}'s check reads its reply, so it can't write files. The send step writes the result out.`);
|
|
694
700
|
}
|
|
695
701
|
|
|
702
|
+
// M4d amendment 8: a step whose check is green (every figure cites a source cell) must read an input with cells; a text
|
|
703
|
+
// output of an earlier step has no cells to cite.
|
|
704
|
+
if (fitJobLine === true && effectiveClass === 'green' && reads !== null && !reads.some((r) => cellsRoles.includes(r))) {
|
|
705
|
+
const n = fromLine;
|
|
706
|
+
const reading = reads.length === 0 ? 'it reads nothing' : `it reads only ${reads.join(', ')}`;
|
|
707
|
+
const want = cellsRoles.length === 0 ? 'a spreadsheet input, and this job signs none' : cellsRoles.join(' or ');
|
|
708
|
+
reds.push(`declaration: Line ${n}'s check needs cells, but ${reading}. Line ${n} must read ${want}.`);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// M4d amendment 9: an ask step shows you something: its FIRST read must be the output of an earlier step. A read is not a
|
|
712
|
+
// grant (the ask stays a pure stop); the check is for the plan checker only (fitJobLine), so signed flows still run.
|
|
713
|
+
if (fitJobLine === true && reads !== null && fromLine !== null && askLines.includes(fromLine)
|
|
714
|
+
&& (reads.length === 0 || !earlierEmits.includes(reads[0]))) {
|
|
715
|
+
const want = earlierEmits.length === 0 ? 'the output of an earlier step, and no earlier step makes one' : earlierEmits[earlierEmits.length - 1];
|
|
716
|
+
const got = reads.length === 0 ? 'it reads nothing' : `its first read, ${reads[0]}, is not made by an earlier step`;
|
|
717
|
+
reds.push(`declaration: Line ${fromLine} asks you to check something, but ${got}. Line ${fromLine} must read ${want}.`);
|
|
718
|
+
}
|
|
719
|
+
|
|
696
720
|
// picks — the listing rule, generalised
|
|
697
721
|
if (step.picks !== undefined) {
|
|
698
722
|
if (!isPlainObject(step.picks)) {
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// M4d amendment 15: the Chat card's list of what a draft really did, as PROGRESS only. ONE function builds it (here), from the draft's own log.json and
|
|
2
|
+
// its declaration; the page only renders it. It sits outside the readout (never signed, never hashed).
|
|
3
|
+
//
|
|
4
|
+
// One line per step: { id, label, status: 'done' | 'failed', details: [] } where the label is the step's name with its facts joined by " · ". No detail
|
|
5
|
+
// lines, folds, try lines or raw checker text. A draft that ends red has one plain reason on its plan-checks line and, when the plain words say what
|
|
6
|
+
// to do, one `checks-fix` line (`note: true`: no ✓/✗) under it. The try-by-try history is `triesOf` (the Audit Draft group reads the same function).
|
|
7
|
+
// Throws away: the log's per-round tokens, the model's replies, the questions, and every try but the count of refused ones.
|
|
8
|
+
// Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
|
|
9
|
+
|
|
10
|
+
import { plainPlanCheck } from './plain-checks.js';
|
|
11
|
+
|
|
12
|
+
const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
|
|
13
|
+
|
|
14
|
+
function money(log) {
|
|
15
|
+
if (typeof log.costUsd !== 'number') return 'cost unknown';
|
|
16
|
+
return `${log.spendComplete === false ? 'at least ' : ''}$${log.costUsd.toFixed(4)}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The tries of a draft, one per round, oldest first. The free retry after a broken reply (a `structure-retry` round) keeps the number of the try it
|
|
21
|
+
* retries: "try N again", never a new number. `reds` are the checker's raw refusals; `outcome` is a non-validator round's plain words, `rawOutcome` its own raw words.
|
|
22
|
+
* @param {any[]} rounds the draft's log.json `log`
|
|
23
|
+
* @returns {Array<{ label: string, passed: boolean, reds: string[], outcome: string, rawOutcome: string, again: boolean }>}
|
|
24
|
+
*/
|
|
25
|
+
export function triesOf(rounds) {
|
|
26
|
+
let no = 0;
|
|
27
|
+
return (Array.isArray(rounds) ? rounds : []).map((e, i, all) => {
|
|
28
|
+
const again = e?.kind === 'structure-retry' && i > 0;
|
|
29
|
+
if (!again) no += 1;
|
|
30
|
+
const passed = e?.outcome === 'valid';
|
|
31
|
+
const outcome = typeof e?.outcome === 'string' ? e.outcome.replace(/^structure: /, '') : '';
|
|
32
|
+
const brokenThenRetried = !passed && String(e?.outcome).startsWith('structure: ') && all[i + 1]?.kind === 'structure-retry';
|
|
33
|
+
return {
|
|
34
|
+
label: again ? `try ${no} again` : `try ${no}`,
|
|
35
|
+
passed,
|
|
36
|
+
reds: Array.isArray(e?.reds) ? e.reds.map(String) : [],
|
|
37
|
+
outcome: brokenThenRetried ? 'the reply came back broken; one free retry' : outcome,
|
|
38
|
+
rawOutcome: outcome,
|
|
39
|
+
again,
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `questionOpen` (am15 item 3): the plan asked a question and the draft has NOT ended: its plan-checks line is not red and has no Fix ("red appears only on a draft that ended red").
|
|
46
|
+
* @param {{ log: any, declaration: any, questionOpen?: boolean }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
|
|
47
|
+
* @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
|
|
48
|
+
*/
|
|
49
|
+
export function draftStepList({ log, declaration, questionOpen = false }) {
|
|
50
|
+
if (log === null || typeof log !== 'object') return null;
|
|
51
|
+
const rounds = Array.isArray(log.log) ? log.log : [];
|
|
52
|
+
/** @type {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }>} */
|
|
53
|
+
const out = [];
|
|
54
|
+
|
|
55
|
+
const t = log.thinking;
|
|
56
|
+
if (t && (t.asked === 'on' || t.asked === 'off') && typeof t.status === 'string') {
|
|
57
|
+
if (t.status === 'applied') out.push({ id: 'thinking', label: `thinking ${t.asked}`, status: 'done', details: [] });
|
|
58
|
+
else if (typeof t.say === 'string' && t.say !== '') out.push({ id: 'thinking', label: t.say, status: 'failed', details: [] });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (Array.isArray(log.inputs) && log.inputs.length > 0) {
|
|
62
|
+
out.push({ id: 'inputs', label: ['inputs', ...log.inputs.map((i) => `${i.role}: ${i.detail}`)].join(' · '), status: 'done', details: [] });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// a plan came back (valid or refused by the checker) vs. a round that never gave one (provider red, cut off, budget)
|
|
66
|
+
const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
|
|
67
|
+
const n = typeof log.rounds === 'number' ? log.rounds : 0;
|
|
68
|
+
const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
|
|
69
|
+
const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
|
|
70
|
+
const facts = ['drafted', who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
|
|
71
|
+
if (!gotPlan && reds.length > 0) facts.push(reds[0]); // no plan at all (provider red, cut off): its own words, there is no checker text
|
|
72
|
+
out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [] });
|
|
73
|
+
|
|
74
|
+
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
75
|
+
const rubricReds = [];
|
|
76
|
+
const checkReds = [];
|
|
77
|
+
for (const r of reds) {
|
|
78
|
+
const m = REBUILD_RE.exec(r);
|
|
79
|
+
if (m) rubricReds.push(`line ${steps[Number(m[1])]?.fromLine ?? '?'}: ${m[2]}`); else checkReds.push(r);
|
|
80
|
+
}
|
|
81
|
+
if (gotPlan) {
|
|
82
|
+
if (log.ok === true) {
|
|
83
|
+
// N = the number of the try that passed, minus one (a free retry after a broken reply keeps its try's number)
|
|
84
|
+
const tries = triesOf(rounds);
|
|
85
|
+
const fixedAfter = tries.length > 0 && tries[tries.length - 1].passed ? tries.filter((x) => !x.again).length - 1 : 0;
|
|
86
|
+
out.push({ id: 'checks', label: fixedAfter > 0 ? `plan checks · fixed by the AI after ${fixedAfter} ${fixedAfter === 1 ? 'try' : 'tries'}` : 'plan checks', status: 'done', details: [] });
|
|
87
|
+
} else if (questionOpen) {
|
|
88
|
+
out.push({ id: 'checks', label: 'plan checks · a question for you', status: 'waiting', details: [] });
|
|
89
|
+
} else {
|
|
90
|
+
// one plain reason and its one Fix line (every rule has fix wording): the first refusal
|
|
91
|
+
const pick = checkReds.map(plainPlanCheck)[0];
|
|
92
|
+
out.push({ id: 'checks', label: pick ? `plan checks · ${pick.reason}` : 'plan checks', status: 'failed', details: [] });
|
|
93
|
+
if (pick) out.push({ id: 'checks-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (log.ok === true) {
|
|
98
|
+
const soft = steps.filter((s) => s?.close?.class === 'softgreen');
|
|
99
|
+
if (soft.length > 0) out.push({ id: 'rubrics', label: ['rubrics', ...soft.map((s) => `line ${s.fromLine}`)].join(' · '), status: 'done', details: [] });
|
|
100
|
+
} else if (rubricReds.length > 0) {
|
|
101
|
+
out.push({ id: 'rubrics', label: ['rubrics', ...rubricReds].join(' · '), status: 'failed', details: [] });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* M4d amendment 15, every line of the list: the line of ONE revise (or the redraft after answers), from that plan folder's own log.json. Same rules as `draftStepList`:
|
|
109
|
+
* one line, `<name> · <model> · <n rounds> · <cost>` and, for a plan that passed after refused tries, `fixed by the AI after N tries`; a red one carries one plain
|
|
110
|
+
* reason (and the Fix line under it), never details, folds or raw checker text. The try-by-try history is `triesOf` (the Audit Draft group). `null` = no log.
|
|
111
|
+
* @param {{ log: any, name: string }} p
|
|
112
|
+
* @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
|
|
113
|
+
*/
|
|
114
|
+
export function reviseStepList({ log, name }) {
|
|
115
|
+
if (log === null || typeof log !== 'object') return null;
|
|
116
|
+
const rounds = Array.isArray(log.log) ? log.log : [];
|
|
117
|
+
const n = typeof log.rounds === 'number' ? log.rounds : 0;
|
|
118
|
+
const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
|
|
119
|
+
const facts = [name, who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
|
|
120
|
+
const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
|
|
121
|
+
if (log.ok === true) {
|
|
122
|
+
const tries = triesOf(rounds);
|
|
123
|
+
const fixedAfter = tries.length > 0 && tries[tries.length - 1].passed ? tries.filter((x) => !x.again).length - 1 : 0;
|
|
124
|
+
if (fixedAfter > 0) facts.push(`fixed by the AI after ${fixedAfter} ${fixedAfter === 1 ? 'try' : 'tries'}`);
|
|
125
|
+
return [{ id: 'plan', label: facts.join(' · '), status: 'done', details: [] }];
|
|
126
|
+
}
|
|
127
|
+
const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
|
|
128
|
+
const checkReds = reds.filter((r) => !REBUILD_RE.test(r));
|
|
129
|
+
if (!gotPlan || checkReds.length === 0) {
|
|
130
|
+
if (reds.length > 0) facts.push(reds[0]);
|
|
131
|
+
return [{ id: 'plan', label: facts.join(' · '), status: 'failed', details: [] }];
|
|
132
|
+
}
|
|
133
|
+
const pick = plainPlanCheck(checkReds[0]);
|
|
134
|
+
return [
|
|
135
|
+
{ id: 'plan', label: [name, pick.reason].join(' · '), status: 'failed', details: [] },
|
|
136
|
+
{ id: 'plan-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true },
|
|
137
|
+
];
|
|
138
|
+
}
|