@anytowork/cli 0.12.48 → 0.12.49

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
@@ -428,7 +428,7 @@ anytowork usage check [--scope ...] # 本机先查一遍,再对照
428
428
  anytowork usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原因>"] [--json]
429
429
  ```
430
430
 
431
- - **求职用量样本**:按本地日期汇总最近 30 天每天每个模型的 token 数,外加最近 20 次调用,只传时间、模型名(照日志原样)和四类 token 数。只交你自己这个程序的:本机有几个程序的日志时不上传(退出码 2),用 `--from` 指定你自己这个程序的日志位置;先 `--dry-run` 试读不上传;本机没有日志(例如在云端运行)时用 `--unreadable "<一句原因>"`(不超过 50 个字)。退出码 0 已送达(不论平台结果)、1 平台没收下、2 参数问题、4 命令行版本过旧。
431
+ - **求职用量样本**:按本地日期汇总最近 30 天每天每个模型的 token 数,外加最近 20 次调用,只传时间、模型名(照日志原样)和四类 token 数。只交你自己这个程序的:本机有几个程序的日志时不上传(退出码 2),用 `--from` 指定你自己这个程序的日志位置;先 `--dry-run` 试读不上传;本机没有日志(例如在云端运行)时用 `--unreadable "<一句原因>"`(不超过 50 个字)。退出码 0 已送达(不论平台结果)、1 平台没收下、2 参数问题、4 命令行版本过旧。DeepSeek Harness(dsh)的日志也能读(需 Node 22.15 或更新,太旧会如实报原因);标题生成、联网搜索这类辅助小请求在日志里没有用量,不在统计内。
432
432
 
433
433
  - **自动**:`anytowork listen` 运行时,空闲时每 10 分钟自动上传一次(不调用模型、不花额度;环境变量 `ANYTOWORK_COLLECT_INTERVAL_MIN` 可改,0 = 关);`task deliver` / `deliver upload` 交付前也会自动上传本单记录,上传失败不影响交付。被选中 / 签署时平台若已发了目录编号,`listen` 会直接把目录建好。
434
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` 等)的文件整份不会上传。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.48",
3
+ "version": "0.12.49",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/mt/dsh.js ADDED
@@ -0,0 +1,174 @@
1
+ // v0.38.20: reader core for the DeepSeek Harness (program name dsh) session logs.
2
+ //
3
+ // Layout (measured): ~/.dsh/sessions/<folder code>/session-<uuid>/session.v4.jsonl.zstd. One file per session, appended
4
+ // to for as long as the session lives. The file is MANY independent zstd frames laid end to end (one JSON line per
5
+ // frame). Node's zlib only decodes the first frame of such a file, so the frames are cut here by their magic number
6
+ // and decoded one by one. A frame that does not decode (a false magic inside compressed data, or the last frame still
7
+ // being written) is joined with the next piece; a tail that never decodes is left for the next read.
8
+ //
9
+ // Only the metadata of `assistant/message` events is copied out: ids, model, provider, time, working folder and the
10
+ // four token counts. Prompts, answers and tool data are parsed (a whole line must be) but never kept.
11
+ //
12
+ // Not counted: small helper requests (session title, web search) - the log has no usage for them.
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import zlib from 'node:zlib';
17
+
18
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
19
+ const MAX_FRAME_BYTES = 32 * 1024 * 1024; // one decoded frame is never larger than this
20
+ const MAX_JOIN = 8; // pieces joined while looking for a decodable frame
21
+ const MAX_DEPTH = 4;
22
+ const CACHE_MAX = 300;
23
+
24
+ /** Node 22.15+ / 23.8+ have the built-in zstd; older Node cannot read this log. Checked at call time. */
25
+ export function zstdSupported() {
26
+ return typeof zlib.zstdDecompressSync === 'function';
27
+ }
28
+
29
+ export function dshRoots(home) {
30
+ return [path.join(home, '.dsh', 'sessions')];
31
+ }
32
+
33
+ function isLogName(n) {
34
+ return /\.jsonl\.zstd$/.test(n);
35
+ }
36
+
37
+ /** All session log files under `root` (or `root` itself when it is one) changed at or after sinceMs (by mtime). */
38
+ export function listDshFiles(root, sinceMs = 0) {
39
+ const out = [];
40
+ let st;
41
+ try { st = fs.statSync(root); } catch { return out; }
42
+ if (st.isFile()) { if (isLogName(path.basename(root)) && st.mtimeMs >= sinceMs) out.push(root); return out; }
43
+ const walk = (dir, depth) => {
44
+ let entries;
45
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
46
+ for (const e of entries) {
47
+ const p = path.join(dir, e.name);
48
+ if (e.isDirectory()) { if (depth < MAX_DEPTH) walk(p, depth + 1); continue; }
49
+ if (!e.isFile() || !isLogName(e.name)) continue;
50
+ try { if (fs.statSync(p).mtimeMs >= sinceMs) out.push(p); } catch { /* vanished */ }
51
+ }
52
+ };
53
+ walk(root, 0);
54
+ return out;
55
+ }
56
+
57
+ /** True when `dir` (or its sessions folder) holds at least one session log: used to tell this log from other programs. */
58
+ export function looksLikeDsh(dir) {
59
+ return listDshFiles(dir, 0).length > 0 || listDshFiles(path.join(dir, 'sessions'), 0).length > 0;
60
+ }
61
+
62
+ function isoSec(ms) {
63
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
64
+ }
65
+
66
+ function count(v) {
67
+ const n = Number(v);
68
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
69
+ }
70
+
71
+ /** The JSON objects of one decoded frame, or null when it is not a whole one (Node returns the part of a cut-off frame without an error). */
72
+ function parseFrame(text) {
73
+ const out = [];
74
+ for (const line of text.split('\n')) {
75
+ if (!line) continue;
76
+ if (line[0] !== '{') return null;
77
+ try { out.push(JSON.parse(line)); } catch { return null; }
78
+ }
79
+ return out.length ? out : null;
80
+ }
81
+
82
+ /**
83
+ * Decode the frames of `buf` from byte `from`. Returns { events, end }: the parsed events and the offset just after the
84
+ * last frame that decoded (a tail that does not decode yet is not consumed).
85
+ */
86
+ export function decodeFrames(buf, from = 0) {
87
+ const starts = [];
88
+ for (let k = buf.indexOf(MAGIC, from); k !== -1; k = buf.indexOf(MAGIC, k + 1)) starts.push(k);
89
+ const events = [];
90
+ let end = from;
91
+ let i = 0;
92
+ while (i < starts.length) {
93
+ let done = false;
94
+ for (let j = i + 1; j <= Math.min(starts.length, i + MAX_JOIN); j += 1) {
95
+ const stop = j < starts.length ? starts[j] : buf.length;
96
+ let got = null;
97
+ try { got = parseFrame(zlib.zstdDecompressSync(buf.subarray(starts[i], stop), { maxOutputLength: MAX_FRAME_BYTES }).toString('utf8')); } catch { /* join the next piece */ }
98
+ if (!got) continue;
99
+ events.push(...got);
100
+ end = stop;
101
+ i = j;
102
+ done = true;
103
+ break;
104
+ }
105
+ if (!done) i += 1; // a damaged piece: skip it, the frames after it are still read
106
+ }
107
+ return { events, end };
108
+ }
109
+
110
+ // file -> { size, offset, sid, cwd, calls: Map } so a file that only grew is decoded from where it was left
111
+ const cache = new Map();
112
+
113
+ function applyEvent(st, o) {
114
+ if (!o || typeof o !== 'object') return;
115
+ const d = o.data && typeof o.data === 'object' ? o.data : {};
116
+ if (o.type === 'session') {
117
+ if (d.id) st.sid = String(d.id);
118
+ if (typeof d.cwd === 'string') st.cwd = d.cwd;
119
+ return;
120
+ }
121
+ if (o.type !== 'assistant/message') return;
122
+ const u = d.usage;
123
+ const m = d.message && typeof d.message === 'object' ? d.message : null;
124
+ const src = m && m.source && typeof m.source === 'object' ? m.source : null;
125
+ if (!u || typeof u !== 'object' || !src || !src.model) return;
126
+ const atMs = Number(o.time);
127
+ if (!Number.isFinite(atMs) || atMs <= 0) return;
128
+ const id = m.id || `${st.sid || st.dir}:${d.turn != null ? d.turn : o.seq}:${d.step != null ? d.step : ''}`;
129
+ st.calls.set(String(id), {
130
+ call_id: String(id),
131
+ session_id: st.sid || st.dir,
132
+ provider: typeof src.provider === 'string' ? src.provider.toLowerCase() : '',
133
+ model: String(src.model),
134
+ atMs,
135
+ started_at: isoSec(atMs),
136
+ input_tokens: count(u.inputTokens),
137
+ output_tokens: count(u.outputTokens),
138
+ cache_read_tokens: count(u.cacheReadTokens),
139
+ cache_write_tokens: count(u.cacheWriteTokens),
140
+ cwd: null, // filled in from the session line when the file is summed up
141
+ });
142
+ }
143
+
144
+ /** The calls of one session log file (all of them; the caller filters by time). Never throws. */
145
+ export function readDshFile(file) {
146
+ let buf;
147
+ try { buf = fs.readFileSync(file); } catch { return { calls: [], cwd: null }; }
148
+ let st = cache.get(file);
149
+ const head = buf.subarray(0, 48).toString('hex'); // a file replaced by another one is not mistaken for the same one
150
+ if (!st || buf.length < st.size || st.head !== head) st = { head, size: 0, offset: 0, sid: null, cwd: null, calls: new Map(), dir: path.basename(path.dirname(file)) };
151
+ const { events, end } = decodeFrames(buf, st.offset);
152
+ for (const o of events) applyEvent(st, o);
153
+ st.offset = end;
154
+ st.size = buf.length;
155
+ if (cache.size >= CACHE_MAX) cache.clear();
156
+ cache.set(file, st);
157
+ return { calls: [...st.calls.values()].map((c) => ({ ...c, cwd: st.cwd })), cwd: st.cwd };
158
+ }
159
+
160
+ /**
161
+ * Every call of the session logs under `roots` seen at or after sinceMs.
162
+ * { found, files, oldNode, calls }: oldNode = there are logs but this Node cannot decode them (nothing is read).
163
+ */
164
+ export function readDshCalls(roots, sinceMs) {
165
+ const files = roots.flatMap((r) => listDshFiles(r, sinceMs));
166
+ const found = roots.some((r) => { try { return fs.existsSync(r); } catch { return false; } });
167
+ if (!files.length) return { found, files: 0, oldNode: false, calls: [] };
168
+ if (!zstdSupported()) return { found, files: files.length, oldNode: true, calls: [] };
169
+ const byId = new Map();
170
+ for (const f of files) {
171
+ for (const c of readDshFile(f).calls) if (c.atMs >= sinceMs) byId.set(`${c.session_id}|${c.call_id}`, c);
172
+ }
173
+ return { found, files: files.length, oldNode: false, calls: [...byId.values()] };
174
+ }
package/src/mt/inrun.js CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  import os from 'node:os';
16
16
  import path from 'node:path';
17
- import { readMsgLog, readRollout, readSessionModelUsage, readRunLog, readTranscriptUsage, guessProvider } from './readers.js';
17
+ import { readMsgLog, readRollout, readDshLog, readSessionModelUsage, readRunLog, readTranscriptUsage, guessProvider } from './readers.js';
18
18
  import { readState, writeState, sendRows, sha256, isZero, localKey } from './collect.js';
19
19
  import { readRegistry, workdirForPath } from './workdirs.js';
20
20
 
@@ -76,6 +76,7 @@ export function programOfCommand(command) {
76
76
  if (b === 'openclaw') return 'openclaw';
77
77
  if (b === 'claude') return 'claude_code';
78
78
  if (b === 'codex') return 'codex';
79
+ if (b === 'dsh') return 'dsh';
79
80
  }
80
81
  return null;
81
82
  }
@@ -240,6 +241,7 @@ export class RunUsageTracker {
240
241
  const fromJsonl = [
241
242
  { program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since, log: this.log }) },
242
243
  { program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since, log: this.log }) },
244
+ { program: 'dsh', reader: 'cli:dsh_log', read: () => readDshLog({ home, env, sinceMs: since, log: this.log }) },
243
245
  ];
244
246
  for (const src of fromJsonl) {
245
247
  if (r.prog && r.prog !== src.program) continue;
package/src/mt/readers.js CHANGED
@@ -22,6 +22,7 @@ import os from 'node:os';
22
22
  import path from 'node:path';
23
23
  import { createHash } from 'node:crypto';
24
24
  import zlib from 'node:zlib';
25
+ import { dshRoots, readDshCalls } from './dsh.js';
25
26
  import { mayRead, formatAlerts, msgLogProblem, rolloutProblem, sessionDbProblem, openClawProblem } from './format-check.js';
26
27
 
27
28
  const MAX_DEPTH = 6;
@@ -224,6 +225,33 @@ export function readRollout({ home, env, sinceMs, log }) {
224
225
  return { calls: [...calls.values()], summaries: [], files };
225
226
  }
226
227
 
228
+ // ---------------------------------------------------------------- dsh (DeepSeek Harness, v0.38.20)
229
+
230
+ /**
231
+ * One call per `assistant/message` event of the session logs (zstd frames, see dsh.js). Small helper requests (title,
232
+ * web search) have no usage in the log and are not counted. A Node without built-in zstd reads nothing and says so with
233
+ * `unreadable` (the number of log files it could not open).
234
+ */
235
+ export function readDshLog({ home, env, sinceMs }) {
236
+ const r = readDshCalls(dshRoots(home, env), sinceMs);
237
+ if (r.oldNode) return { calls: [], summaries: [], files: 0, unreadable: r.files };
238
+ const calls = r.calls.filter((c) => c.model).map((c) => ({
239
+ call_id: c.call_id,
240
+ conversation_id: c.session_id,
241
+ provider: c.provider || guessProvider(c.model),
242
+ model: c.model,
243
+ started_at: c.started_at,
244
+ ended_at: null,
245
+ input_tokens: c.input_tokens,
246
+ output_tokens: c.output_tokens,
247
+ cache_write_tokens: c.cache_write_tokens,
248
+ cache_read_tokens: c.cache_read_tokens,
249
+ cwd: c.cwd,
250
+ seenMs: c.atMs,
251
+ }));
252
+ return { calls, summaries: [], files: r.files };
253
+ }
254
+
227
255
  // ---------------------------------------------------------------- sessionDb
228
256
 
229
257
  export async function loadSqlite() {
@@ -523,7 +551,7 @@ export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
523
551
  * @returns {Promise<{calls, summaries, files}>}
524
552
  */
525
553
  export async function readLocalLogs({ home = os.homedir(), env = process.env, sinceMs = 0, nowMs = Date.now(), settleMs = 60_000, sqlite } = {}) {
526
- const parts = [readMsgLog({ home, env, sinceMs }), readRollout({ home, env, sinceMs }), await readSessionDb({ home, env, sinceMs, sqlite })];
554
+ const parts = [readMsgLog({ home, env, sinceMs }), readRollout({ home, env, sinceMs }), readDshLog({ home, env, sinceMs }), await readSessionDb({ home, env, sinceMs, sqlite })];
527
555
  const cut = nowMs - settleMs;
528
556
  return {
529
557
  calls: parts.flatMap((p) => p.calls).filter((c) => c.seenMs <= cut),
package/src/mt/sample.js CHANGED
@@ -26,6 +26,7 @@ import { UPGRADE_COMMAND } from '../client-version.js';
26
26
  import { pickLang } from '../model-pledge.js';
27
27
  import { t } from './text.js';
28
28
  import { listJsonl, loadSqlite } from './readers.js';
29
+ import { dshRoots, readDshCalls, looksLikeDsh } from './dsh.js';
29
30
 
30
31
  export const KIND = 'job_usage_sample';
31
32
  export const JOB_CHECK_PATH = '/api/v1/agent/hire/job-check';
@@ -40,6 +41,7 @@ export const REASONS = {
40
41
  empty: { zh: '找到了日志,但最近 30 天没有记录', en: 'Logs found, but no records in the last 30 days' },
41
42
  model: { zh: '日志里的模型名是 auto 或空,无法计价', en: 'Model name is auto or empty; cannot be priced' },
42
43
  db: { zh: '日志数据库打不开', en: 'The log database cannot be opened' },
44
+ node_old: { zh: 'Node 版本太旧,读不了 DeepSeek Harness 日志,需升级', en: 'Node too old to read DeepSeek logs; please upgrade' },
43
45
  };
44
46
 
45
47
  export function reasonText(key, env = process.env) {
@@ -338,6 +340,22 @@ export async function readRunDbSample({ files, sinceMs, sqlite }) {
338
340
  return { found: true, calls: [...runs.values()], dbError };
339
341
  }
340
342
 
343
+ // ---------------------------------------------------------------- dsh (DeepSeek Harness, v0.38.20)
344
+
345
+ /** Session logs of the DeepSeek Harness: zstd frames, one call per assistant message (helper requests have no usage). */
346
+ export function readDshSample({ roots, sinceMs }) {
347
+ const r = readDshCalls(roots, sinceMs);
348
+ if (r.oldNode) return { found: true, calls: [], oldNode: true };
349
+ return {
350
+ found: r.found,
351
+ calls: r.calls.filter((c) => c.model).map((c) => ({
352
+ atMs: c.atMs, model: c.model,
353
+ input_tokens: c.input_tokens, output_tokens: c.output_tokens,
354
+ cache_write_tokens: c.cache_write_tokens, cache_read_tokens: c.cache_read_tokens,
355
+ })),
356
+ };
357
+ }
358
+
341
359
  // ---------------------------------------------------------------- where the logs are
342
360
 
343
361
  /** The usual log location of each reader on this computer. */
@@ -355,6 +373,7 @@ export function defaultSources(home, env = {}) {
355
373
  return [
356
374
  { reader: 'msg_log', roots: [...new Set(msg)] },
357
375
  { reader: 'rollout', roots: [...new Set(roll)] },
376
+ { reader: 'dsh_log', roots: dshRoots(home) },
358
377
  { reader: 'session_db', files: [...new Set(sdb)] },
359
378
  { reader: 'run_db', files: agentsDbFiles(agents), root: agents },
360
379
  ];
@@ -368,10 +387,12 @@ export function sourceFromPath(p) {
368
387
  if (st.isFile()) {
369
388
  if (abs.endsWith('.sqlite')) return { reader: 'run_db', files: [abs], root: abs };
370
389
  if (abs.endsWith('.db')) return { reader: 'session_db', files: [abs], root: abs };
390
+ if (abs.endsWith('.jsonl.zstd')) return { reader: 'dsh_log', roots: [abs], root: abs };
371
391
  return null;
372
392
  }
373
393
  if (!st.isDirectory()) return null;
374
394
  const base = path.basename(abs);
395
+ if (looksLikeDsh(abs) || base === '.dsh') return { reader: 'dsh_log', roots: [isDir(path.join(abs, 'sessions')) ? path.join(abs, 'sessions') : abs], root: abs };
375
396
  if (isFile(path.join(abs, 'state.db'))) return { reader: 'session_db', files: [path.join(abs, 'state.db')], root: abs };
376
397
  if (base === 'agents') return { reader: 'run_db', files: agentsDbFiles(abs), root: abs };
377
398
  if (isDir(path.join(abs, 'agents')) && agentsDbFiles(path.join(abs, 'agents')).length) {
@@ -393,6 +414,7 @@ export async function readSource(src, { sinceMs, sqlite }) {
393
414
  switch (src.reader) {
394
415
  case 'msg_log': return readMsgLogSample({ roots: src.roots, sinceMs });
395
416
  case 'rollout': return readRolloutSample({ roots: src.roots, sinceMs });
417
+ case 'dsh_log': return readDshSample({ roots: src.roots, sinceMs });
396
418
  case 'session_db': return readSessionDbSample({ files: src.files, sinceMs, sqlite });
397
419
  case 'run_db': return readRunDbSample({ files: src.files, sinceMs, sqlite });
398
420
  default: return { found: false, calls: [] };
@@ -483,14 +505,16 @@ async function gatherSample(c, tz) {
483
505
  const got = [];
484
506
  let found = false;
485
507
  let dbError = false;
508
+ let oldNode = false;
486
509
  for (const src of sources) {
487
510
  const r = await readSource(src, { sinceMs, sqlite: c.sqlite });
488
511
  found = found || r.found;
489
512
  dbError = dbError || !!r.dbError;
513
+ oldNode = oldNode || !!r.oldNode;
490
514
  const inWin = windowCalls(r.calls, tz, nowMs);
491
515
  if (inWin.length) got.push({ src, calls: r.calls, inWin });
492
516
  }
493
- if (!got.length) return { unreadable: dbError ? 'db' : (found ? 'empty' : 'no_log') };
517
+ if (!got.length) return { unreadable: oldNode ? 'node_old' : dbError ? 'db' : (found ? 'empty' : 'no_log') };
494
518
  if (got.length > 1) {
495
519
  return {
496
520
  several: got.map((g) => {