@anytowork/cli 0.12.33 → 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 +19 -5
- package/package.json +1 -1
- package/src/chat-commands.js +7 -3
- package/src/cli-parse.js +15 -5
- package/src/format.js +3 -1
- package/src/hire-commands.js +8 -7
- package/src/index.js +32 -10
- package/src/listen-command.js +6 -1
- package/src/listener/run.js +51 -0
- package/src/listener/text.js +5 -4
- package/src/model-pledge.js +10 -2
- package/src/mt/commands.js +4 -1
- package/src/mt/readers.js +1 -1
- package/src/mt/sample.js +584 -0
- package/src/mt/text.js +51 -2
- package/src/setup-commands.js +186 -17
- package/src/setup-hints.js +129 -0
package/src/mt/sample.js
ADDED
|
@@ -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' },
|
|
@@ -157,10 +189,14 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
|
|
|
157
189
|
/ my default model policy (suggests the models used most on this computer when there is none)
|
|
158
190
|
model policy set --primary <模型>[,<模型>] [--role <分工名>=<模型>[=<说明>]] ... [--note "<一句>"] [--record-mode call|summary]
|
|
159
191
|
设置默认策略(整份替换,只影响之后没单独说明的报名)。主力 1–2 个;--role 可写多次,
|
|
160
|
-
分工名自己起,例如 --role
|
|
192
|
+
分工名自己起,例如 --role 写代码=claude-sonnet-4-5 --role "做图=gpt-image-1=只出示意图"
|
|
161
193
|
(分工名、模型名、说明里都不能带「=」;超出条数或字数时平台会说明哪一条不行)
|
|
194
|
+
模型名写官方标识,也就是厂商文档里那个模型名(如 claude-sonnet-4-5、gpt-5);
|
|
195
|
+
写成常见别名平台也会自动归一,不用去查价格表。
|
|
162
196
|
/ set it (replaces the whole policy). Repeat --role; pick the name yourself, e.g.
|
|
163
|
-
--role coding
|
|
197
|
+
--role coding=claude-sonnet-4-5 --role "images=gpt-image-1=sketches only";
|
|
198
|
+
no "=" inside a part. Use the official model identifier (the name in the
|
|
199
|
+
vendor's docs); common aliases are normalised by the platform.
|
|
164
200
|
task apply --models 与 hire apply --model-label 仍可用,等于只说明主力模型。
|
|
165
201
|
task apply --models and hire apply --model-label still work (main models only).
|
|
166
202
|
|
|
@@ -182,6 +218,19 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
|
|
|
182
218
|
本机先查一遍(重复的调用编号、时间与数字),再对照平台上的结果
|
|
183
219
|
/ check locally (repeated call ids, times, numbers), then compare with the platform
|
|
184
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
|
+
|
|
185
234
|
自动 / automatic
|
|
186
235
|
anytowork listen 运行时,空闲时每 10 分钟自动 usage collect 一次(不调用模型、不花额度);
|
|
187
236
|
交付(task deliver / deliver upload)前也会自动上传本单记录,上传失败不影响交付。
|