@anytowork/cli 0.12.65 → 0.12.67
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/package.json +1 -1
- package/src/mt/recipes.js +389 -0
- package/src/mt/sample.js +63 -9
- package/src/mt/text.js +7 -0
package/package.json
CHANGED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// v0.38.71 (CLI 0.12.67): a recipe-driven log reader.
|
|
2
|
+
//
|
|
3
|
+
// Why: every Agent used to need its own hand-written reader in readers.js. A new Agent now only needs a recipe, which is
|
|
4
|
+
// data: where its logs are, which file name to take, which lines carry a model call, where the numbers sit, and which
|
|
5
|
+
// trailing model tags do not change the price. The five hand-written readers stay untouched (they carry per-log
|
|
6
|
+
// precision this layer does not try to copy); everything here is additive.
|
|
7
|
+
//
|
|
8
|
+
// What a recipe can never do: supply totals. The numbers are always summed by the CLI from the raw files; a recipe only
|
|
9
|
+
// says where to look and how to read a line. A line that matches but is broken (a missing required field, a token count
|
|
10
|
+
// that is not a number or is negative) is refused with the recipe name, the file and the line number, never counted as 0.
|
|
11
|
+
//
|
|
12
|
+
// A recipe:
|
|
13
|
+
// id internal name; shown in the usage sample diagnostics only
|
|
14
|
+
// client the program name shown in the client line (null when the logs do not name the program)
|
|
15
|
+
// roots default folders, relative to the home folder (an absolute folder is allowed)
|
|
16
|
+
// glob file name to read inside a root ("transcript_full.jsonl", or "*.jsonl")
|
|
17
|
+
// excludeDirs folder names never walked into (shards / caches) so the same call is not counted twice
|
|
18
|
+
// lineFilter {field: value}: a line counts only when every pair matches (nested fields use dotted paths)
|
|
19
|
+
// fields where each value sits (dotted paths): model / input / output / cacheRead / cacheWrite / time
|
|
20
|
+
// dedupeKey field naming one call inside one file; a step written again keeps the last line
|
|
21
|
+
// required fields a matching line must carry (a missing value is refused, never counted as 0)
|
|
22
|
+
// modelSuffixes trailing tags that do not change the price (thinking effort); stripped from the end, repeatedly
|
|
23
|
+
// sessionFrom "dir" = the first folder under the root is the conversation id
|
|
24
|
+
// sniff (optional) a function(headText) -> bool. A recipe with sniff has no default folder and is never found by
|
|
25
|
+
// file name or folder walk: it is used only for a single --from file whose first line passes sniff
|
|
26
|
+
// strictLines (optional) every non-empty line must be a JSON object; anything else is refused, never skipped
|
|
27
|
+
// dedupeRequired (optional) a matching line without the dedupeKey value is refused
|
|
28
|
+
//
|
|
29
|
+
// Adding an Agent: append one object to RECIPES. No other file changes.
|
|
30
|
+
|
|
31
|
+
import fs from "node:fs";
|
|
32
|
+
import os from "node:os";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
import { guessProvider } from "./readers.js";
|
|
35
|
+
|
|
36
|
+
const MAX_DEPTH = 6;
|
|
37
|
+
|
|
38
|
+
export const RECIPES = [
|
|
39
|
+
{
|
|
40
|
+
id: "antigravity",
|
|
41
|
+
client: "Antigravity",
|
|
42
|
+
roots: [".gemini/antigravity/brain", ".gemini/antigravity-cli/brain"],
|
|
43
|
+
glob: "transcript_full.jsonl",
|
|
44
|
+
excludeDirs: ["chunks"],
|
|
45
|
+
lineFilter: { source: "MODEL", type: "PLANNER_RESPONSE" },
|
|
46
|
+
fields: {
|
|
47
|
+
model: "model",
|
|
48
|
+
input: "input_tokens",
|
|
49
|
+
output: "output_tokens",
|
|
50
|
+
cacheRead: "cache_read_tokens",
|
|
51
|
+
time: "created_at",
|
|
52
|
+
},
|
|
53
|
+
dedupeKey: "step_index",
|
|
54
|
+
required: ["model", "time", "input", "output"],
|
|
55
|
+
modelSuffixes: ["-low", "-medium", "-high", "-xhigh", "-sonar", "-tiered"],
|
|
56
|
+
sessionFrom: "dir",
|
|
57
|
+
},
|
|
58
|
+
// v0.38.71: a file an Agent exported by hand (its usage lives in a runtime database, not in a local log). One JSON object
|
|
59
|
+
// per line: message_id (the call, written twice keeps the last), model, input_tokens, output_tokens, created_at (unix
|
|
60
|
+
// seconds or ISO time), optional cache_read_tokens / cache_write_tokens; any other field is ignored. Never scanned by
|
|
61
|
+
// default. The platform is told reader "export" and marks the check low-trust: an exported file is the Agent own copy,
|
|
62
|
+
// so it must not pass for a log the CLI read on this machine.
|
|
63
|
+
{
|
|
64
|
+
id: "export",
|
|
65
|
+
client: null,
|
|
66
|
+
roots: [],
|
|
67
|
+
glob: "*.jsonl",
|
|
68
|
+
fields: {
|
|
69
|
+
model: "model",
|
|
70
|
+
input: "input_tokens",
|
|
71
|
+
output: "output_tokens",
|
|
72
|
+
cacheRead: "cache_read_tokens",
|
|
73
|
+
cacheWrite: "cache_write_tokens",
|
|
74
|
+
time: "created_at",
|
|
75
|
+
},
|
|
76
|
+
dedupeKey: "message_id",
|
|
77
|
+
dedupeRequired: true,
|
|
78
|
+
strictLines: true,
|
|
79
|
+
required: ["model", "time", "input", "output"],
|
|
80
|
+
modelSuffixes: [],
|
|
81
|
+
sniff: sniffExport,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
|
|
85
|
+
/** The first non-empty line of an export file: a JSON object carrying all of message_id / model / created_at / both token counts. */
|
|
86
|
+
function sniffExport(head) {
|
|
87
|
+
const first = String(head || "").split("\n").find((l) => l.trim() !== "");
|
|
88
|
+
if (!first || first.trim()[0] !== "{") return false;
|
|
89
|
+
let o;
|
|
90
|
+
try { o = JSON.parse(first); } catch { return false; }
|
|
91
|
+
return !!o && typeof o === "object"
|
|
92
|
+
&& ["message_id", "model", "created_at", "input_tokens", "output_tokens"].every((k) => k in o);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function recipeById(id) {
|
|
96
|
+
return RECIPES.find((r) => r.id === id) || null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The folders of a recipe: relative entries become paths under the home folder; absolute entries stay as they are. */
|
|
100
|
+
export function expandRoots(recipe, home) {
|
|
101
|
+
return (recipe.roots || []).map((r) => (path.isAbsolute(r) ? r : path.join(home, r)));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isDir(p) {
|
|
105
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function isFile(p) {
|
|
109
|
+
try { return fs.statSync(p).isFile(); } catch { return false; }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The existing default folders of a recipe. */
|
|
113
|
+
export function recipeRoots(recipe, home) {
|
|
114
|
+
return expandRoots(recipe, home).filter(isDir);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A file name pattern: "*" is any run of characters, everything else is literal. */
|
|
118
|
+
export function nameMatches(pattern, name) {
|
|
119
|
+
if (!pattern || pattern === "*") return true;
|
|
120
|
+
if (!pattern.includes("*")) return name === pattern;
|
|
121
|
+
const re = new RegExp("^" + pattern.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
|
|
122
|
+
return re.test(name);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function fieldOf(obj, dotted) {
|
|
126
|
+
let v = obj;
|
|
127
|
+
for (const k of String(dotted).split(".")) {
|
|
128
|
+
if (v == null || typeof v !== "object") return undefined;
|
|
129
|
+
v = v[k];
|
|
130
|
+
}
|
|
131
|
+
return v;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function isEmpty(v) {
|
|
135
|
+
return v === undefined || v === null || (typeof v === "string" && v.trim() === "");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function toMs(v) {
|
|
139
|
+
if (v == null || v === "") return null;
|
|
140
|
+
const num = typeof v === "number" ? v : (/^\s*\d+(\.\d+)?\s*$/.test(String(v)) ? Number(v) : null); // unix seconds / ms, also as text
|
|
141
|
+
const ms = num != null ? (num < 1e12 ? num * 1000 : num) : Date.parse(String(v));
|
|
142
|
+
return Number.isFinite(ms) ? ms : null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A recipe or a log line that cannot be used: names the recipe and, for a line, the file and the line number. */
|
|
146
|
+
export class RecipeError extends Error {
|
|
147
|
+
constructor(info) {
|
|
148
|
+
super("recipe " + info.recipe + (info.file ? " (" + info.file + " line " + info.line + ")" : "") + ": " + info.message);
|
|
149
|
+
this.name = "RecipeError";
|
|
150
|
+
this.code = "recipe_bad_line";
|
|
151
|
+
this.info = info;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function bad(recipe, file, line, message) {
|
|
156
|
+
throw new RecipeError({ recipe: recipe.id, file, line, message });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** A model name without its thinking-effort tags ("gemini-4-carbon-medium" -> "gemini-4-carbon"). */
|
|
160
|
+
export function normalizeModel(model, suffixes = []) {
|
|
161
|
+
let m = String(model == null ? "" : model).trim();
|
|
162
|
+
const list = [...suffixes].sort((a, b) => b.length - a.length);
|
|
163
|
+
let again = true;
|
|
164
|
+
while (again) {
|
|
165
|
+
again = false;
|
|
166
|
+
const low = m.toLowerCase();
|
|
167
|
+
for (const s of list) {
|
|
168
|
+
if (low.length > s.length && low.endsWith(s.toLowerCase())) {
|
|
169
|
+
m = m.slice(0, m.length - s.length);
|
|
170
|
+
again = true;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return m;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function checkRecipe(recipe) {
|
|
179
|
+
if (!recipe || !recipe.id) throw new RecipeError({ recipe: "?", file: null, line: 0, message: "recipe has no id" });
|
|
180
|
+
for (const k of ["model", "time", "input", "output"]) {
|
|
181
|
+
if (!recipe.fields || !recipe.fields[k]) bad(recipe, null, 0, "recipe is missing fields." + k);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function matchesFilter(recipe, obj) {
|
|
186
|
+
const f = recipe.lineFilter || {};
|
|
187
|
+
for (const [k, v] of Object.entries(f)) {
|
|
188
|
+
if (String(fieldOf(obj, k)) !== String(v)) return false;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function countAt(recipe, obj, key, file, line) {
|
|
194
|
+
const dotted = recipe.fields[key];
|
|
195
|
+
if (!dotted) return null;
|
|
196
|
+
const v = fieldOf(obj, dotted);
|
|
197
|
+
const required = (recipe.required || []).includes(key);
|
|
198
|
+
if (isEmpty(v)) {
|
|
199
|
+
if (required) bad(recipe, file, line, "missing " + key + " (" + dotted + ")");
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
const n = typeof v === "number" ? v : Number(String(v).trim());
|
|
203
|
+
if (!Number.isFinite(n)) bad(recipe, file, line, key + " (" + dotted + ") is not a number: " + JSON.stringify(v));
|
|
204
|
+
if (n < 0) bad(recipe, file, line, key + " (" + dotted + ") is negative: " + n);
|
|
205
|
+
return Math.floor(n);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function sessionOf(recipe, file, root) {
|
|
209
|
+
if (recipe.sessionFrom !== "dir") return null;
|
|
210
|
+
if (file === root) return null;
|
|
211
|
+
const rel = path.relative(root, file);
|
|
212
|
+
if (!rel || rel.startsWith("..")) return null;
|
|
213
|
+
const first = rel.split(path.sep)[0];
|
|
214
|
+
return first && first !== path.basename(file) ? first : null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function rowOf(recipe, obj, entry, lineNo) {
|
|
218
|
+
const modelRaw = String(fieldOf(obj, recipe.fields.model) ?? "").trim();
|
|
219
|
+
if (!modelRaw) bad(recipe, entry.file, lineNo, "missing model (" + recipe.fields.model + ")");
|
|
220
|
+
const model = normalizeModel(modelRaw, recipe.modelSuffixes);
|
|
221
|
+
const atRaw = fieldOf(obj, recipe.fields.time);
|
|
222
|
+
const atMs = toMs(atRaw);
|
|
223
|
+
if (atMs == null) bad(recipe, entry.file, lineNo, "bad time (" + recipe.fields.time + "): " + JSON.stringify(atRaw));
|
|
224
|
+
const input = countAt(recipe, obj, "input", entry.file, lineNo);
|
|
225
|
+
const output = countAt(recipe, obj, "output", entry.file, lineNo);
|
|
226
|
+
const cacheRead = countAt(recipe, obj, "cacheRead", entry.file, lineNo);
|
|
227
|
+
const cacheWrite = countAt(recipe, obj, "cacheWrite", entry.file, lineNo);
|
|
228
|
+
const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
|
|
229
|
+
if (recipe.dedupeRequired && isEmpty(step)) bad(recipe, entry.file, lineNo, "missing " + recipe.dedupeKey);
|
|
230
|
+
const id = isEmpty(step) ? path.basename(entry.file) + ":" + lineNo : String(step);
|
|
231
|
+
return {
|
|
232
|
+
call_id: (entry.session || path.basename(entry.file)) + ":" + id,
|
|
233
|
+
conversation_id: entry.session || null,
|
|
234
|
+
provider: guessProvider(model),
|
|
235
|
+
model,
|
|
236
|
+
started_at: new Date(atMs).toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
237
|
+
ended_at: null,
|
|
238
|
+
input_tokens: input,
|
|
239
|
+
output_tokens: output,
|
|
240
|
+
cache_write_tokens: cacheWrite,
|
|
241
|
+
cache_read_tokens: cacheRead,
|
|
242
|
+
cwd: null,
|
|
243
|
+
seenMs: atMs,
|
|
244
|
+
atMs,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function walk(dir, root, depth, out, recipe, sinceMs) {
|
|
249
|
+
let entries;
|
|
250
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
251
|
+
for (const e of entries) {
|
|
252
|
+
const p = path.join(dir, e.name);
|
|
253
|
+
if (e.isDirectory()) {
|
|
254
|
+
if (depth >= MAX_DEPTH) continue;
|
|
255
|
+
if ((recipe.excludeDirs || []).includes(e.name)) continue;
|
|
256
|
+
walk(p, root, depth + 1, out, recipe, sinceMs);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (!e.isFile() || !nameMatches(recipe.glob, e.name)) continue;
|
|
260
|
+
try { if (sinceMs && fs.statSync(p).mtimeMs < sinceMs) continue; } catch { continue; }
|
|
261
|
+
out.push({ file: p, root, session: sessionOf(recipe, p, root) });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Read one recipe. `roots` overrides the recipe folders (used by --from). Returns
|
|
267
|
+
* { found, calls, files, lines, models, sample, client }. Throws RecipeError when a matching line is broken.
|
|
268
|
+
*/
|
|
269
|
+
export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, roots = null } = {}) {
|
|
270
|
+
checkRecipe(recipe);
|
|
271
|
+
const baseRoots = roots || expandRoots(recipe, home);
|
|
272
|
+
const files = [];
|
|
273
|
+
const seenFiles = new Set();
|
|
274
|
+
for (const root of baseRoots) {
|
|
275
|
+
if (isFile(root)) {
|
|
276
|
+
if (nameMatches(recipe.glob, path.basename(root)) && !seenFiles.has(root)) {
|
|
277
|
+
seenFiles.add(root);
|
|
278
|
+
files.push({ file: root, root, session: null });
|
|
279
|
+
}
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (!isDir(root)) continue;
|
|
283
|
+
const found = [];
|
|
284
|
+
walk(root, root, 0, found, recipe, sinceMs);
|
|
285
|
+
for (const f of found) {
|
|
286
|
+
if (seenFiles.has(f.file)) continue;
|
|
287
|
+
seenFiles.add(f.file);
|
|
288
|
+
files.push(f);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const calls = [];
|
|
292
|
+
const models = new Set();
|
|
293
|
+
// a line that cannot match need not be parsed: every matching line holds the first filter value somewhere
|
|
294
|
+
const needle = String(Object.values(recipe.lineFilter || {})[0] || "");
|
|
295
|
+
let lines = 0;
|
|
296
|
+
let sample = null;
|
|
297
|
+
for (const entry of files) {
|
|
298
|
+
let text;
|
|
299
|
+
try { text = fs.readFileSync(entry.file, "utf8"); } catch { continue; }
|
|
300
|
+
const rows = [];
|
|
301
|
+
const at = new Map();
|
|
302
|
+
const list = text.split("\n");
|
|
303
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
304
|
+
const raw = list[i];
|
|
305
|
+
if (recipe.strictLines && raw.trim() === "") continue;
|
|
306
|
+
if (!raw || (!recipe.strictLines && raw[0] !== "{")) continue;
|
|
307
|
+
if (needle && raw.indexOf(needle) === -1) continue;
|
|
308
|
+
let obj;
|
|
309
|
+
try { obj = JSON.parse(raw); } catch {
|
|
310
|
+
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON line");
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
314
|
+
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON object");
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (!matchesFilter(recipe, obj)) continue;
|
|
318
|
+
lines += 1;
|
|
319
|
+
const row = rowOf(recipe, obj, entry, i + 1);
|
|
320
|
+
const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
|
|
321
|
+
const key = isEmpty(step) ? entry.file + ":" + (i + 1) : entry.file + ":" + String(step);
|
|
322
|
+
if (at.has(key)) rows[at.get(key)] = row; // a step written again: the last line wins
|
|
323
|
+
else { at.set(key, rows.length); rows.push(row); }
|
|
324
|
+
}
|
|
325
|
+
for (const row of rows) {
|
|
326
|
+
calls.push(row);
|
|
327
|
+
models.add(row.model);
|
|
328
|
+
if (!sample) sample = row;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
found: files.length > 0,
|
|
333
|
+
calls,
|
|
334
|
+
files: files.length,
|
|
335
|
+
lines,
|
|
336
|
+
models: [...models],
|
|
337
|
+
sample: sample ? {
|
|
338
|
+
model: sample.model, at: sample.started_at, input_tokens: sample.input_tokens,
|
|
339
|
+
output_tokens: sample.output_tokens, cache_read_tokens: sample.cache_read_tokens,
|
|
340
|
+
} : null,
|
|
341
|
+
client: recipe.client || null,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** A --from path that belongs to a recipe, or null. Checked before the hand-written path shapes. */
|
|
346
|
+
export function recipeForPath(abs, st) {
|
|
347
|
+
if (!st) return null;
|
|
348
|
+
const as = (r) => ({ reader: "recipe", recipe: r.id, client: r.client || null, roots: [abs], root: abs });
|
|
349
|
+
if (st.isFile()) {
|
|
350
|
+
const name = path.basename(abs);
|
|
351
|
+
const r = RECIPES.find((x) => !x.sniff && nameMatches(x.glob, name));
|
|
352
|
+
if (r) return as(r);
|
|
353
|
+
// a file with its own shape check (an Agent export): only a .jsonl file whose first line passes
|
|
354
|
+
const s = RECIPES.find((x) => x.sniff && abs.endsWith(".jsonl") && sniffFile(x, abs));
|
|
355
|
+
return s ? as(s) : null;
|
|
356
|
+
}
|
|
357
|
+
if (!st.isDirectory()) return null;
|
|
358
|
+
for (const r of RECIPES.filter((x) => !x.sniff)) {
|
|
359
|
+
for (const root of expandRoots(r, os.homedir())) {
|
|
360
|
+
if (abs === root || abs.startsWith(root + path.sep)) return as(r);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
for (const r of RECIPES.filter((x) => !x.sniff)) {
|
|
364
|
+
if (hasFileBelow(abs, r, 3)) return as(r);
|
|
365
|
+
}
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function sniffFile(recipe, abs) {
|
|
370
|
+
try {
|
|
371
|
+
const fd = fs.openSync(abs, "r");
|
|
372
|
+
try {
|
|
373
|
+
const b = Buffer.alloc(65536);
|
|
374
|
+
return !!recipe.sniff(b.toString("utf8", 0, fs.readSync(fd, b, 0, b.length, 0)));
|
|
375
|
+
} finally { fs.closeSync(fd); }
|
|
376
|
+
} catch { return false; }
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function hasFileBelow(dir, recipe, depth) {
|
|
380
|
+
let entries;
|
|
381
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
|
|
382
|
+
for (const e of entries) {
|
|
383
|
+
if (e.isFile() && nameMatches(recipe.glob, e.name)) return true;
|
|
384
|
+
if (e.isDirectory() && depth > 0 && !(recipe.excludeDirs || []).includes(e.name)) {
|
|
385
|
+
if (hasFileBelow(path.join(dir, e.name), recipe, depth - 1)) return true;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return false;
|
|
389
|
+
}
|
package/src/mt/sample.js
CHANGED
|
@@ -27,6 +27,7 @@ import { pickLang } from '../model-pledge.js';
|
|
|
27
27
|
import { t } from './text.js';
|
|
28
28
|
import { listJsonl, loadSqlite } from './readers.js';
|
|
29
29
|
import { dshRoots, readDshCalls, looksLikeDsh } from './dsh.js';
|
|
30
|
+
import { RECIPES, recipeById, expandRoots, recipeForPath, readRecipeCalls } from './recipes.js';
|
|
30
31
|
|
|
31
32
|
export const KIND = 'job_usage_sample';
|
|
32
33
|
export const JOB_CHECK_PATH = '/api/v1/agent/hire/job-check';
|
|
@@ -395,13 +396,20 @@ export function defaultSources(home, env = {}) {
|
|
|
395
396
|
if (env.HERMES_HOME) sdb.push(path.join(String(env.HERMES_HOME), 'state.db'));
|
|
396
397
|
sdb.push(path.join(home, '.hermes', 'state.db'));
|
|
397
398
|
const agents = path.join(home, '.openclaw', 'agents');
|
|
398
|
-
|
|
399
|
+
const out = [
|
|
399
400
|
{ reader: 'msg_log', roots: [...new Set(msg)] },
|
|
400
401
|
{ reader: 'rollout', roots: [...new Set(roll)] },
|
|
401
402
|
{ reader: 'dsh_log', roots: dshRoots(home) },
|
|
402
403
|
{ reader: 'session_db', files: [...new Set(sdb)] },
|
|
403
404
|
{ reader: 'run_db', files: agentsDbFiles(agents), root: agents },
|
|
404
405
|
];
|
|
406
|
+
// v0.38.68: recipe sources. A recipe with no folder on this computer is left out, so a machine without that program
|
|
407
|
+
// reads exactly the same logs as before.
|
|
408
|
+
for (const recipe of RECIPES) {
|
|
409
|
+
const roots = expandRoots(recipe, home).filter(isDir);
|
|
410
|
+
if (roots.length) out.push({ reader: 'recipe', recipe: recipe.id, client: recipe.client || null, roots });
|
|
411
|
+
}
|
|
412
|
+
return out;
|
|
405
413
|
}
|
|
406
414
|
|
|
407
415
|
/** `--from <path>`: the reader picked by the shape of the path, or null when nothing there looks like a log. */
|
|
@@ -409,6 +417,9 @@ export function sourceFromPath(p) {
|
|
|
409
417
|
const abs = path.resolve(String(p));
|
|
410
418
|
let st;
|
|
411
419
|
try { st = fs.statSync(abs); } catch { return null; }
|
|
420
|
+
// v0.38.68: a recipe path wins over the hand-written shapes (a recipe folder would otherwise look like a plain jsonl folder).
|
|
421
|
+
const byRecipe = recipeForPath(abs, st);
|
|
422
|
+
if (byRecipe) return byRecipe;
|
|
412
423
|
if (st.isFile()) {
|
|
413
424
|
if (abs.endsWith('.sqlite')) return { reader: 'run_db', files: [abs], root: abs };
|
|
414
425
|
if (abs.endsWith('.db')) return { reader: 'session_db', files: [abs], root: abs };
|
|
@@ -448,7 +459,17 @@ export function sourceFromPath(p) {
|
|
|
448
459
|
return null;
|
|
449
460
|
}
|
|
450
461
|
|
|
451
|
-
export async function readSource(src, { sinceMs, sqlite }) {
|
|
462
|
+
export async function readSource(src, { sinceMs, sqlite, home, env } = {}) {
|
|
463
|
+
if (src.reader === 'recipe') {
|
|
464
|
+
const recipe = recipeById(src.recipe);
|
|
465
|
+
const r = readRecipeCalls(recipe, { home, env, sinceMs, roots: src.roots });
|
|
466
|
+
return {
|
|
467
|
+
found: r.found,
|
|
468
|
+
calls: r.calls,
|
|
469
|
+
client: r.client,
|
|
470
|
+
stats: { recipe: recipe.id, files: r.files, lines: r.lines, models: r.models, sample: r.sample },
|
|
471
|
+
};
|
|
472
|
+
}
|
|
452
473
|
switch (src.reader) {
|
|
453
474
|
case 'msg_log': return readMsgLogSample({ roots: src.roots, sinceMs });
|
|
454
475
|
case 'rollout': return readRolloutSample({ roots: src.roots, sinceMs });
|
|
@@ -500,7 +521,8 @@ export function buildSample({ reader, calls, tz, nowMs }) {
|
|
|
500
521
|
return {
|
|
501
522
|
kind: KIND,
|
|
502
523
|
tz,
|
|
503
|
-
|
|
524
|
+
// an Agent export file is the Agent own copy: it never passes for a log read on this computer
|
|
525
|
+
source: reader === 'export' ? 'agent-export' : 'local-log',
|
|
504
526
|
reader,
|
|
505
527
|
calls: inWin.slice(-RECENT_CALLS).map((c) => ({
|
|
506
528
|
at: isoLocal(c.atMs, tz), model: c.model, input_tokens: c.input_tokens, output_tokens: c.output_tokens,
|
|
@@ -524,8 +546,14 @@ export function summarize(sample) {
|
|
|
524
546
|
// ---------------------------------------------------------------- the command
|
|
525
547
|
|
|
526
548
|
function shortRoot(src, home) {
|
|
549
|
+
const short = (r) => (home && r.startsWith(home) ? `~${r.slice(home.length)}` : r);
|
|
550
|
+
// a recipe can hold several folders (one program, two layouts): show every folder it found, not just the first
|
|
551
|
+
if (src.reader === 'recipe' && Array.isArray(src.roots) && src.roots.length > 1) {
|
|
552
|
+
const found = src.roots.filter(isDir).map(short);
|
|
553
|
+
if (found.length) return found.join(' + ');
|
|
554
|
+
}
|
|
527
555
|
const r = src.root || (src.roots && src.roots.find(isDir)) || (src.files && src.files.find(isFile)) || '';
|
|
528
|
-
return
|
|
556
|
+
return short(r);
|
|
529
557
|
}
|
|
530
558
|
|
|
531
559
|
function errorCodeOf(e) {
|
|
@@ -545,12 +573,18 @@ async function gatherSample(c, tz) {
|
|
|
545
573
|
let dbError = false;
|
|
546
574
|
let oldNode = false;
|
|
547
575
|
for (const src of sources) {
|
|
548
|
-
|
|
576
|
+
let r;
|
|
577
|
+
try {
|
|
578
|
+
r = await readSource(src, { sinceMs, sqlite: c.sqlite, home: c.home, env: c.env });
|
|
579
|
+
} catch (e) {
|
|
580
|
+
if (e && e.code === 'recipe_bad_line') return { bad: e.info };
|
|
581
|
+
throw e;
|
|
582
|
+
}
|
|
549
583
|
found = found || r.found;
|
|
550
584
|
dbError = dbError || !!r.dbError;
|
|
551
585
|
oldNode = oldNode || !!r.oldNode;
|
|
552
586
|
const inWin = windowCalls(r.calls, tz, nowMs);
|
|
553
|
-
if (inWin.length) got.push({ src, calls: r.calls, inWin, entries: r.entries || [] });
|
|
587
|
+
if (inWin.length) got.push({ src, calls: r.calls, inWin, entries: r.entries || [], stats: r.stats || null });
|
|
554
588
|
}
|
|
555
589
|
if (!got.length) return { unreadable: oldNode ? 'node_old' : dbError ? 'db' : (found ? 'empty' : 'no_log') };
|
|
556
590
|
if (got.length > 1) {
|
|
@@ -564,7 +598,10 @@ async function gatherSample(c, tz) {
|
|
|
564
598
|
const g = got[0];
|
|
565
599
|
if (g.inWin.every((x) => unpriceable(x.model))) return { unreadable: 'model' };
|
|
566
600
|
const noModel = g.inWin.filter((x) => String(x.model || '').trim() === '').length;
|
|
567
|
-
|
|
601
|
+
const client = clientOf(g.src.reader, g.entries)
|
|
602
|
+
|| (g.src.reader === 'recipe' && g.src.client ? { name: g.src.client, entries: [] } : null);
|
|
603
|
+
const readerName = g.src.reader === 'recipe' ? g.src.recipe : g.src.reader;
|
|
604
|
+
return { sample: buildSample({ reader: readerName, calls: g.calls, tz, nowMs }), client, stats: g.stats || null, drops: { old: g.calls.length - g.inWin.length, nomodel: noModel } };
|
|
568
605
|
}
|
|
569
606
|
|
|
570
607
|
function resultLines(d, env) {
|
|
@@ -590,6 +627,7 @@ export async function cmdSample(c) {
|
|
|
590
627
|
let summary = null;
|
|
591
628
|
let client = null;
|
|
592
629
|
let drops = null;
|
|
630
|
+
let stats = null;
|
|
593
631
|
if (c.flags.unreadable != null) {
|
|
594
632
|
const reason = String(c.flags.unreadable).replace(/\s+/g, ' ').trim();
|
|
595
633
|
if (!reason || reason.length > REASON_MAX) return c.fail(2, 'bad_reason', t('sample.bad_reason', { max: REASON_MAX }, env));
|
|
@@ -601,6 +639,14 @@ export async function cmdSample(c) {
|
|
|
601
639
|
c.fromSource = sourceFromPath(p);
|
|
602
640
|
}
|
|
603
641
|
const g = c.flags.from != null && !c.fromSource ? { unreadable: 'no_log' } : await gatherSample(c, tz);
|
|
642
|
+
if (g.bad) {
|
|
643
|
+
const msg = t('sample.recipe_bad', { recipe: g.bad.recipe, file: g.bad.file || '-', line: g.bad.line, msg: g.bad.message }, env);
|
|
644
|
+
if (c.flags.json) {
|
|
645
|
+
c.log(JSON.stringify({ ok: false, error: 'recipe_bad_line', recipe: g.bad.recipe, file: g.bad.file || null, line: g.bad.line, message: g.bad.message }));
|
|
646
|
+
return 2;
|
|
647
|
+
}
|
|
648
|
+
return c.fail(2, 'recipe_bad_line', msg);
|
|
649
|
+
}
|
|
604
650
|
if (g.several) {
|
|
605
651
|
if (c.flags.json) {
|
|
606
652
|
c.log(JSON.stringify({ ok: false, error: 'several_sources', message: t('sample.several', {}, env), sources: g.several }));
|
|
@@ -611,10 +657,12 @@ export async function cmdSample(c) {
|
|
|
611
657
|
return 2;
|
|
612
658
|
}
|
|
613
659
|
body = g.sample || { kind: KIND, unreadable: true, reason: reasonText(g.unreadable, env) };
|
|
614
|
-
if (g.sample) { summary = summarize(g.sample); client = g.client; drops = g.drops || null; }
|
|
660
|
+
if (g.sample) { summary = summarize(g.sample); client = g.client; drops = g.drops || null; stats = g.stats || null; }
|
|
615
661
|
}
|
|
616
662
|
const clientField = client ? { client } : {};
|
|
617
|
-
const clientLine = client
|
|
663
|
+
const clientLine = client
|
|
664
|
+
? [t('sample.client', { v: client.entries.length ? client.name + ' · ' + client.entries.join(', ') : client.name }, env)]
|
|
665
|
+
: [];
|
|
618
666
|
|
|
619
667
|
if (c.flags.dryRun) {
|
|
620
668
|
if (c.flags.json) { c.log(JSON.stringify({ ok: true, dry_run: true, sample: body, ...clientField })); return 0; }
|
|
@@ -624,8 +672,13 @@ export async function cmdSample(c) {
|
|
|
624
672
|
c.log(t('sample.dry_title', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
|
|
625
673
|
for (const l of clientLine) c.log(l);
|
|
626
674
|
c.log(t('sample.dry_models', { v: summary.models.map((m) => `${m.model} ${m.share}%`).join(', ') }, env));
|
|
675
|
+
if (stats) {
|
|
676
|
+
c.log(t('sample.dry_recipe', { recipe: stats.recipe, files: stats.files, lines: stats.lines, models: stats.models.join(', ') || '-' }, env));
|
|
677
|
+
if (stats.sample) c.log(t('sample.dry_row', { v: JSON.stringify(stats.sample) }, env));
|
|
678
|
+
}
|
|
627
679
|
if (drops && (drops.old || drops.nomodel)) c.log(t('sample.dry_dropped', drops, env));
|
|
628
680
|
}
|
|
681
|
+
if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
|
|
629
682
|
c.log(t('sample.own_only', {}, env));
|
|
630
683
|
return 0;
|
|
631
684
|
}
|
|
@@ -650,5 +703,6 @@ export async function cmdSample(c) {
|
|
|
650
703
|
: t('sample.delivered', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
|
|
651
704
|
for (const l of clientLine) c.log(l);
|
|
652
705
|
for (const l of resultLines(d, env)) c.log(l);
|
|
706
|
+
if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
|
|
653
707
|
return 0;
|
|
654
708
|
}
|
package/src/mt/text.js
CHANGED
|
@@ -130,10 +130,17 @@ const TEXT = {
|
|
|
130
130
|
'sample.dry_title': { zh: '试读(不上传):{reader},{days} 天,{calls} 次调用', en: 'Trial read (nothing sent): {reader}, {days} days, {calls} calls' },
|
|
131
131
|
'sample.client': { zh: ' 客户端:{v}', en: ' Client: {v}' },
|
|
132
132
|
'sample.dry_models': { zh: ' 模型(按输入 + 输出 token 占比):{v}', en: ' Models (share of input + output tokens): {v}' },
|
|
133
|
+
'sample.dry_recipe': { zh: ' 配方 {recipe}:{files} 个文件,{lines} 行命中,模型 {models}', en: ' Recipe {recipe}: {files} files, {lines} lines matched, models {models}' },
|
|
134
|
+
'sample.dry_row': { zh: ' 样例:{v}', en: ' Sample: {v}' },
|
|
135
|
+
'sample.recipe_bad': { zh: '配方 {recipe} 读不了:{file} 第 {line} 行,{msg}', en: 'Recipe {recipe} cannot be read: {file} line {line}, {msg}' },
|
|
133
136
|
'sample.dry_unreadable': {
|
|
134
137
|
zh: '试读(不上传):读不到可用的用量({reason})。正式运行会把这句原因交给平台。',
|
|
135
138
|
en: 'Trial read (nothing sent): no usable usage ({reason}). A real run sends this reason to the platform.',
|
|
136
139
|
},
|
|
140
|
+
'sample.export_note': {
|
|
141
|
+
zh: '来源是 Agent 导出的文件,平台会标为低可信来源。',
|
|
142
|
+
en: 'The source is a file exported by the Agent; the platform marks it as a low-trust source.',
|
|
143
|
+
},
|
|
137
144
|
'sample.own_only': {
|
|
138
145
|
zh: '只算你自己这个程序的用量:如果读到的不是你自己这个程序的日志,用 --from <你自己这个程序的日志位置> 指定。',
|
|
139
146
|
en: 'Only the usage of your own program counts: if this is not the log of your own program, point to it with --from <your own log path>.',
|