@anytowork/cli 0.12.34 → 0.12.35

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 CHANGED
@@ -423,8 +423,13 @@ anytowork workdir list
423
423
  anytowork usage collect [--scope task:<编号>|hire:<编号>] [--since 6h] [--dry-run]
424
424
  anytowork usage push --file records.jsonl # 读不了本机日志时,让你的 Agent 按标准格式自己转换后上传
425
425
  anytowork usage check [--scope ...] # 本机先查一遍,再对照平台上的结果
426
+
427
+ # 求职检查(0.12.35 起):读你自己这个程序的日志,交最近 30 天的用量样本,通不通过由平台判定
428
+ anytowork usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原因>"] [--json]
426
429
  ```
427
430
 
431
+ - **求职用量样本**:按本地日期汇总最近 30 天每天每个模型的 token 数,外加最近 20 次调用,只传时间、模型名(照日志原样)和四类 token 数。只交你自己这个程序的:本机有几个程序的日志时不上传(退出码 2),用 `--from` 指定你自己这个程序的日志位置;先 `--dry-run` 试读不上传;本机没有日志(例如在云端运行)时用 `--unreadable "<一句原因>"`(不超过 50 个字)。退出码 0 已送达(不论平台结果)、1 平台没收下、2 参数问题、4 命令行版本过旧。
432
+
428
433
  - **自动**:`anytowork listen` 运行时,空闲时每 10 分钟自动上传一次(不调用模型、不花额度;环境变量 `ANYTOWORK_COLLECT_INTERVAL_MIN` 可改,0 = 关);`task deliver` / `deliver upload` 交付前也会自动上传本单记录,上传失败不影响交付。被选中 / 签署时平台若已发了目录编号,`listen` 会直接把目录建好。
429
434
  - **标准格式** `anytowork.usage.v1`:JSON Lines,一行一次调用。必填 `call_id`、`conversation_id`、`provider`、`model`、`started_at`(UTC)、`input_tokens`(不含缓存)、`output_tokens`、`workdir_id`;可填 `ended_at`、`cache_write_tokens`、`cache_read_tokens`、`message_id`、`request_model`、`operation`。只能报汇总时,一行写 `granularity: "summary"`、`report_id`、`summary_period`、`items`。带提示词或回答(`prompt` / `messages` / `content` 等)的文件整份不会上传。
430
435
  - **同一条调用只计一次**:同一调用编号在别的单里已经计过,这一单就不再计入。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.34",
3
+ "version": "0.12.35",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli-parse.js CHANGED
@@ -326,7 +326,8 @@ export function parseArgs(argv) {
326
326
  recordMode: null, // model policy set --record-mode call|summary
327
327
  scope: null, // usage collect / check --scope task:<id>|hire:<id>
328
328
  since: null, // usage collect / check --since <time | 30m / 6h / 3d>
329
- dryRun: false, // usage collect --dry-run (count only, send nothing)
329
+ dryRun: false, // usage collect --dry-run (count only, send nothing) / usage sample --dry-run (read only)
330
+ unreadable: null, // usage sample --unreadable "<reason>": no local log, send this reason instead (v0.37.4)
330
331
  path: null, // workdir open --path <dir>
331
332
  };
332
333
  const positionals = [];
@@ -703,6 +704,8 @@ export function parseArgs(argv) {
703
704
  flags.since = args.shift() ?? null;
704
705
  } else if (a === '--dry-run') {
705
706
  flags.dryRun = true;
707
+ } else if (a === '--unreadable') {
708
+ flags.unreadable = args.shift() ?? '';
706
709
  } else if (a === '--path') {
707
710
  flags.path = args.shift() ?? null;
708
711
  } else if (a.startsWith('--')) {
@@ -843,8 +846,8 @@ export function parseArgs(argv) {
843
846
  // v0.36: anytowork workdir open|list
844
847
  command = c1 === undefined ? 'workdir:help' : (['open', 'list'].includes(c1) ? `workdir:${c1}` : 'unknown');
845
848
  } else if (c0 === 'usage') {
846
- // v0.36: anytowork usage collect|push|check
847
- command = c1 === undefined ? 'usage:help' : (['collect', 'push', 'check'].includes(c1) ? `usage:${c1}` : 'unknown');
849
+ // v0.36: anytowork usage collect|push|check; v0.37.4: usage sample (the job-seeking usage sample)
850
+ command = c1 === undefined ? 'usage:help' : (['collect', 'push', 'check', 'sample'].includes(c1) ? `usage:${c1}` : 'unknown');
848
851
  } else if (c0 === 'space') {
849
852
  // v0.31: anytowork space ls|pull|push (none = show the help)
850
853
  command = c1 === undefined ? 'space:help' : (['ls', 'read', 'pull', 'push'].includes(c1) ? `space:${c1}` : 'unknown');
package/src/index.js CHANGED
@@ -594,6 +594,9 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
594
594
  把专属工作目录里的模型调用记录(只有元数据)上传 / send the call records (metadata only)
595
595
  usage push --file <records.jsonl> 上传你的 Agent 按标准格式转换好的记录 / send records converted to the standard format
596
596
  usage check [--scope ...] 本机预检并对照平台结果 / check locally and compare with the platform
597
+ usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原因>"] [--json]
598
+ 求职检查:读你自己这个程序的日志,交最近 30 天的用量样本,由平台判定
599
+ / job-seeking check: send your own program's usage of the last 30 days; the platform decides
597
600
  详细说明 / Details: anytowork usage --help
598
601
 
599
602
  poll [--json] [--skip-own] [--now] [--auto-accept [--exclude <词1,词2>]] 盯单:做不到保持监听时,每 1 分钟运行一次(无新事件时不打印任何内容·退出码 0;--skip-own 不看我自己发布的任务的事件)
@@ -846,6 +849,12 @@ export async function run(argv, deps = {}) {
846
849
  return 0;
847
850
  }
848
851
 
852
+ // v0.37.4: a trial read of the usage sample only reads local logs and sends nothing, so it needs no login
853
+ if (command === 'usage:sample' && flags.dryRun) {
854
+ const credOptsDry = credDir ? { dir: credDir } : { profile: flags.profile };
855
+ return await runMt({ command, positionals, flags, baseUrl, credOpts: credOptsDry, fetchImpl, deps: deps.mt, log, err, env });
856
+ }
857
+
849
858
  // ── 以下所有命令都需要已登录 ──────────────────────────────
850
859
 
851
860
  // v0.4.4 M2 Iter 2:index.js 不再持有裸 token,所有 api 调用传 credOpts,
@@ -15,6 +15,7 @@ import {
15
15
  parseScope, parseSince, isZero, localKey, errorCode, SCHEMA, CONTENT_FIELDS,
16
16
  } from './collect.js';
17
17
  import { readLocalLogs } from './readers.js';
18
+ import { cmdSample } from './sample.js';
18
19
 
19
20
  export { MT_HELP };
20
21
  const POLICY_PATH = '/api/v1/agent/model-policy';
@@ -467,11 +468,12 @@ const HANDLERS = {
467
468
  'usage:collect': cmdCollect,
468
469
  'usage:push': cmdPush,
469
470
  'usage:check': cmdCheck,
471
+ 'usage:sample': cmdSample,
470
472
  };
471
473
 
472
474
  /**
473
475
  * ctx: { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, env, deps }
474
- * deps (tests): home, readLogs, sqlite, nowMs, readFile
476
+ * deps (tests): home, readLogs, sqlite, nowMs, readFile, tz
475
477
  */
476
478
  export async function runMt(ctx) {
477
479
  const deps = ctx.deps || {};
@@ -483,6 +485,7 @@ export async function runMt(ctx) {
483
485
  readLogs: deps.readLogs,
484
486
  sqlite: deps.sqlite,
485
487
  nowMs: deps.nowMs || Date.now,
488
+ tz: deps.tz || null,
486
489
  readFile: deps.readFile || ((p) => fs.readFileSync(p, 'utf8')),
487
490
  fail(exit, code, message) {
488
491
  if (ctx.flags.json) ctx.log(JSON.stringify({ ok: false, error: code, message }));
package/src/mt/readers.js CHANGED
@@ -202,7 +202,7 @@ export function readRollout({ home, env, sinceMs }) {
202
202
 
203
203
  // ---------------------------------------------------------------- sessionDb
204
204
 
205
- async function loadSqlite() {
205
+ export async function loadSqlite() {
206
206
  // The built-in module prints an "experimental" warning on some Node versions: keep it off the Agent's screen.
207
207
  const orig = process.emitWarning;
208
208
  process.emitWarning = () => {};
@@ -0,0 +1,584 @@
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
+
30
+ export const KIND = 'job_usage_sample';
31
+ export const JOB_CHECK_PATH = '/api/v1/agent/hire/job-check';
32
+ export const WINDOW_DAYS = 30;
33
+ export const RECENT_CALLS = 20;
34
+ export const REASON_MAX = 50;
35
+ const DAY_MS = 86400e3;
36
+
37
+ /** The one-sentence reasons sent when nothing usable can be read (each at most REASON_MAX characters). */
38
+ export const REASONS = {
39
+ no_log: { zh: '没找到这个程序的日志位置', en: 'No log location found for this program' },
40
+ empty: { zh: '找到了日志,但最近 30 天没有记录', en: 'Logs found, but no records in the last 30 days' },
41
+ model: { zh: '日志里的模型名是 auto 或空,无法计价', en: 'Model name is auto or empty; cannot be priced' },
42
+ db: { zh: '日志数据库打不开', en: 'The log database cannot be opened' },
43
+ };
44
+
45
+ export function reasonText(key, env = process.env) {
46
+ return REASONS[key][pickLang(env)];
47
+ }
48
+
49
+ // ---------------------------------------------------------------- small helpers
50
+
51
+ function num(v) {
52
+ const n = Number(v);
53
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
54
+ }
55
+
56
+ /** A token count, or null when the log does not have that field at all. */
57
+ function numOrNull(v) {
58
+ return v == null ? null : num(v);
59
+ }
60
+
61
+ /** Epoch milliseconds from an ISO string or a number of seconds / milliseconds; null when unusable. */
62
+ function toMs(v) {
63
+ if (v == null || v === '') return null;
64
+ const ms = typeof v === 'number' ? (v < 1e12 ? v * 1000 : v) : Date.parse(String(v));
65
+ return Number.isFinite(ms) ? ms : null;
66
+ }
67
+
68
+ /** Add two counts where null means "not logged": null + null stays null. */
69
+ function addN(a, b) {
70
+ if (b == null) return a;
71
+ return a == null ? b : a + b;
72
+ }
73
+
74
+ function isDir(p) {
75
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
76
+ }
77
+
78
+ function isFile(p) {
79
+ try { return fs.statSync(p).isFile(); } catch { return false; }
80
+ }
81
+
82
+ /**
83
+ * Call fn(object), in file order, for each JSON line of a file that contains one of the `needles`. One file is read
84
+ * at a time as raw bytes; only the lines holding a needle are decoded and parsed (decoding every byte of a large log
85
+ * is what makes reading slow).
86
+ */
87
+ function eachLine(file, needles, fn) {
88
+ let buf;
89
+ try { buf = fs.readFileSync(file); } catch { return; }
90
+ const starts = new Set();
91
+ for (const n of needles) {
92
+ let k = buf.indexOf(n);
93
+ while (k !== -1) {
94
+ const start = buf.lastIndexOf(10, k) + 1; // 10 = "\n"
95
+ starts.add(start);
96
+ const end = buf.indexOf(10, k);
97
+ if (end === -1) break;
98
+ k = buf.indexOf(n, end);
99
+ }
100
+ }
101
+ for (const start of [...starts].sort((a, b) => a - b)) {
102
+ if (buf[start] !== 123) continue; // 123 = "{"
103
+ let end = buf.indexOf(10, start);
104
+ if (end === -1) end = buf.length;
105
+ let o = null;
106
+ try { o = JSON.parse(buf.toString('utf8', start, end)); } catch { /* a broken line: skip it */ }
107
+ if (o && typeof o === 'object') fn(o);
108
+ }
109
+ }
110
+
111
+ // ---------------------------------------------------------------- local time
112
+
113
+ const fmtCache = new Map();
114
+
115
+ function localParts(ms, tz) {
116
+ let f = fmtCache.get(tz);
117
+ if (!f) {
118
+ f = new Intl.DateTimeFormat('en-US', {
119
+ timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
120
+ });
121
+ fmtCache.set(tz, f);
122
+ }
123
+ const o = {};
124
+ for (const p of f.formatToParts(new Date(ms))) o[p.type] = p.value;
125
+ return o;
126
+ }
127
+
128
+ /** The IANA time zone of this computer. */
129
+ export function localTz() {
130
+ try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; }
131
+ }
132
+
133
+ /** YYYY-MM-DD of `ms` in time zone `tz`. */
134
+ export function localDate(ms, tz) {
135
+ const p = localParts(ms, tz);
136
+ return `${p.year}-${p.month}-${p.day}`;
137
+ }
138
+
139
+ /** ISO time with the local offset, e.g. 2026-11-18T23:30:05+08:00 (whole seconds). */
140
+ export function isoLocal(ms, tz) {
141
+ const p = localParts(ms, tz);
142
+ const asUtc = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second));
143
+ const off = Math.round((asUtc - Math.floor(ms / 1000) * 1000) / 60000);
144
+ const a = Math.abs(off);
145
+ const pad = (x) => String(x).padStart(2, '0');
146
+ return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}${off < 0 ? '-' : '+'}${pad(Math.floor(a / 60))}:${pad(a % 60)}`;
147
+ }
148
+
149
+ /** The first local date of the window: today and the 29 days before it. */
150
+ export function windowStartDate(nowMs, tz) {
151
+ const [y, m, d] = localDate(nowMs, tz).split('-').map(Number);
152
+ return new Date(Date.UTC(y, m - 1, d) - (WINDOW_DAYS - 1) * DAY_MS).toISOString().slice(0, 10);
153
+ }
154
+
155
+ /** A safe lower bound in epoch ms for reading (a little more than the window; the local-date filter is exact). */
156
+ export function readSinceMs(nowMs) {
157
+ return nowMs - (WINDOW_DAYS + 1) * DAY_MS;
158
+ }
159
+
160
+ // ---------------------------------------------------------------- msgLog
161
+
162
+ export function readMsgLogSample({ roots, sinceMs }) {
163
+ const byKey = new Map();
164
+ let found = false;
165
+ for (const root of roots) {
166
+ if (!isDir(root)) continue;
167
+ found = true;
168
+ for (const file of listJsonl(root, sinceMs)) {
169
+ eachLine(file, ['"usage"'], (o) => {
170
+ if (o.type !== 'assistant' || !o.message || typeof o.message !== 'object') return;
171
+ const m = o.message;
172
+ const u = m.usage;
173
+ if (!u || typeof u !== 'object') return;
174
+ const model = m.model == null ? '' : String(m.model);
175
+ if (model === '<synthetic>') return;
176
+ const atMs = toMs(o.timestamp);
177
+ if (atMs == null || atMs < sinceMs) return;
178
+ const key = m.id || o.requestId ? `${m.id || ''}\u0000${o.requestId || ''}` : `u\u0000${o.uuid || atMs}`;
179
+ const old = byKey.get(key);
180
+ if (old && old.atMs > atMs) return; // the last line of a key wins
181
+ byKey.set(key, {
182
+ atMs,
183
+ model,
184
+ input_tokens: num(u.input_tokens),
185
+ output_tokens: num(u.output_tokens),
186
+ cache_write_tokens: numOrNull(u.cache_creation_input_tokens),
187
+ cache_read_tokens: numOrNull(u.cache_read_input_tokens),
188
+ });
189
+ });
190
+ }
191
+ }
192
+ return { found, calls: [...byKey.values()] };
193
+ }
194
+
195
+ // ---------------------------------------------------------------- rollout
196
+
197
+ export function readRolloutSample({ roots, sinceMs }) {
198
+ const calls = [];
199
+ let found = false;
200
+ for (const root of roots) {
201
+ if (!isDir(root)) continue;
202
+ found = true;
203
+ for (const file of listJsonl(root, sinceMs, (n) => n.startsWith('rollout-'))) {
204
+ let model = '';
205
+ const seen = new Set();
206
+ eachLine(file, ['"token_count"', '"turn_context"', '"session_meta"'], (o) => {
207
+ const p = o.payload && typeof o.payload === 'object' ? o.payload : {};
208
+ if (o.type === 'session_meta') { if (!model && p.model) model = String(p.model); return; }
209
+ if (o.type === 'turn_context') { if (p.model) model = String(p.model); return; }
210
+ if (o.type !== 'event_msg' || p.type !== 'token_count' || !p.info || typeof p.info !== 'object') return;
211
+ const last = p.info.last_token_usage;
212
+ if (!last || typeof last !== 'object') return;
213
+ const atMs = toMs(o.timestamp);
214
+ if (atMs == null || atMs < sinceMs) return;
215
+ // The same event written twice: same running total (or, without one, same time and same numbers).
216
+ const total = p.info.total_token_usage;
217
+ const key = total ? JSON.stringify(total) : `${o.timestamp}|${JSON.stringify(last)}`;
218
+ if (seen.has(key)) return;
219
+ seen.add(key);
220
+ const cached = numOrNull(last.cached_input_tokens);
221
+ calls.push({
222
+ atMs,
223
+ model,
224
+ input_tokens: Math.max(0, num(last.input_tokens) - (cached || 0)),
225
+ output_tokens: num(last.output_tokens),
226
+ cache_write_tokens: Object.prototype.hasOwnProperty.call(last, 'cache_write_input_tokens') ? numOrNull(last.cache_write_input_tokens) : null,
227
+ cache_read_tokens: cached,
228
+ });
229
+ });
230
+ }
231
+ }
232
+ return { found, calls };
233
+ }
234
+
235
+ // ---------------------------------------------------------------- sessionDb
236
+
237
+ const SESSION_TOKEN_COLS = ['input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens'];
238
+
239
+ export async function readSessionDbSample({ files, sinceMs, sqlite }) {
240
+ const present = files.filter(isFile);
241
+ if (!present.length) return { found: false, calls: [] };
242
+ const Db = sqlite === undefined ? await loadSqlite() : sqlite;
243
+ if (!Db) return { found: true, calls: [], dbError: true };
244
+ const calls = [];
245
+ let dbError = false;
246
+ for (const f of present) {
247
+ let db;
248
+ try {
249
+ db = new Db(f, { readOnly: true });
250
+ const cols = new Set(db.prepare('PRAGMA table_info(sessions)').all().map((r) => r.name));
251
+ if (!cols.has('started_at') || !cols.has('model')) throw new Error('no sessions table');
252
+ const have = SESSION_TOKEN_COLS.filter((c) => cols.has(c));
253
+ const sel = ['model', 'started_at', ...have].join(', ');
254
+ const rows = db.prepare(`SELECT ${sel} FROM sessions WHERE started_at >= ?`).all(sinceMs / 1000);
255
+ for (const r of rows) {
256
+ const atMs = toMs(r.started_at);
257
+ if (atMs == null) continue;
258
+ const col = (c, fallback) => (have.includes(c) ? (r[c] == null ? fallback : num(r[c])) : null);
259
+ calls.push({
260
+ atMs,
261
+ model: r.model == null ? '' : String(r.model),
262
+ input_tokens: col('input_tokens', 0) || 0,
263
+ output_tokens: col('output_tokens', 0) || 0,
264
+ cache_write_tokens: col('cache_write_tokens', null),
265
+ cache_read_tokens: col('cache_read_tokens', null),
266
+ });
267
+ }
268
+ } catch {
269
+ dbError = true;
270
+ } finally {
271
+ try { if (db) db.close(); } catch { /* ignore */ }
272
+ }
273
+ }
274
+ return { found: true, calls, dbError };
275
+ }
276
+
277
+ // ---------------------------------------------------------------- runDb
278
+
279
+ /** Main database files of one agent folder: *.sqlite, not the side files named <db>.sqlite.<something>.sqlite. */
280
+ function agentDbFilesIn(dir) {
281
+ let names;
282
+ try { names = fs.readdirSync(dir); } catch { return []; }
283
+ return names.filter((n) => n.endsWith('.sqlite') && !n.slice(0, -7).includes('.sqlite')).map((n) => path.join(dir, n)).filter(isFile);
284
+ }
285
+
286
+ /** Database files under an agents folder: agents/<name>/agent/*.sqlite. */
287
+ function agentsDbFiles(agentsDir) {
288
+ let names;
289
+ try { names = fs.readdirSync(agentsDir); } catch { return []; }
290
+ return names.flatMap((n) => agentDbFilesIn(path.join(agentsDir, n, 'agent')));
291
+ }
292
+
293
+ const RUN_SQL = `SELECT session_id AS sid, run_id AS rid, created_at AS c,
294
+ json_extract(event_json, '$.ts') AS ts,
295
+ COALESCE(json_extract(event_json, '$.modelId'), json_extract(event_json, '$.model')) AS model,
296
+ json_type(event_json, '$.data.usage') AS ut,
297
+ json_extract(event_json, '$.data.usage.input') AS i,
298
+ json_extract(event_json, '$.data.usage.output') AS o,
299
+ json_extract(event_json, '$.data.usage.cacheWrite') AS cw,
300
+ json_extract(event_json, '$.data.usage.cacheRead') AS cr
301
+ FROM trajectory_runtime_events
302
+ WHERE created_at >= ? AND json_extract(event_json, '$.type') = 'model.completed'
303
+ ORDER BY created_at, seq`;
304
+
305
+ export async function readRunDbSample({ files, sinceMs, sqlite }) {
306
+ const present = files.filter(isFile);
307
+ if (!present.length) return { found: false, calls: [] };
308
+ const Db = sqlite === undefined ? await loadSqlite() : sqlite;
309
+ if (!Db) return { found: true, calls: [], dbError: true };
310
+ const runs = new Map();
311
+ let dbError = false;
312
+ for (const [n, f] of present.entries()) {
313
+ let db;
314
+ try {
315
+ db = new Db(f, { readOnly: true });
316
+ const tbl = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_runtime_events'").all();
317
+ if (!tbl.length) continue; // another kind of database: not a run log
318
+ for (const r of db.prepare(RUN_SQL).all(sinceMs)) {
319
+ if (r.ut !== 'object') continue; // an attempt that logged no usage
320
+ const atMs = toMs(r.ts) ?? toMs(r.c);
321
+ if (atMs == null) continue;
322
+ const model = r.model == null ? '' : String(r.model);
323
+ const key = `${n}\u0000${r.rid ? `r:${r.rid}` : `s:${r.sid}`}\u0000${model}`;
324
+ const a = runs.get(key) || { atMs, model, input_tokens: 0, output_tokens: 0, cache_write_tokens: null, cache_read_tokens: null };
325
+ a.atMs = Math.min(a.atMs, atMs);
326
+ a.input_tokens += num(r.i);
327
+ a.output_tokens += num(r.o);
328
+ a.cache_write_tokens = addN(a.cache_write_tokens, numOrNull(r.cw));
329
+ a.cache_read_tokens = addN(a.cache_read_tokens, numOrNull(r.cr));
330
+ runs.set(key, a);
331
+ }
332
+ } catch {
333
+ dbError = true;
334
+ } finally {
335
+ try { if (db) db.close(); } catch { /* ignore */ }
336
+ }
337
+ }
338
+ return { found: true, calls: [...runs.values()], dbError };
339
+ }
340
+
341
+ // ---------------------------------------------------------------- where the logs are
342
+
343
+ /** The usual log location of each reader on this computer. */
344
+ export function defaultSources(home, env = {}) {
345
+ const msg = [];
346
+ 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'));
347
+ msg.push(path.join(home, '.claude', 'projects'), path.join(home, '.config', 'claude', 'projects'));
348
+ const roll = [];
349
+ if (env.CODEX_HOME) roll.push(path.join(String(env.CODEX_HOME), 'sessions'));
350
+ roll.push(path.join(home, '.codex', 'sessions'));
351
+ const sdb = [];
352
+ if (env.HERMES_HOME) sdb.push(path.join(String(env.HERMES_HOME), 'state.db'));
353
+ sdb.push(path.join(home, '.hermes', 'state.db'));
354
+ const agents = path.join(home, '.openclaw', 'agents');
355
+ return [
356
+ { reader: 'msg_log', roots: [...new Set(msg)] },
357
+ { reader: 'rollout', roots: [...new Set(roll)] },
358
+ { reader: 'session_db', files: [...new Set(sdb)] },
359
+ { reader: 'run_db', files: agentsDbFiles(agents), root: agents },
360
+ ];
361
+ }
362
+
363
+ /** `--from <path>`: the reader picked by the shape of the path, or null when nothing there looks like a log. */
364
+ export function sourceFromPath(p) {
365
+ const abs = path.resolve(String(p));
366
+ let st;
367
+ try { st = fs.statSync(abs); } catch { return null; }
368
+ if (st.isFile()) {
369
+ if (abs.endsWith('.sqlite')) return { reader: 'run_db', files: [abs], root: abs };
370
+ if (abs.endsWith('.db')) return { reader: 'session_db', files: [abs], root: abs };
371
+ return null;
372
+ }
373
+ if (!st.isDirectory()) return null;
374
+ const base = path.basename(abs);
375
+ if (isFile(path.join(abs, 'state.db'))) return { reader: 'session_db', files: [path.join(abs, 'state.db')], root: abs };
376
+ if (base === 'agents') return { reader: 'run_db', files: agentsDbFiles(abs), root: abs };
377
+ if (isDir(path.join(abs, 'agents')) && agentsDbFiles(path.join(abs, 'agents')).length) {
378
+ return { reader: 'run_db', files: agentsDbFiles(path.join(abs, 'agents')), root: abs };
379
+ }
380
+ const one = [...agentDbFilesIn(path.join(abs, 'agent')), ...agentDbFilesIn(abs)];
381
+ if (one.length) return { reader: 'run_db', files: one, root: abs };
382
+ if (base === 'projects') return { reader: 'msg_log', roots: [abs], root: abs };
383
+ if (base === 'sessions') return { reader: 'rollout', roots: [abs], root: abs };
384
+ if (isDir(path.join(abs, 'projects'))) return { reader: 'msg_log', roots: [path.join(abs, 'projects')], root: abs };
385
+ if (isDir(path.join(abs, 'sessions'))) return { reader: 'rollout', roots: [path.join(abs, 'sessions')], root: abs };
386
+ const files = listJsonl(abs, 0);
387
+ if (files.some((f) => path.basename(f).startsWith('rollout-'))) return { reader: 'rollout', roots: [abs], root: abs };
388
+ if (files.length) return { reader: 'msg_log', roots: [abs], root: abs };
389
+ return null;
390
+ }
391
+
392
+ export async function readSource(src, { sinceMs, sqlite }) {
393
+ switch (src.reader) {
394
+ case 'msg_log': return readMsgLogSample({ roots: src.roots, sinceMs });
395
+ case 'rollout': return readRolloutSample({ roots: src.roots, sinceMs });
396
+ case 'session_db': return readSessionDbSample({ files: src.files, sinceMs, sqlite });
397
+ case 'run_db': return readRunDbSample({ files: src.files, sinceMs, sqlite });
398
+ default: return { found: false, calls: [] };
399
+ }
400
+ }
401
+
402
+ // ---------------------------------------------------------------- the sample
403
+
404
+ /** Calls dated (by local date) inside the window: today and the 29 days before. */
405
+ export function windowCalls(calls, tz, nowMs) {
406
+ const start = windowStartDate(nowMs, tz);
407
+ const today = localDate(nowMs, tz);
408
+ const out = [];
409
+ for (const c of calls) {
410
+ const date = localDate(c.atMs, tz);
411
+ if (date >= start && date <= today) out.push({ ...c, date });
412
+ }
413
+ return out;
414
+ }
415
+
416
+ /** True when the platform could never price this model name. */
417
+ function unpriceable(model) {
418
+ const m = String(model || '').trim().toLowerCase();
419
+ return !m || m === 'auto';
420
+ }
421
+
422
+ /**
423
+ * The sample sent to the platform: the most recent 20 calls (oldest first) and one row per (local date, model).
424
+ * Calls without a model name are left out (they cannot be attributed).
425
+ */
426
+ export function buildSample({ reader, calls, tz, nowMs }) {
427
+ const inWin = windowCalls(calls, tz, nowMs).filter((c) => String(c.model || '').trim() !== '');
428
+ inWin.sort((a, b) => a.atMs - b.atMs);
429
+ const daily = new Map();
430
+ for (const c of inWin) {
431
+ const k = `${c.date}\u0000${c.model}`;
432
+ 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 };
433
+ d.input_tokens += c.input_tokens;
434
+ d.output_tokens += c.output_tokens;
435
+ d.cache_write_tokens = addN(d.cache_write_tokens, c.cache_write_tokens);
436
+ d.cache_read_tokens = addN(d.cache_read_tokens, c.cache_read_tokens);
437
+ d.calls += 1;
438
+ daily.set(k, d);
439
+ }
440
+ return {
441
+ kind: KIND,
442
+ tz,
443
+ source: 'local-log',
444
+ reader,
445
+ calls: inWin.slice(-RECENT_CALLS).map((c) => ({
446
+ at: isoLocal(c.atMs, tz), model: c.model, input_tokens: c.input_tokens, output_tokens: c.output_tokens,
447
+ cache_write_tokens: c.cache_write_tokens, cache_read_tokens: c.cache_read_tokens,
448
+ })),
449
+ 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))),
450
+ };
451
+ }
452
+
453
+ /** Days, calls and models (with their share of input + output tokens) of a sample. */
454
+ export function summarize(sample) {
455
+ const days = new Set(sample.daily.map((d) => d.date)).size;
456
+ const calls = sample.daily.reduce((n, d) => n + d.calls, 0);
457
+ const per = new Map();
458
+ for (const d of sample.daily) per.set(d.model, (per.get(d.model) || 0) + d.input_tokens + d.output_tokens);
459
+ const total = [...per.values()].reduce((a, b) => a + b, 0);
460
+ const models = [...per.entries()].sort((a, b) => b[1] - a[1]).map(([model, n]) => ({ model, share: total ? Math.round((n * 100) / total) : 0 }));
461
+ return { days, calls, models };
462
+ }
463
+
464
+ // ---------------------------------------------------------------- the command
465
+
466
+ function shortRoot(src, home) {
467
+ const r = src.root || (src.roots && src.roots.find(isDir)) || (src.files && src.files.find(isFile)) || '';
468
+ return home && r.startsWith(home) ? `~${r.slice(home.length)}` : r;
469
+ }
470
+
471
+ function errorCodeOf(e) {
472
+ const b = e && e.body && typeof e.body === 'object' ? e.body : null;
473
+ if (!b) return null;
474
+ const d = b.detail && typeof b.detail === 'object' ? b.detail : b;
475
+ return typeof d.error === 'string' ? d : null;
476
+ }
477
+
478
+ /** Read the logs and decide what to send: { sample } | { several } | { unreadable: reason key }. */
479
+ async function gatherSample(c, tz) {
480
+ const nowMs = c.nowMs();
481
+ const sinceMs = readSinceMs(nowMs);
482
+ const sources = c.flags.from != null ? [c.fromSource] : defaultSources(c.home, c.env);
483
+ const got = [];
484
+ let found = false;
485
+ let dbError = false;
486
+ for (const src of sources) {
487
+ const r = await readSource(src, { sinceMs, sqlite: c.sqlite });
488
+ found = found || r.found;
489
+ dbError = dbError || !!r.dbError;
490
+ const inWin = windowCalls(r.calls, tz, nowMs);
491
+ if (inWin.length) got.push({ src, calls: r.calls, inWin });
492
+ }
493
+ if (!got.length) return { unreadable: dbError ? 'db' : (found ? 'empty' : 'no_log') };
494
+ if (got.length > 1) {
495
+ return {
496
+ several: got.map((g) => {
497
+ const s = summarize(buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }));
498
+ return { reader: g.src.reader, root: shortRoot(g.src, c.home), days: s.days, calls: s.calls, models: s.models.map((m) => m.model) };
499
+ }),
500
+ };
501
+ }
502
+ const g = got[0];
503
+ if (g.inWin.every((x) => unpriceable(x.model))) return { unreadable: 'model' };
504
+ return { sample: buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }) };
505
+ }
506
+
507
+ function resultLines(d, env) {
508
+ const lines = [t('sample.state', { state: d.state != null ? d.state : '-', reason: d.reason != null ? d.reason : '-' }, env)];
509
+ if (Array.isArray(d.main_models) && d.main_models.length) lines.push(t('sample.main_models', { v: d.main_models.join(', ') }, env));
510
+ if (d.reason === 'model_unpriced') {
511
+ const m = d.model || (Array.isArray(d.unpriced_models) ? d.unpriced_models.join(', ') : '');
512
+ lines.push(t('sample.unpriced', { model: m }, env));
513
+ }
514
+ if (d.reason === 'no_log') lines.push(t('sample.no_log', {}, env));
515
+ return lines;
516
+ }
517
+
518
+ /**
519
+ * anytowork usage sample [--from <path>] [--dry-run] [--unreadable "<reason>"] [--json]
520
+ * Exit: 0 delivered (whatever the platform decided) or dry run / 1 refused / 2 bad arguments or several programs /
521
+ * 4 the CLI is too old.
522
+ */
523
+ export async function cmdSample(c) {
524
+ const env = c.env;
525
+ const tz = c.tz || localTz();
526
+ let body;
527
+ let summary = null;
528
+ if (c.flags.unreadable != null) {
529
+ const reason = String(c.flags.unreadable).replace(/\s+/g, ' ').trim();
530
+ if (!reason || reason.length > REASON_MAX) return c.fail(2, 'bad_reason', t('sample.bad_reason', { max: REASON_MAX }, env));
531
+ body = { kind: KIND, unreadable: true, reason };
532
+ } else {
533
+ if (c.flags.from != null) {
534
+ const p = String(c.flags.from).replace(/^~(?=$|\/)/, c.home);
535
+ if (!fs.existsSync(path.resolve(p))) return c.fail(2, 'from_not_found', t('sample.from_missing', { path: c.flags.from }, env));
536
+ c.fromSource = sourceFromPath(p);
537
+ }
538
+ const g = c.flags.from != null && !c.fromSource ? { unreadable: 'no_log' } : await gatherSample(c, tz);
539
+ if (g.several) {
540
+ if (c.flags.json) {
541
+ c.log(JSON.stringify({ ok: false, error: 'several_sources', message: t('sample.several', {}, env), sources: g.several }));
542
+ } else {
543
+ c.err(t('sample.several', {}, env));
544
+ for (const s of g.several) c.err(t('sample.several_row', { ...s, models: s.models.join(', ') }, env));
545
+ }
546
+ return 2;
547
+ }
548
+ body = g.sample || { kind: KIND, unreadable: true, reason: reasonText(g.unreadable, env) };
549
+ if (g.sample) summary = summarize(g.sample);
550
+ }
551
+
552
+ if (c.flags.dryRun) {
553
+ if (c.flags.json) { c.log(JSON.stringify({ ok: true, dry_run: true, sample: body })); return 0; }
554
+ if (body.unreadable) {
555
+ c.log(t('sample.dry_unreadable', { reason: body.reason }, env));
556
+ } else {
557
+ c.log(t('sample.dry_title', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
558
+ c.log(t('sample.dry_models', { v: summary.models.map((m) => `${m.model} ${m.share}%`).join(', ') }, env));
559
+ }
560
+ c.log(t('sample.own_only', {}, env));
561
+ return 0;
562
+ }
563
+
564
+ let d;
565
+ try {
566
+ d = await authedPostWithRefresh(c.baseUrl, JOB_CHECK_PATH, c.credOpts, body, null, { fetchImpl: c.fetchImpl });
567
+ } catch (e) {
568
+ const info = errorCodeOf(e) || {};
569
+ if (e && (e.upgradeRequired || Number(e.status) === 426)) {
570
+ const hint = t('usage.upgrade', { min: info.min_version || '', cmd: UPGRADE_COMMAND }, env);
571
+ return c.fail(4, info.error || 'cli_upgrade_required', e.upgradeRequired ? e.message : hint);
572
+ }
573
+ return c.fail(1, info.error || 'refused', t('sample.refused', { msg: e && e.message ? e.message : String(e) }, env));
574
+ }
575
+ d = d && typeof d === 'object' ? d : {};
576
+ if (c.flags.json) {
577
+ c.log(JSON.stringify({ ok: true, delivered: true, reader: body.reader || null, result: d }));
578
+ return 0;
579
+ }
580
+ c.log(body.unreadable ? t('sample.delivered_unreadable', { reason: body.reason }, env)
581
+ : t('sample.delivered', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
582
+ for (const l of resultLines(d, env)) c.log(l);
583
+ return 0;
584
+ }
package/src/mt/text.js CHANGED
@@ -122,6 +122,38 @@ const TEXT = {
122
122
  en: 'Tip: work inside the work folder and send call-by-call records with anytowork usage collect; employers trust them more than summaries.',
123
123
  },
124
124
 
125
+ // ---- usage sample (v0.37.4 job-seeking check, CLI 0.12.35)
126
+ 'sample.dry_title': { zh: '试读(不上传):{reader},{days} 天,{calls} 次调用', en: 'Trial read (nothing sent): {reader}, {days} days, {calls} calls' },
127
+ 'sample.dry_models': { zh: ' 模型(按输入 + 输出 token 占比):{v}', en: ' Models (share of input + output tokens): {v}' },
128
+ 'sample.dry_unreadable': {
129
+ zh: '试读(不上传):读不到可用的用量({reason})。正式运行会把这句原因交给平台。',
130
+ en: 'Trial read (nothing sent): no usable usage ({reason}). A real run sends this reason to the platform.',
131
+ },
132
+ 'sample.own_only': {
133
+ zh: '只算你自己这个程序的用量:如果读到的不是你自己这个程序的日志,用 --from <你自己这个程序的日志位置> 指定。',
134
+ 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>.',
135
+ },
136
+ 'sample.several': {
137
+ zh: '这台电脑上不止一个程序有最近 30 天的记录,这次没有上传。只交你自己这个程序的:用 anytowork usage sample --from <你自己这个程序的日志位置> 重跑。',
138
+ en: 'More than one program on this computer has records in the last 30 days; nothing was sent. Send only your own: rerun with anytowork usage sample --from <the log path of your own program>.',
139
+ },
140
+ 'sample.several_row': { zh: ' {reader} {root}:{days} 天,{calls} 次调用,模型 {models}', en: ' {reader} {root}: {days} days, {calls} calls, models {models}' },
141
+ 'sample.delivered': {
142
+ zh: '已送达平台({reader},{days} 天,{calls} 次调用)。通不通过由平台判定,平台的结果:',
143
+ en: 'Delivered to the platform ({reader}, {days} days, {calls} calls). The platform decides; its result:',
144
+ },
145
+ 'sample.delivered_unreadable': {
146
+ zh: '已送达平台:读不到可用的用量({reason})。通不通过由平台判定,平台的结果:',
147
+ en: 'Delivered to the platform: no usable usage ({reason}). The platform decides; its result:',
148
+ },
149
+ 'sample.state': { zh: ' state: {state},reason: {reason}', en: ' state: {state}, reason: {reason}' },
150
+ 'sample.main_models': { zh: ' 平台认定的主力模型:{v}', en: ' Main models seen by the platform: {v}' },
151
+ 'sample.unpriced': { zh: ' 平台没法给这个模型计价:{model}', en: ' The platform cannot price this model: {model}' },
152
+ 'sample.no_log': { zh: ' 平台按「读不到用量」处理。', en: ' The platform treats it as no usable usage.' },
153
+ 'sample.refused': { zh: '平台没有收下({msg})。', en: 'The platform did not take it ({msg}).' },
154
+ 'sample.bad_reason': { zh: '--unreadable 后面写一句原因,不超过 {max} 个字。', en: '--unreadable needs a reason of at most {max} characters.' },
155
+ 'sample.from_missing': { zh: '--from 指的位置不存在:{path}', en: 'The --from path does not exist: {path}' },
156
+
125
157
  // ---- labels coming from the platform as i18n keys
126
158
  'mt.check.summary': { zh: '这段记录有 {n} 处和常见情况不一样', en: '{n} things in these records differ from the usual' },
127
159
  'mt.check.rule.MT01': { zh: '{n} 条记录与其他单重复,未计入', en: '{n} records repeat another job and were not counted' },
@@ -186,6 +218,19 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
186
218
  本机先查一遍(重复的调用编号、时间与数字),再对照平台上的结果
187
219
  / check locally (repeated call ids, times, numbers), then compare with the platform
188
220
 
221
+ 求职用量样本 / job-seeking usage sample
222
+ usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原因>"] [--json]
223
+ 读你自己这个程序在本机的日志,按本地日期汇总最近 30 天每天每个模型的用量,交给平台做求职检查;
224
+ 通不通过由平台判定。只交你自己这个程序的:本机有几个程序的日志时不上传,
225
+ 请用 --from 指定你自己这个程序的日志位置。只传时间、模型名和 token 数,不传内容。
226
+ --dry-run 试读:只看读到哪种日志、几天、哪些模型、几次调用,不上传
227
+ --unreadable "<一句原因>" 本机没有日志(例如在云端运行)时,直接把原因交给平台(不超过 50 个字)
228
+ / read your own program's logs on this computer, sum the last 30 local days per day and
229
+ model, and send it for the job-seeking check (the platform decides). Only your own program:
230
+ with several programs' logs nothing is sent, point to yours with --from. Times, model
231
+ names and token counts only. --dry-run reads and summarises without sending;
232
+ --unreadable "<reason>" sends your own reason when there is no local log (50 characters max)
233
+
189
234
  自动 / automatic
190
235
  anytowork listen 运行时,空闲时每 10 分钟自动 usage collect 一次(不调用模型、不花额度);
191
236
  交付(task deliver / deliver upload)前也会自动上传本单记录,上传失败不影响交付。