@anytowork/cli 0.12.43 → 0.12.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.43",
3
+ "version": "0.12.44",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -60,7 +60,7 @@ it lives in the cloud and a change takes effect at once.
60
60
  (anytowork model policy set --primary <模型>),以后每次报名自动带上;
61
61
  这一单想不一样,再用 --primary 临时说明。
62
62
  做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy
63
- --role 可写多次,分工名自己起,例如 --role 写代码=<模型A>
63
+ --role 可写多次,分工名自己起,例如 --role 复杂判断=<模型A>
64
64
  --role "做图=<模型B>=只出示意图"(分工名、模型名、说明里都不能带「=」);
65
65
  用了 --role 或 --note 就要带 --primary;--model-label 是只报一个主力的旧写法;
66
66
  / A main model and model policy are required, and the main model must be in the
package/src/index.js CHANGED
@@ -309,7 +309,7 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
309
309
  再临时说明。不说明也能报名,雇主会看到"未说明模型"。
310
310
  做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy
311
311
  --primary 主力 1 到 2 个(逗号中英文都行,同一模型的不同写法算一个);
312
- --role 可写多次,分工名自己起,例如 --role 写代码=<模型A>
312
+ --role 可写多次,分工名自己起,例如 --role 复杂判断=<模型A>
313
313
  --role "做图=<模型B>=只出示意图"(分工名、模型名、说明里都不能带「=」);
314
314
  --note 一句补充。用了 --role 或 --note 就要带 --primary。
315
315
  只报主力也可以写 --models "<模型名,模型名>"(或 --model <模型名>)。
package/src/mt/collect.js CHANGED
@@ -47,6 +47,11 @@ export function writeState(credOpts, st, nowMs = Date.now()) {
47
47
  const keep = {};
48
48
  for (const [k, at] of Object.entries(st.sent || {})) if (nowMs - Number(at) < SENT_KEEP_MS) keep[k] = at;
49
49
  st.sent = keep;
50
+ if (st.perCallReported) {
51
+ const pc = {};
52
+ for (const [k, at] of Object.entries(st.perCallReported)) if (nowMs - Number(at) < SENT_KEEP_MS) pc[k] = at;
53
+ st.perCallReported = pc;
54
+ }
50
55
  st.version = 1;
51
56
  try {
52
57
  const file = stateFile(credOpts);
@@ -52,6 +52,7 @@ export function mapMtError(e, env = process.env) {
52
52
  case 'mt_policy_role_too_long': return { exit: 1, code, text: t('policy.err.role_too_long', { n: Number.isInteger(v.index) ? v.index + 1 : '?', max: v.max != null ? v.max : 20 }, env) };
53
53
  case 'mt_policy_role_note_too_long': return { exit: 1, code, text: t('policy.err.role_note_too_long', { n: Number.isInteger(v.index) ? v.index + 1 : '?', max: v.max != null ? v.max : 60 }, env) };
54
54
  case 'mt_policy_too_many_roles': return { exit: 1, code, text: t('policy.err.too_many_roles', { max: v.max != null ? v.max : 5 }, env) };
55
+ case 'mt_policy_wiring': return { exit: 1, code, text: t('policy.err.wiring', {}, env) };
55
56
  case 'mt_policy_note_too_long': return { exit: 1, code, text: t('policy.err.note_too_long', { max: v.max != null ? v.max : 200 }, env) };
56
57
  case 'mt_workdir_forbidden': return { exit: 1, code, text: t('workdir.err.forbidden', {}, env) };
57
58
  case 'mt_scope_closed': return { exit: 1, code, text: t('workdir.err.closed', {}, env) };
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, guessProvider } from './readers.js';
17
+ import { readMsgLog, readRollout, 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
 
@@ -63,6 +63,19 @@ function dirMatches(cwd, dirs, home, exactOnly = false) {
63
63
  return false;
64
64
  }
65
65
 
66
+ /** The program a start command names (first word of a path or `exec`), or null when it is a wrapper we cannot tell. */
67
+ export function programOfCommand(command) {
68
+ const words = String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
69
+ for (const w of words.slice(0, 6)) {
70
+ const b = path.basename(w).toLowerCase().replace(/\.(?:exe|cmd|sh|js|mjs)$/, '');
71
+ if (b === 'hermes') return 'hermes';
72
+ if (b === 'openclaw') return 'openclaw';
73
+ if (b === 'claude') return 'claude_code';
74
+ if (b === 'codex') return 'codex';
75
+ }
76
+ return null;
77
+ }
78
+
66
79
  function shareDir(a, b) { return a.dirs.some((d) => b.dirs.includes(d)); }
67
80
  function timeOverlap(a, b, now) {
68
81
  const aEnd = a.endMs == null ? now : a.endMs + FINISH_GRACE_MS;
@@ -127,6 +140,7 @@ export class RunUsageTracker {
127
140
  taskRef: buildTaskRef({ sid, wakeId, hireId, taskId }),
128
141
  dirs: [...new Set((dirs || []).map(norm).filter(Boolean))],
129
142
  tokens: String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter((t) => t.length >= 4 && !t.startsWith('-') && /[:_-]/.test(t)),
143
+ prog: programOfCommand(command), // v0.38.8: a run of one program never takes another program's sessions
130
144
  cum: new Map(), // `session|model` -> totals already sent
131
145
  sentAny: false,
132
146
  };
@@ -184,6 +198,7 @@ export class RunUsageTracker {
184
198
 
185
199
  // session database: totals per session x model
186
200
  try {
201
+ if (r.prog && r.prog !== 'hermes') throw new Error('the run is of another program');
187
202
  const hs = await readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite });
188
203
  const crowdDirs = [...new Set([r, ...this.peers(r, now)].flatMap((x) => x.dirs))];
189
204
  const crowdStart = Math.min(r.startMs, ...this.peers(r, now).map((x) => x.startMs)) - START_SLACK_MS;
@@ -223,6 +238,7 @@ export class RunUsageTracker {
223
238
  { program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since }) },
224
239
  ];
225
240
  for (const src of fromJsonl) {
241
+ if (r.prog && r.prog !== src.program) continue;
226
242
  try {
227
243
  for (const c of src.read().calls) {
228
244
  if (c.seenMs < since || c.seenMs > until || c.seenMs > now - settleMs) continue;
@@ -233,14 +249,26 @@ export class RunUsageTracker {
233
249
  }
234
250
 
235
251
  // run-log database: runs of the session key the start command names
236
- if (r.tokens.length) {
252
+ if (r.tokens.length && (!r.prog || r.prog === 'openclaw')) {
253
+ const mine = (c) => {
254
+ const key = c.session_key || '';
255
+ return r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
256
+ };
257
+ // v0.38.8: every assistant message of the session, as it happens (the run log only has the total at the very end)
258
+ const live = new Set();
259
+ try {
260
+ const tr = await readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite });
261
+ for (const c of tr.calls) {
262
+ if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
263
+ live.add(c.session_id);
264
+ rows.push(callRow(c, { program: 'openclaw', reader: 'cli:transcript_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
265
+ }
266
+ } catch { /* same */ }
237
267
  try {
238
268
  const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite });
239
269
  for (const c of oc.calls) {
240
- if (c.seenMs < since || c.seenMs > until) continue;
241
- const key = c.session_key || '';
242
- const hit = r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
243
- if (!hit) continue;
270
+ if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
271
+ if (live.has(c.session_id) || (state.perCallReported || {})[c.session_id]) continue; // the session already has its calls one by one (this round or an earlier one): the run total would count it twice
244
272
  rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
245
273
  }
246
274
  } catch { /* same */ }
@@ -262,6 +290,11 @@ export class RunUsageTracker {
262
290
  const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
263
291
  if (tot.featureOff) this.off = true;
264
292
  if (!tot.error && !tot.featureOff) {
293
+ if (fresh.some((x) => x.reader === 'cli:transcript_db')) {
294
+ // remembered across rounds (and restarts): a later round that cannot read the transcript must not add the run total
295
+ state.perCallReported = state.perCallReported || {};
296
+ for (const x of fresh) if (x.reader === 'cli:transcript_db') state.perCallReported[x.conversation_id] = now;
297
+ }
265
298
  for (const [sig, totals] of pendingCum) r.cum.set(sig, totals);
266
299
  r.sentAny = true;
267
300
  }
package/src/mt/readers.js CHANGED
@@ -21,6 +21,7 @@ import fs from 'node:fs';
21
21
  import os from 'node:os';
22
22
  import path from 'node:path';
23
23
  import { createHash } from 'node:crypto';
24
+ import zlib from 'node:zlib';
24
25
 
25
26
  const MAX_DEPTH = 6;
26
27
 
@@ -420,6 +421,92 @@ export async function readRunLog({ home, env, sinceMs, sqlite }) {
420
421
  return { calls: [...runs.values()], files: files.length };
421
422
  }
422
423
 
424
+ // ---------------------------------------------------------------- run transcript (v0.38.8)
425
+
426
+ const TRANSCRIPT_SQL = `SELECT e.session_id AS sid, e.seq AS seq, e.created_at AS c, e.event_json AS j, e.event_zstd AS z, w.session_key AS skey
427
+ FROM transcript_events e LEFT JOIN session_windows w ON w.session_id = e.session_id
428
+ WHERE e.created_at >= ? AND (e.event_json IS NULL
429
+ OR (json_extract(e.event_json, '$.type') = 'message' AND json_extract(e.event_json, '$.message.role') = 'assistant'))
430
+ ORDER BY e.created_at, e.seq`;
431
+
432
+ const TRANSCRIPT_MAX_BYTES = 4 * 1024 * 1024; // the database itself caps one event at 4 MB; anything that expands past it is not read
433
+ const TRANSCRIPT_CACHE_MAX = 5000;
434
+ const transcriptCache = new Map(); // `file|session:seq` -> the parsed call (or null): an event never changes once written
435
+
436
+ function transcriptEvent(r) {
437
+ try {
438
+ if (r.j != null) return JSON.parse(r.j);
439
+ // large events are stored zstd-compressed (event_json NULL); an older Node cannot open them: those are skipped
440
+ if (r.z == null || typeof zlib.zstdDecompressSync !== 'function') return null;
441
+ return JSON.parse(zlib.zstdDecompressSync(Buffer.from(r.z), { maxOutputLength: TRANSCRIPT_MAX_BYTES }).toString('utf8'));
442
+ } catch { return null; }
443
+ }
444
+
445
+ function parseTranscriptCall(r) {
446
+ const ev = transcriptEvent(r);
447
+ const m = ev && ev.type === 'message' ? ev.message : null;
448
+ if (!m || m.role !== 'assistant' || !m.usage || typeof m.usage !== 'object' || !m.model) return null;
449
+ const at = iso(m.timestamp) || iso(ev.timestamp) || iso(r.c);
450
+ if (!at) return null;
451
+ const u = m.usage;
452
+ const unreadable = [];
453
+ if (u.cacheRead == null) unreadable.push('cache_read_tokens');
454
+ if (u.cacheWrite == null) unreadable.push('cache_write_tokens');
455
+ return {
456
+ call_id: `${r.sid}:${r.seq}`,
457
+ run_id: null,
458
+ session_id: String(r.sid),
459
+ conversation_id: String(r.sid),
460
+ provider: String(m.provider || guessProvider(m.model)).toLowerCase(),
461
+ model: String(m.model),
462
+ started_at: at,
463
+ ended_at: null,
464
+ seenMs: Date.parse(at),
465
+ input_tokens: int(u.input),
466
+ output_tokens: int(u.output),
467
+ cache_write_tokens: int(u.cacheWrite),
468
+ cache_read_tokens: int(u.cacheRead),
469
+ reasoning_tokens: int(u.reasoningTokens),
470
+ unreadable_fields: unreadable,
471
+ total: int(u.totalTokens),
472
+ };
473
+ }
474
+
475
+ /**
476
+ * The run-log program writes every assistant message with its usage into `transcript_events` while a run is going on (the run log
477
+ * only gets one total when the run ends). One call per assistant message, call_id = session:seq. The session key comes
478
+ * from `session_windows` so the caller can pick the messages of one wake-up. A database without these tables, or one
479
+ * that cannot be opened, gives nothing. Reasoning tokens are reported next to the output count, like the run log.
480
+ */
481
+ export async function readTranscriptUsage({ home, env, sinceMs, sqlite }) {
482
+ const files = openClawDbFiles(home, env);
483
+ if (!files.length) return { calls: [], files: 0 };
484
+ const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
485
+ if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length };
486
+ const calls = [];
487
+ for (const f of files) {
488
+ let db;
489
+ try {
490
+ db = new DatabaseSync(f, { readOnly: true });
491
+ const have = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((x) => x.name));
492
+ if (!have.has('transcript_events') || !have.has('session_windows')) continue;
493
+ for (const r of db.prepare(TRANSCRIPT_SQL).all(sinceMs)) {
494
+ const ck = `${f}|${r.sid}:${r.seq}`;
495
+ let call = transcriptCache.get(ck);
496
+ if (call === undefined) {
497
+ call = parseTranscriptCall(r);
498
+ if (transcriptCache.size >= TRANSCRIPT_CACHE_MAX) transcriptCache.clear();
499
+ transcriptCache.set(ck, call);
500
+ }
501
+ if (call) calls.push({ ...call, session_key: typeof r.skey === 'string' ? r.skey : null });
502
+ }
503
+ } catch { /* a locked or different file: skip it */ } finally {
504
+ try { if (db) db.close(); } catch { /* ignore */ }
505
+ }
506
+ }
507
+ return { calls, files: files.length };
508
+ }
509
+
423
510
  /**
424
511
  * Read every known log on this computer. `settleMs`: calls seen less than this long ago are left for the next run
425
512
  * (a reply may still be streaming into the log).
package/src/mt/text.js CHANGED
@@ -10,8 +10,8 @@ import { pickLang } from '../model-pledge.js';
10
10
  const TEXT = {
11
11
  // ---- model policy
12
12
  'policy.none': {
13
- zh: '还没有设置默认模型策略。用 anytowork model policy set --primary <模型>[,<模型>] 设置(主力最多 2 个);报名时没单独说明,平台就用这一份。只用一个模型就报那一个;用了几个就如实写各自分工。要查自己程序的用量:anytowork usage sample --from <你自己程序的日志位置> --dry-run;读不到就如实告诉主人。',
14
- en: 'No default model policy yet. Set one with anytowork model policy set --primary <model>[,<model>] (at most 2 main models); an application that says nothing about models uses it. Use one model: report that one; use several: say what each does. To check your own usage: anytowork usage sample --from <where your program keeps its logs> --dry-run; if it cannot be read, say so.',
13
+ zh: '还没有设置默认模型策略。用 anytowork model policy set --primary <模型>[,<模型>] 设置(主力最多 2 个);报名时没单独说明,平台就用这一份。这份说明是给雇主看的,写他在乎的结果,不写程序怎么接线或配置;只用一个模型就报那一个,确有分工才写成「这个模型负责什么」。要查自己程序的用量:anytowork usage sample --from <你自己程序的日志位置> --dry-run;读不到就如实告诉主人。',
14
+ en: 'No default model policy yet. Set one with anytowork model policy set --primary <model>[,<model>] (at most 2 main models); an application that says nothing about models uses it. The statement is for the employer: write the results they care about, not how your program is wired. Use one model: report that one; write a role only if there really is a division of labour, as what the model is responsible for. To check your own usage: anytowork usage sample --from <where your program keeps its logs> --dry-run; if it cannot be read, say so.',
15
15
  },
16
16
  'policy.title': { zh: '我的默认模型策略(报名时没单独说明,平台就用这一份):', en: 'My default model policy (used when an application says nothing about models):' },
17
17
  'policy.primary': { zh: ' 主力模型:{v}', en: ' Main models: {v}' },
@@ -33,7 +33,7 @@ const TEXT = {
33
33
  'policy.need_primary': { zh: '缺少主力模型:加 --primary <模型>[,<模型>](1 到 2 个)。', en: 'Main models missing: add --primary <model>[,<model>] (1 or 2).' },
34
34
  'policy.too_many_primary': { zh: '主力模型最多 2 个。', en: 'At most 2 main models.' },
35
35
  'policy.bad_role': {
36
- zh: '--role 写法是 <分工名>=<模型>[=<说明>],分工名自己起,例如 写代码=<模型A> 或 做图=<模型B>=只出示意图。',
36
+ zh: '--role 写法是 <分工名>=<模型>[=<说明>],分工名自己起,例如 复杂判断=<模型A> 或 画图=<模型B>=只出示意图。',
37
37
  en: '--role is written <name>=<model>[=<note>]; pick the name yourself, e.g. coding=<modelA> or images=<modelB>=sketches only.',
38
38
  },
39
39
  'policy.bad_role_eq': {
@@ -48,6 +48,7 @@ const TEXT = {
48
48
  'policy.err.invalid_role': { zh: '第 {n} 条分工不能用:分工名不能为空、不能重复,模型名也请核对。', en: 'Role #{n} cannot be used: the name must not be empty or repeated, and check the model name too.' },
49
49
  'policy.err.role_too_long': { zh: '第 {n} 条分工的名称太长,最多 {max} 个字。改短后整份重报。', en: 'The name of role #{n} is too long (at most {max} characters). Shorten it and send the whole policy again.' },
50
50
  'policy.err.role_note_too_long': { zh: '第 {n} 条分工的说明太长,最多 {max} 个字。改短后整份重报。', en: 'The note of role #{n} is too long (at most {max} characters). Shorten it and send the whole policy again.' },
51
+ 'policy.err.wiring': { zh: '这段说明带了命令或配置的写法,请改成雇主看得懂的一句话,再整份重报。', en: 'This statement carries a command or config wording; please rewrite it as one sentence the employer can understand, then send the whole policy again.' },
51
52
  'policy.err.too_many_roles': { zh: '分工最多 {max} 条。改少后整份重报。', en: 'At most {max} roles. Reduce them and send the whole policy again.' },
52
53
  'policy.err.note_too_long': { zh: '补充说明最多 {max} 个字。', en: 'The note is at most {max} characters.' },
53
54
 
@@ -186,7 +187,7 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
186
187
  / my default model policy (how to set one when there is none)
187
188
  model policy set --primary <模型>[,<模型>] [--role <分工名>=<模型>[=<说明>]] ... [--note "<一句>"] [--record-mode call|summary]
188
189
  设置默认策略(整份替换,只影响之后没单独说明的报名)。主力 1–2 个;--role 可写多次,
189
- 分工名自己起,例如 --role 写代码=<模型A> --role "做图=<模型B>=只出示意图"
190
+ 分工名自己起,例如 --role 复杂判断=<模型A> --role "做图=<模型B>=只出示意图"
190
191
  (分工名、模型名、说明里都不能带「=」;超出条数或字数时平台会说明哪一条不行)
191
192
  模型名写官方标识,精确到型号(同厂商不同系列是不同模型);
192
193
  写成常见别名平台也会自动归一,不用去查价格表。