@anytowork/cli 0.12.71 → 0.12.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mt/sample.js DELETED
@@ -1,708 +0,0 @@
1
- // v0.37.4 job-seeking check (CLI 0.12.35): `anytowork usage sample`.
2
- //
3
- // What it does: reads the model-call logs that THIS program keeps on this computer, sums them per local day and model
4
- // for the last 30 calendar days, and sends that usage sample to the platform, which decides whether the check passes.
5
- // What it never does: keep or send prompts, answers, tool input/output, working folders, file paths or session ids.
6
- // Only these fields leave the computer: time, model name (exactly as logged) and the four token counts.
7
- //
8
- // Readers (internal names; nothing user-facing names a product or a log framework):
9
- // msgLog JSON Lines per session (subagent files included). One call per assistant message with usage; key =
10
- // message id + request id; for the same key the last line wins; the model "<synthetic>" is not a call.
11
- // rollout JSON Lines per session. One call per token_count event (its last_token_usage); an exactly repeated event
12
- // is dropped. Input there includes cached input, so it is split out; cache write only when the log has it.
13
- // sessionDb SQLite file with one row per session. Each session counts as one call, dated by the session start; a
14
- // column the file does not have is null, a real 0 stays 0.
15
- // runDb SQLite run-event files. Each "model.completed" event carries the usage of that attempt (not a running
16
- // total); events are summed per run id (per session when there is no run id). Reasoning tokens are
17
- // already part of the output count in that log, so nothing is added for them.
18
- //
19
- // Speed: files whose last change is older than the window are not opened; a line is parsed only when it can hold
20
- // usage; SQLite files are filtered by time inside SQLite and only the few needed fields are pulled out.
21
-
22
- import fs from 'node:fs';
23
- import path from 'node:path';
24
- import { authedPostWithRefresh } from '../api.js';
25
- import { UPGRADE_COMMAND } from '../client-version.js';
26
- import { pickLang } from '../model-pledge.js';
27
- import { t } from './text.js';
28
- import { listJsonl, loadSqlite } from './readers.js';
29
- import { dshRoots, readDshCalls, looksLikeDsh } from './dsh.js';
30
- import { RECIPES, recipeById, expandRoots, recipeForPath, readRecipeCalls } from './recipes.js';
31
-
32
- export const KIND = 'job_usage_sample';
33
- export const JOB_CHECK_PATH = '/api/v1/agent/hire/job-check';
34
- export const WINDOW_DAYS = 30;
35
- export const RECENT_CALLS = 20;
36
- export const REASON_MAX = 50;
37
- const DAY_MS = 86400e3;
38
-
39
- /** The one-sentence reasons sent when nothing usable can be read (each at most REASON_MAX characters). */
40
- export const REASONS = {
41
- no_log: { zh: '没找到这个程序的日志位置', en: 'No log location found for this program' },
42
- empty: { zh: '找到了日志,但最近 30 天没有记录', en: 'Logs found, but no records in the last 30 days' },
43
- model: { zh: '日志里的模型名是 auto 或空,无法计价', en: 'Model name is auto or empty; cannot be priced' },
44
- db: { zh: '日志数据库打不开', en: 'The log database cannot be opened' },
45
- node_old: { zh: 'Node 版本太旧,读不了 DeepSeek Harness 日志,需升级', en: 'Node too old to read DeepSeek logs; please upgrade' },
46
- };
47
-
48
- export function reasonText(key, env = process.env) {
49
- return REASONS[key][pickLang(env)];
50
- }
51
-
52
- // ---------------------------------------------------------------- small helpers
53
-
54
- function num(v) {
55
- const n = Number(v);
56
- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
57
- }
58
-
59
- /** A token count, or null when the log does not have that field at all. */
60
- function numOrNull(v) {
61
- return v == null ? null : num(v);
62
- }
63
-
64
- /** Epoch milliseconds from an ISO string or a number of seconds / milliseconds; null when unusable. */
65
- function toMs(v) {
66
- if (v == null || v === '') return null;
67
- const ms = typeof v === 'number' ? (v < 1e12 ? v * 1000 : v) : Date.parse(String(v));
68
- return Number.isFinite(ms) ? ms : null;
69
- }
70
-
71
- /** Add two counts where null means "not logged": null + null stays null. */
72
- function addN(a, b) {
73
- if (b == null) return a;
74
- return a == null ? b : a + b;
75
- }
76
-
77
- function isDir(p) {
78
- try { return fs.statSync(p).isDirectory(); } catch { return false; }
79
- }
80
-
81
- function isFile(p) {
82
- try { return fs.statSync(p).isFile(); } catch { return false; }
83
- }
84
-
85
- /**
86
- * Call fn(object), in file order, for each JSON line of a file that contains one of the `needles`. One file is read
87
- * at a time as raw bytes; only the lines holding a needle are decoded and parsed (decoding every byte of a large log
88
- * is what makes reading slow).
89
- */
90
- function eachLine(file, needles, fn) {
91
- let buf;
92
- try { buf = fs.readFileSync(file); } catch { return; }
93
- const starts = new Set();
94
- for (const n of needles) {
95
- let k = buf.indexOf(n);
96
- while (k !== -1) {
97
- const start = buf.lastIndexOf(10, k) + 1; // 10 = "\n"
98
- starts.add(start);
99
- const end = buf.indexOf(10, k);
100
- if (end === -1) break;
101
- k = buf.indexOf(n, end);
102
- }
103
- }
104
- for (const start of [...starts].sort((a, b) => a - b)) {
105
- if (buf[start] !== 123) continue; // 123 = "{"
106
- let end = buf.indexOf(10, start);
107
- if (end === -1) end = buf.length;
108
- let o = null;
109
- try { o = JSON.parse(buf.toString('utf8', start, end)); } catch { /* a broken line: skip it */ }
110
- if (o && typeof o === 'object') fn(o);
111
- }
112
- }
113
-
114
- /** The .jsonl files of a root: the root itself when it is one file (not filtered by age), else the ones inside a folder. */
115
- function jsonlFilesOf(root, sinceMs, filter) {
116
- if (isFile(root)) return [root];
117
- return isDir(root) ? listJsonl(root, sinceMs, filter) : [];
118
- }
119
-
120
- /** Shown names of the programs whose logs carry an entry (entrypoint / originator). */
121
- const CLIENT_NAMES = { msg_log: 'Claude Code', rollout: 'Codex' };
122
-
123
- /** { name, entries } for the output, or null when the log names no entry. */
124
- export function clientOf(reader, entries) {
125
- const list = [...new Set((entries || []).filter(Boolean))].sort();
126
- return CLIENT_NAMES[reader] && list.length ? { name: CLIENT_NAMES[reader], entries: list } : null;
127
- }
128
-
129
- // ---------------------------------------------------------------- local time
130
-
131
- const fmtCache = new Map();
132
-
133
- function localParts(ms, tz) {
134
- let f = fmtCache.get(tz);
135
- if (!f) {
136
- f = new Intl.DateTimeFormat('en-US', {
137
- timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
138
- });
139
- fmtCache.set(tz, f);
140
- }
141
- const o = {};
142
- for (const p of f.formatToParts(new Date(ms))) o[p.type] = p.value;
143
- return o;
144
- }
145
-
146
- /** The IANA time zone of this computer. */
147
- export function localTz() {
148
- try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; }
149
- }
150
-
151
- /** YYYY-MM-DD of `ms` in time zone `tz`. */
152
- export function localDate(ms, tz) {
153
- const p = localParts(ms, tz);
154
- return `${p.year}-${p.month}-${p.day}`;
155
- }
156
-
157
- /** ISO time with the local offset, e.g. 2026-11-18T23:30:05+08:00 (whole seconds). */
158
- export function isoLocal(ms, tz) {
159
- const p = localParts(ms, tz);
160
- const asUtc = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second));
161
- const off = Math.round((asUtc - Math.floor(ms / 1000) * 1000) / 60000);
162
- const a = Math.abs(off);
163
- const pad = (x) => String(x).padStart(2, '0');
164
- return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}${off < 0 ? '-' : '+'}${pad(Math.floor(a / 60))}:${pad(a % 60)}`;
165
- }
166
-
167
- /** The first local date of the window: today and the 29 days before it. */
168
- export function windowStartDate(nowMs, tz) {
169
- const [y, m, d] = localDate(nowMs, tz).split('-').map(Number);
170
- return new Date(Date.UTC(y, m - 1, d) - (WINDOW_DAYS - 1) * DAY_MS).toISOString().slice(0, 10);
171
- }
172
-
173
- /** A safe lower bound in epoch ms for reading (a little more than the window; the local-date filter is exact). */
174
- export function readSinceMs(nowMs) {
175
- return nowMs - (WINDOW_DAYS + 1) * DAY_MS;
176
- }
177
-
178
- // ---------------------------------------------------------------- msgLog
179
-
180
- export function readMsgLogSample({ roots, sinceMs }) {
181
- const byKey = new Map();
182
- const entries = new Set();
183
- let found = false;
184
- for (const root of roots) {
185
- if (!isDir(root) && !isFile(root)) continue;
186
- found = true;
187
- for (const file of jsonlFilesOf(root, sinceMs)) {
188
- eachLine(file, ['"usage"'], (o) => {
189
- if (o.type !== 'assistant' || !o.message || typeof o.message !== 'object') return;
190
- const m = o.message;
191
- const u = m.usage;
192
- if (!u || typeof u !== 'object') return;
193
- const model = m.model == null ? '' : String(m.model);
194
- if (model === '<synthetic>') return;
195
- const atMs = toMs(o.timestamp);
196
- if (atMs == null || atMs < sinceMs) return;
197
- if (typeof o.entrypoint === 'string' && o.entrypoint) entries.add(o.entrypoint);
198
- const key = m.id || o.requestId ? `${m.id || ''}\u0000${o.requestId || ''}` : `u\u0000${o.uuid || atMs}`;
199
- const old = byKey.get(key);
200
- if (old && old.atMs > atMs) return; // the last line of a key wins
201
- byKey.set(key, {
202
- atMs,
203
- model,
204
- input_tokens: num(u.input_tokens),
205
- output_tokens: num(u.output_tokens),
206
- cache_write_tokens: numOrNull(u.cache_creation_input_tokens),
207
- cache_read_tokens: numOrNull(u.cache_read_input_tokens),
208
- });
209
- });
210
- }
211
- }
212
- return { found, calls: [...byKey.values()], entries: [...entries] };
213
- }
214
-
215
- // ---------------------------------------------------------------- rollout
216
-
217
- export function readRolloutSample({ roots, sinceMs }) {
218
- const calls = [];
219
- const entries = new Set();
220
- let found = false;
221
- for (const root of roots) {
222
- if (!isDir(root) && !isFile(root)) continue;
223
- found = true;
224
- for (const file of jsonlFilesOf(root, sinceMs, (n) => n.startsWith('rollout-'))) {
225
- let model = '';
226
- let originator = '';
227
- const before = calls.length;
228
- const seen = new Set();
229
- eachLine(file, ['"token_count"', '"turn_context"', '"session_meta"'], (o) => {
230
- const p = o.payload && typeof o.payload === 'object' ? o.payload : {};
231
- if (o.type === 'session_meta') {
232
- if (!model && p.model) model = String(p.model);
233
- if (!originator && typeof p.originator === 'string') originator = p.originator;
234
- return;
235
- }
236
- if (o.type === 'turn_context') { if (p.model) model = String(p.model); return; }
237
- if (o.type !== 'event_msg' || p.type !== 'token_count' || !p.info || typeof p.info !== 'object') return;
238
- const last = p.info.last_token_usage;
239
- if (!last || typeof last !== 'object') return;
240
- const atMs = toMs(o.timestamp);
241
- if (atMs == null || atMs < sinceMs) return;
242
- // The same event written twice: same running total (or, without one, same time and same numbers).
243
- const total = p.info.total_token_usage;
244
- const key = total ? JSON.stringify(total) : `${o.timestamp}|${JSON.stringify(last)}`;
245
- if (seen.has(key)) return;
246
- seen.add(key);
247
- const cached = numOrNull(last.cached_input_tokens);
248
- calls.push({
249
- atMs,
250
- model,
251
- input_tokens: Math.max(0, num(last.input_tokens) - (cached || 0)),
252
- output_tokens: num(last.output_tokens),
253
- cache_write_tokens: Object.prototype.hasOwnProperty.call(last, 'cache_write_input_tokens') ? numOrNull(last.cache_write_input_tokens) : null,
254
- cache_read_tokens: cached,
255
- });
256
- });
257
- if (originator && calls.length > before) entries.add(originator);
258
- }
259
- }
260
- return { found, calls, entries: [...entries] };
261
- }
262
-
263
- // ---------------------------------------------------------------- sessionDb
264
-
265
- const SESSION_TOKEN_COLS = ['input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens'];
266
-
267
- export async function readSessionDbSample({ files, sinceMs, sqlite }) {
268
- const present = files.filter(isFile);
269
- if (!present.length) return { found: false, calls: [] };
270
- const Db = sqlite === undefined ? await loadSqlite() : sqlite;
271
- if (!Db) return { found: true, calls: [], dbError: true };
272
- const calls = [];
273
- let dbError = false;
274
- for (const f of present) {
275
- let db;
276
- try {
277
- db = new Db(f, { readOnly: true });
278
- const cols = new Set(db.prepare('PRAGMA table_info(sessions)').all().map((r) => r.name));
279
- if (!cols.has('started_at') || !cols.has('model')) throw new Error('no sessions table');
280
- const have = SESSION_TOKEN_COLS.filter((c) => cols.has(c));
281
- const sel = ['model', 'started_at', ...have].join(', ');
282
- const rows = db.prepare(`SELECT ${sel} FROM sessions WHERE started_at >= ?`).all(sinceMs / 1000);
283
- for (const r of rows) {
284
- const atMs = toMs(r.started_at);
285
- if (atMs == null) continue;
286
- const col = (c, fallback) => (have.includes(c) ? (r[c] == null ? fallback : num(r[c])) : null);
287
- calls.push({
288
- atMs,
289
- model: r.model == null ? '' : String(r.model),
290
- input_tokens: col('input_tokens', 0) || 0,
291
- output_tokens: col('output_tokens', 0) || 0,
292
- cache_write_tokens: col('cache_write_tokens', null),
293
- cache_read_tokens: col('cache_read_tokens', null),
294
- });
295
- }
296
- } catch {
297
- dbError = true;
298
- } finally {
299
- try { if (db) db.close(); } catch { /* ignore */ }
300
- }
301
- }
302
- return { found: true, calls, dbError };
303
- }
304
-
305
- // ---------------------------------------------------------------- runDb
306
-
307
- /** Main database files of one agent folder: *.sqlite, not the side files named <db>.sqlite.<something>.sqlite. */
308
- function agentDbFilesIn(dir) {
309
- let names;
310
- try { names = fs.readdirSync(dir); } catch { return []; }
311
- return names.filter((n) => n.endsWith('.sqlite') && !n.slice(0, -7).includes('.sqlite')).map((n) => path.join(dir, n)).filter(isFile);
312
- }
313
-
314
- /** Database files under an agents folder: agents/<name>/agent/*.sqlite. */
315
- function agentsDbFiles(agentsDir) {
316
- let names;
317
- try { names = fs.readdirSync(agentsDir); } catch { return []; }
318
- return names.flatMap((n) => agentDbFilesIn(path.join(agentsDir, n, 'agent')));
319
- }
320
-
321
- const RUN_SQL = `SELECT session_id AS sid, run_id AS rid, created_at AS c,
322
- json_extract(event_json, '$.ts') AS ts,
323
- COALESCE(json_extract(event_json, '$.modelId'), json_extract(event_json, '$.model')) AS model,
324
- json_type(event_json, '$.data.usage') AS ut,
325
- json_extract(event_json, '$.data.usage.input') AS i,
326
- json_extract(event_json, '$.data.usage.output') AS o,
327
- json_extract(event_json, '$.data.usage.cacheWrite') AS cw,
328
- json_extract(event_json, '$.data.usage.cacheRead') AS cr
329
- FROM trajectory_runtime_events
330
- WHERE created_at >= ? AND json_extract(event_json, '$.type') = 'model.completed'
331
- ORDER BY created_at, seq`;
332
-
333
- export async function readRunDbSample({ files, sinceMs, sqlite }) {
334
- const present = files.filter(isFile);
335
- if (!present.length) return { found: false, calls: [] };
336
- const Db = sqlite === undefined ? await loadSqlite() : sqlite;
337
- if (!Db) return { found: true, calls: [], dbError: true };
338
- const runs = new Map();
339
- let dbError = false;
340
- for (const [n, f] of present.entries()) {
341
- let db;
342
- try {
343
- db = new Db(f, { readOnly: true });
344
- const tbl = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_runtime_events'").all();
345
- if (!tbl.length) continue; // another kind of database: not a run log
346
- for (const r of db.prepare(RUN_SQL).all(sinceMs)) {
347
- if (r.ut !== 'object') continue; // an attempt that logged no usage
348
- const atMs = toMs(r.ts) ?? toMs(r.c);
349
- if (atMs == null) continue;
350
- const model = r.model == null ? '' : String(r.model);
351
- const key = `${n}\u0000${r.rid ? `r:${r.rid}` : `s:${r.sid}`}\u0000${model}`;
352
- const a = runs.get(key) || { atMs, model, input_tokens: 0, output_tokens: 0, cache_write_tokens: null, cache_read_tokens: null };
353
- a.atMs = Math.min(a.atMs, atMs);
354
- a.input_tokens += num(r.i);
355
- a.output_tokens += num(r.o);
356
- a.cache_write_tokens = addN(a.cache_write_tokens, numOrNull(r.cw));
357
- a.cache_read_tokens = addN(a.cache_read_tokens, numOrNull(r.cr));
358
- runs.set(key, a);
359
- }
360
- } catch {
361
- dbError = true;
362
- } finally {
363
- try { if (db) db.close(); } catch { /* ignore */ }
364
- }
365
- }
366
- return { found: true, calls: [...runs.values()], dbError };
367
- }
368
-
369
- // ---------------------------------------------------------------- dsh (DeepSeek Harness, v0.38.20)
370
-
371
- /** Session logs of the DeepSeek Harness: zstd frames, one call per assistant message (helper requests have no usage). */
372
- export function readDshSample({ roots, sinceMs }) {
373
- const r = readDshCalls(roots, sinceMs);
374
- if (r.oldNode) return { found: true, calls: [], oldNode: true };
375
- return {
376
- found: r.found,
377
- calls: r.calls.filter((c) => c.model).map((c) => ({
378
- atMs: c.atMs, model: c.model,
379
- input_tokens: c.input_tokens, output_tokens: c.output_tokens,
380
- cache_write_tokens: c.cache_write_tokens, cache_read_tokens: c.cache_read_tokens,
381
- })),
382
- };
383
- }
384
-
385
- // ---------------------------------------------------------------- where the logs are
386
-
387
- /** The usual log location of each reader on this computer. */
388
- export function defaultSources(home, env = {}) {
389
- const msg = [];
390
- if (env.CLAUDE_CONFIG_DIR) for (const d of String(env.CLAUDE_CONFIG_DIR).split(',')) if (d.trim()) msg.push(path.join(d.trim(), 'projects'));
391
- msg.push(path.join(home, '.claude', 'projects'), path.join(home, '.config', 'claude', 'projects'));
392
- const roll = [];
393
- if (env.CODEX_HOME) roll.push(path.join(String(env.CODEX_HOME), 'sessions'));
394
- roll.push(path.join(home, '.codex', 'sessions'));
395
- const sdb = [];
396
- if (env.HERMES_HOME) sdb.push(path.join(String(env.HERMES_HOME), 'state.db'));
397
- sdb.push(path.join(home, '.hermes', 'state.db'));
398
- const agents = path.join(home, '.openclaw', 'agents');
399
- const out = [
400
- { reader: 'msg_log', roots: [...new Set(msg)] },
401
- { reader: 'rollout', roots: [...new Set(roll)] },
402
- { reader: 'dsh_log', roots: dshRoots(home) },
403
- { reader: 'session_db', files: [...new Set(sdb)] },
404
- { reader: 'run_db', files: agentsDbFiles(agents), root: agents },
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;
413
- }
414
-
415
- /** `--from <path>`: the reader picked by the shape of the path, or null when nothing there looks like a log. */
416
- export function sourceFromPath(p) {
417
- const abs = path.resolve(String(p));
418
- let st;
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;
423
- if (st.isFile()) {
424
- if (abs.endsWith('.sqlite')) return { reader: 'run_db', files: [abs], root: abs };
425
- if (abs.endsWith('.db')) return { reader: 'session_db', files: [abs], root: abs };
426
- if (abs.endsWith('.jsonl.zstd')) return { reader: 'dsh_log', roots: [abs], root: abs };
427
- if (abs.endsWith('.jsonl')) {
428
- // One log file: a Codex session file by its name, otherwise by what its first lines look like.
429
- if (path.basename(abs).startsWith('rollout-')) return { reader: 'rollout', roots: [abs], root: abs };
430
- let head = '';
431
- try {
432
- const fd = fs.openSync(abs, 'r');
433
- const b = Buffer.alloc(65536);
434
- head = b.toString('utf8', 0, fs.readSync(fd, b, 0, b.length, 0));
435
- fs.closeSync(fd);
436
- } catch { return null; }
437
- if (/"(session_meta|token_count|turn_context)"/.test(head)) return { reader: 'rollout', roots: [abs], root: abs };
438
- if (/"type"\s*:\s*"(assistant|user)"/.test(head)) return { reader: 'msg_log', roots: [abs], root: abs };
439
- }
440
- return null;
441
- }
442
- if (!st.isDirectory()) return null;
443
- const base = path.basename(abs);
444
- if (looksLikeDsh(abs) || base === '.dsh') return { reader: 'dsh_log', roots: [isDir(path.join(abs, 'sessions')) ? path.join(abs, 'sessions') : abs], root: abs };
445
- if (isFile(path.join(abs, 'state.db'))) return { reader: 'session_db', files: [path.join(abs, 'state.db')], root: abs };
446
- if (base === 'agents') return { reader: 'run_db', files: agentsDbFiles(abs), root: abs };
447
- if (isDir(path.join(abs, 'agents')) && agentsDbFiles(path.join(abs, 'agents')).length) {
448
- return { reader: 'run_db', files: agentsDbFiles(path.join(abs, 'agents')), root: abs };
449
- }
450
- const one = [...agentDbFilesIn(path.join(abs, 'agent')), ...agentDbFilesIn(abs)];
451
- if (one.length) return { reader: 'run_db', files: one, root: abs };
452
- if (base === 'projects') return { reader: 'msg_log', roots: [abs], root: abs };
453
- if (base === 'sessions') return { reader: 'rollout', roots: [abs], root: abs };
454
- if (isDir(path.join(abs, 'projects'))) return { reader: 'msg_log', roots: [path.join(abs, 'projects')], root: abs };
455
- if (isDir(path.join(abs, 'sessions'))) return { reader: 'rollout', roots: [path.join(abs, 'sessions')], root: abs };
456
- const files = listJsonl(abs, 0);
457
- if (files.some((f) => path.basename(f).startsWith('rollout-'))) return { reader: 'rollout', roots: [abs], root: abs };
458
- if (files.length) return { reader: 'msg_log', roots: [abs], root: abs };
459
- return null;
460
- }
461
-
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
- }
473
- switch (src.reader) {
474
- case 'msg_log': return readMsgLogSample({ roots: src.roots, sinceMs });
475
- case 'rollout': return readRolloutSample({ roots: src.roots, sinceMs });
476
- case 'dsh_log': return readDshSample({ roots: src.roots, sinceMs });
477
- case 'session_db': return readSessionDbSample({ files: src.files, sinceMs, sqlite });
478
- case 'run_db': return readRunDbSample({ files: src.files, sinceMs, sqlite });
479
- default: return { found: false, calls: [] };
480
- }
481
- }
482
-
483
- // ---------------------------------------------------------------- the sample
484
-
485
- /** Calls dated (by local date) inside the window: today and the 29 days before. */
486
- export function windowCalls(calls, tz, nowMs) {
487
- const start = windowStartDate(nowMs, tz);
488
- const today = localDate(nowMs, tz);
489
- const out = [];
490
- for (const c of calls) {
491
- const date = localDate(c.atMs, tz);
492
- if (date >= start && date <= today) out.push({ ...c, date });
493
- }
494
- return out;
495
- }
496
-
497
- /** True when the platform could never price this model name. */
498
- function unpriceable(model) {
499
- const m = String(model || '').trim().toLowerCase();
500
- return !m || m === 'auto';
501
- }
502
-
503
- /**
504
- * The sample sent to the platform: the most recent 20 calls (oldest first) and one row per (local date, model).
505
- * Calls without a model name are left out (they cannot be attributed).
506
- */
507
- export function buildSample({ reader, calls, tz, nowMs }) {
508
- const inWin = windowCalls(calls, tz, nowMs).filter((c) => String(c.model || '').trim() !== '');
509
- inWin.sort((a, b) => a.atMs - b.atMs);
510
- const daily = new Map();
511
- for (const c of inWin) {
512
- const k = `${c.date}\u0000${c.model}`;
513
- const d = daily.get(k) || { date: c.date, model: c.model, input_tokens: 0, output_tokens: 0, cache_write_tokens: null, cache_read_tokens: null, calls: 0 };
514
- d.input_tokens += c.input_tokens;
515
- d.output_tokens += c.output_tokens;
516
- d.cache_write_tokens = addN(d.cache_write_tokens, c.cache_write_tokens);
517
- d.cache_read_tokens = addN(d.cache_read_tokens, c.cache_read_tokens);
518
- d.calls += 1;
519
- daily.set(k, d);
520
- }
521
- return {
522
- kind: KIND,
523
- tz,
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',
526
- reader,
527
- calls: inWin.slice(-RECENT_CALLS).map((c) => ({
528
- at: isoLocal(c.atMs, tz), model: c.model, input_tokens: c.input_tokens, output_tokens: c.output_tokens,
529
- cache_write_tokens: c.cache_write_tokens, cache_read_tokens: c.cache_read_tokens,
530
- })),
531
- daily: [...daily.values()].sort((a, b) => (a.date === b.date ? (a.model < b.model ? -1 : (a.model > b.model ? 1 : 0)) : (a.date < b.date ? -1 : 1))),
532
- };
533
- }
534
-
535
- /** Days, calls and models (with their share of input + output tokens) of a sample. */
536
- export function summarize(sample) {
537
- const days = new Set(sample.daily.map((d) => d.date)).size;
538
- const calls = sample.daily.reduce((n, d) => n + d.calls, 0);
539
- const per = new Map();
540
- for (const d of sample.daily) per.set(d.model, (per.get(d.model) || 0) + d.input_tokens + d.output_tokens);
541
- const total = [...per.values()].reduce((a, b) => a + b, 0);
542
- const models = [...per.entries()].sort((a, b) => b[1] - a[1]).map(([model, n]) => ({ model, share: total ? Math.round((n * 100) / total) : 0 }));
543
- return { days, calls, models };
544
- }
545
-
546
- // ---------------------------------------------------------------- the command
547
-
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
- }
555
- const r = src.root || (src.roots && src.roots.find(isDir)) || (src.files && src.files.find(isFile)) || '';
556
- return short(r);
557
- }
558
-
559
- function errorCodeOf(e) {
560
- const b = e && e.body && typeof e.body === 'object' ? e.body : null;
561
- if (!b) return null;
562
- const d = b.detail && typeof b.detail === 'object' ? b.detail : b;
563
- return typeof d.error === 'string' ? d : null;
564
- }
565
-
566
- /** Read the logs and decide what to send: { sample } | { several } | { unreadable: reason key }. */
567
- async function gatherSample(c, tz) {
568
- const nowMs = c.nowMs();
569
- const sinceMs = readSinceMs(nowMs);
570
- const sources = c.flags.from != null ? [c.fromSource] : defaultSources(c.home, c.env);
571
- const got = [];
572
- let found = false;
573
- let dbError = false;
574
- let oldNode = false;
575
- for (const src of sources) {
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
- }
583
- found = found || r.found;
584
- dbError = dbError || !!r.dbError;
585
- oldNode = oldNode || !!r.oldNode;
586
- const inWin = windowCalls(r.calls, tz, nowMs);
587
- if (inWin.length) got.push({ src, calls: r.calls, inWin, entries: r.entries || [], stats: r.stats || null });
588
- }
589
- if (!got.length) return { unreadable: oldNode ? 'node_old' : dbError ? 'db' : (found ? 'empty' : 'no_log') };
590
- if (got.length > 1) {
591
- return {
592
- several: got.map((g) => {
593
- const s = summarize(buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }));
594
- return { reader: g.src.reader, root: shortRoot(g.src, c.home), days: s.days, calls: s.calls, models: s.models.map((m) => m.model) };
595
- }),
596
- };
597
- }
598
- const g = got[0];
599
- if (g.inWin.every((x) => unpriceable(x.model))) return { unreadable: 'model' };
600
- const noModel = g.inWin.filter((x) => String(x.model || '').trim() === '').length;
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 } };
605
- }
606
-
607
- function resultLines(d, env) {
608
- const lines = [t('sample.state', { state: d.state != null ? d.state : '-', reason: d.reason != null ? d.reason : '-' }, env)];
609
- if (Array.isArray(d.main_models) && d.main_models.length) lines.push(t('sample.main_models', { v: d.main_models.join(', ') }, env));
610
- if (d.reason === 'model_unpriced') {
611
- const m = d.model || (Array.isArray(d.unpriced_models) ? d.unpriced_models.join(', ') : '');
612
- lines.push(t('sample.unpriced', { model: m }, env));
613
- }
614
- if (d.reason === 'no_log') lines.push(t('sample.no_log', {}, env));
615
- return lines;
616
- }
617
-
618
- /**
619
- * anytowork usage sample [--from <path>] [--dry-run] [--unreadable "<reason>"] [--json]
620
- * Exit: 0 delivered (whatever the platform decided) or dry run / 1 refused / 2 bad arguments or several programs /
621
- * 4 the CLI is too old.
622
- */
623
- export async function cmdSample(c) {
624
- const env = c.env;
625
- const tz = c.tz || localTz();
626
- let body;
627
- let summary = null;
628
- let client = null;
629
- let drops = null;
630
- let stats = null;
631
- if (c.flags.unreadable != null) {
632
- const reason = String(c.flags.unreadable).replace(/\s+/g, ' ').trim();
633
- if (!reason || reason.length > REASON_MAX) return c.fail(2, 'bad_reason', t('sample.bad_reason', { max: REASON_MAX }, env));
634
- body = { kind: KIND, unreadable: true, reason };
635
- } else {
636
- if (c.flags.from != null) {
637
- const p = String(c.flags.from).replace(/^~(?=$|\/)/, c.home);
638
- if (!fs.existsSync(path.resolve(p))) return c.fail(2, 'from_not_found', t('sample.from_missing', { path: c.flags.from }, env));
639
- c.fromSource = sourceFromPath(p);
640
- }
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
- }
650
- if (g.several) {
651
- if (c.flags.json) {
652
- c.log(JSON.stringify({ ok: false, error: 'several_sources', message: t('sample.several', {}, env), sources: g.several }));
653
- } else {
654
- c.err(t('sample.several', {}, env));
655
- for (const s of g.several) c.err(t('sample.several_row', { ...s, models: s.models.join(', ') }, env));
656
- }
657
- return 2;
658
- }
659
- body = g.sample || { kind: KIND, unreadable: true, reason: reasonText(g.unreadable, env) };
660
- if (g.sample) { summary = summarize(g.sample); client = g.client; drops = g.drops || null; stats = g.stats || null; }
661
- }
662
- const clientField = client ? { client } : {};
663
- const clientLine = client
664
- ? [t('sample.client', { v: client.entries.length ? client.name + ' · ' + client.entries.join(', ') : client.name }, env)]
665
- : [];
666
-
667
- if (c.flags.dryRun) {
668
- if (c.flags.json) { c.log(JSON.stringify({ ok: true, dry_run: true, sample: body, ...clientField })); return 0; }
669
- if (body.unreadable) {
670
- c.log(t('sample.dry_unreadable', { reason: body.reason }, env));
671
- } else {
672
- c.log(t('sample.dry_title', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
673
- for (const l of clientLine) c.log(l);
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
- }
679
- if (drops && (drops.old || drops.nomodel)) c.log(t('sample.dry_dropped', drops, env));
680
- }
681
- if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
682
- c.log(t('sample.own_only', {}, env));
683
- return 0;
684
- }
685
-
686
- let d;
687
- try {
688
- d = await authedPostWithRefresh(c.baseUrl, JOB_CHECK_PATH, c.credOpts, body, null, { fetchImpl: c.fetchImpl });
689
- } catch (e) {
690
- const info = errorCodeOf(e) || {};
691
- if (e && (e.upgradeRequired || Number(e.status) === 426)) {
692
- const hint = t('usage.upgrade', { min: info.min_version || '', cmd: UPGRADE_COMMAND }, env);
693
- return c.fail(4, info.error || 'cli_upgrade_required', e.upgradeRequired ? e.message : hint);
694
- }
695
- return c.fail(1, info.error || 'refused', t('sample.refused', { msg: e && e.message ? e.message : String(e) }, env));
696
- }
697
- d = d && typeof d === 'object' ? d : {};
698
- if (c.flags.json) {
699
- c.log(JSON.stringify({ ok: true, delivered: true, reader: body.reader || null, ...clientField, result: d }));
700
- return 0;
701
- }
702
- c.log(body.unreadable ? t('sample.delivered_unreadable', { reason: body.reason }, env)
703
- : t('sample.delivered', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
704
- for (const l of clientLine) c.log(l);
705
- for (const l of resultLines(d, env)) c.log(l);
706
- if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
707
- return 0;
708
- }