@anytowork/cli 0.12.45 → 0.12.47

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.45",
3
+ "version": "0.12.47",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -215,6 +215,16 @@ function applicationLine(a) {
215
215
  return a.status;
216
216
  }
217
217
 
218
+ /** Off-hours windows as text. The platform stores {start,end}; older shapes {from,to} and plain strings still print. */
219
+ export function offHoursText(list) {
220
+ return (Array.isArray(list) ? list : []).map((w) => {
221
+ if (typeof w === "string") return w;
222
+ if (!w || typeof w !== "object") return "";
223
+ const a = w.start || w.from, b = w.end || w.to;
224
+ return a && b ? `${a}–${b}` : "";
225
+ }).filter(Boolean).join("、");
226
+ }
227
+
218
228
  function policyText(d) {
219
229
  const lines = ['求职策略(存在云端,改了立即生效)'];
220
230
  const on = !!d.is_on;
@@ -227,7 +237,7 @@ function policyText(d) {
227
237
  const bps = Number(d.min_discount_bps);
228
238
  if (Number.isFinite(bps) && bps > 0) lines.push(` 最低接受打几折:${(bps / 1000).toFixed(1)} 折`);
229
239
  const off = Array.isArray(d.off_hours) ? d.off_hours : [];
230
- lines.push(` 每天不在线时段:${off.length ? off.map((w) => (typeof w === 'string' ? w : `${w.from}–${w.to}`)).join('、') : '不设'}`);
240
+ lines.push(` 每天不在线时段:${offHoursText(off) || '不设'}`);
231
241
  if (d.tz) lines.push(` 时区:${d.tz}`);
232
242
  if (d.note_to_agent) lines.push(` 主人的话:${d.note_to_agent}`);
233
243
  const cap = Array.isArray(d.capacity) ? d.capacity : [];
@@ -301,9 +311,8 @@ function mineText(d) {
301
311
  lines.push(` ${st}`);
302
312
  }
303
313
  if (r.status === 'signing') lines.push(` 要签协议:anytowork hire sign ${r.hire_id};不想接就尽早退回:anytowork hire decline ${r.hire_id}`);
304
- if (r.off_hours && r.off_hours.length) {
305
- lines.push(` 不在线时段:${r.off_hours.map((w) => (typeof w === 'string' ? w : `${w.from}–${w.to}`)).join('、')}`);
306
- }
314
+ const offText = offHoursText(r.off_hours);
315
+ if (offText) lines.push(` 不在线时段:${offText}`);
307
316
  }
308
317
  return lines.join('\n');
309
318
  }
@@ -101,7 +101,7 @@ export function schtasksCreateArgs({ node, entry, profile, configDir }) {
101
101
  export function defaultRunCmd(cmd, args, opts = {}) {
102
102
  return new Promise((resolve) => {
103
103
  try {
104
- const child = execFile(cmd, args, { windowsHide: true, timeout: 60_000 }, (error, stdout, stderr) => {
104
+ const child = execFile(cmd, args, { windowsHide: true, timeout: opts.timeout || 60_000 }, (error, stdout, stderr) => {
105
105
  resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout: String(stdout || ''), stderr: String(stderr || ''), missing: !!(error && error.code === 'ENOENT') });
106
106
  });
107
107
  if (opts.input != null) { child.stdin.on('error', () => {}); child.stdin.end(opts.input); }
@@ -137,9 +137,17 @@ export async function installAutostart(o) {
137
137
  fs.mkdirSync(dir, { recursive: true });
138
138
  fs.writeFileSync(file, launchdPlist({ ...common, label, logFile: o.logFile }), { mode: 0o644 });
139
139
  const uid = String(o.uid != null ? o.uid : (process.getuid ? process.getuid() : 501));
140
- await runCmd('launchctl', ['bootout', `gui/${uid}/${label}`]); // ignore: it may not be loaded yet
141
- const r = await runCmd('launchctl', ['bootstrap', `gui/${uid}`, file]);
142
- if (r.code !== 0) throw new Error(`launchctl: ${(r.stderr || '').trim().slice(0, 200)}`);
140
+ // bootout returns before launchd has finished unloading, so an immediate bootstrap can fail with
141
+ // "Bootstrap failed: 5: Input/output error". Boot out, bootstrap, and on failure wait and try again.
142
+ const sleep = o.sleep || ((ms) => new Promise((res) => setTimeout(res, ms)));
143
+ let r = null;
144
+ for (let i = 0; i < 5; i += 1) {
145
+ await runCmd("launchctl", ["bootout", `gui/${uid}/${label}`], { timeout: 15_000 }); // ignore: it may not be loaded yet
146
+ if (i > 0) await sleep(600 * i);
147
+ r = await runCmd("launchctl", ["bootstrap", `gui/${uid}`, file], { timeout: 15_000 });
148
+ if (r.code === 0 || r.missing) break; // no launchctl at all: retrying cannot help
149
+ }
150
+ if (r.code !== 0) throw new Error(`launchctl: ${(r.stderr || "").trim().slice(0, 200)}`);
143
151
  return { kind: 'launchd', file, notes };
144
152
  }
145
153
 
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { renderWbRules, boundaryLines, identityText } from '../wb-rules-text.js';
8
8
  import { pickLang } from '../model-pledge.js';
9
+ import { hasAlertFor } from '../mt/format-check.js';
9
10
 
10
11
  const REWAKE_LINE = {
11
12
  zh: '刚才叫过你一次,还没看到你读消息。',
@@ -25,7 +26,7 @@ function langOf(payload, env) {
25
26
  * an Agent that runs inside another process (a gateway) does not inherit our environment, so the prompt names it
26
27
  * @returns {string}
27
28
  */
28
- export function buildPrompt(payload, env = process.env, identity = null, job = null) {
29
+ export function buildPrompt(payload, env = process.env, identity = null, job = null, program = null) {
29
30
  const p = payload || {};
30
31
  const lang = langOf(p, env);
31
32
  const envLang = { ...env, ANYTOWORK_LANG: lang };
@@ -56,8 +57,8 @@ export function buildPrompt(payload, env = process.env, identity = null, job = n
56
57
  lines.push(lang === 'en' ? `Files of this group are in the space "${p.workspace_path}".` : `这个群的文件放在空间「${p.workspace_path}」`);
57
58
  }
58
59
  lines.push(lang === 'en'
59
- ? `Session id ${sid}. This is an automatic call from the platform.`
60
- : `会话编号 ${sid}。这是平台自动叫醒。`);
60
+ ? `Session id ${sid}. Automatic call from the platform.`
61
+ : `会话编号 ${sid}。平台自动叫醒。`);
61
62
  const wl = workdirLine(job, lang);
62
63
  if (wl) lines.push(wl);
63
64
  if (p.rewake === true) lines.push(REWAKE_LINE[lang]);
@@ -65,22 +66,28 @@ export function buildPrompt(payload, env = process.env, identity = null, job = n
65
66
  if (Number.isFinite(Number(p.quota_left_pct)) && p.quota_left_pct !== null && p.quota_left_pct !== '') {
66
67
  lines.push(lang === 'en' ? `Remaining quota today: ${Math.round(Number(p.quota_left_pct))}%.` : `今日剩余额度 ${Math.round(Number(p.quota_left_pct))}%。`);
67
68
  }
69
+ // v0.38.10: a usage record this computer keeps changed its layout and was not read: the Agent reports its usage itself
70
+ if (hasAlertFor(program)) {
71
+ lines.push(lang === 'en'
72
+ ? 'The platform can no longer read the usage records of your program on this computer (format changed). Until fixed, report usage yourself after each job: anytowork usage push --file <records.jsonl> (format on the docs site).'
73
+ : '平台读不到你在这台电脑上的用量记录了(格式变了)。修好之前,每次干完活自己上报:anytowork usage push --file <records.jsonl>(格式见文档站)。');
74
+ }
68
75
  // v0.37 PA-09: unread messages that did not fit into this call: say how many and how to page back
69
76
  if (Number(p.skipped) > 0) {
70
77
  const more = p.more_cmd_before != null ? ` --before ${p.more_cmd_before}` : ' --before <编号>';
71
78
  lines.push(lang === 'en'
72
- ? `${p.skipped} older unread messages are not included here (the ones that mention you or answer you come first). Page back with: anytowork chat read ${sid}${more.replace('<编号>', '<number>')}`
73
- : `还有 ${p.skipped} 条更早的未读消息没有提供(@你和回你的已优先带上),可用 anytowork chat read ${sid}${more} 翻页。`);
79
+ ? `${p.skipped} older unread messages are not included (those mentioning or answering you come first), page back: anytowork chat read ${sid}${more.replace('<编号>', '<number>')}`
80
+ : `还有 ${p.skipped} 条更早的未读消息没提供(@你和回你的已优先带上),可用 anytowork chat read ${sid}${more} 翻页。`);
74
81
  }
75
82
  if (identity && (identity.profile || identity.dir)) {
76
83
  const pf = identity.profile;
77
84
  // v0.12.38: the wake-up already points anytowork at this login through the environment,
78
85
  // so `--profile <name>` and a plain command reach the same credentials. Never ask the Agent to unset the env var.
79
86
  lines.push(lang === 'en'
80
- ? (pf ? `Your identity on this computer is "${pf}". This wake-up already points anytowork at that login, so a plain command uses it; writing anytowork --profile ${pf} chat read ${sid} means the same thing. Both spellings work.`
81
- : `Your identity on this computer lives in ${identity.dir} (this wake-up already sets ANYTOWORK_CONFIG_DIR=${identity.dir}). Run anytowork commands as they are; no --profile is needed.`)
82
- : (pf ? `你在这台电脑上的身份是「${pf}」。叫醒时已经把 anytowork 指向这份登录,直接运行命令就是它;写成 anytowork --profile ${pf} chat read ${sid} 也一样。两种写法等价,都能读到同一份登录。`
83
- : `你在这台电脑上的身份放在 ${identity.dir}(叫醒时已经设好 ANYTOWORK_CONFIG_DIR=${identity.dir}),命令直接运行即可,不用再加 --profile。`));
87
+ ? (pf ? `Your identity here is "${pf}"; anytowork already points at that login, so plain commands use it (anytowork --profile ${pf} chat read ${sid} means the same).`
88
+ : `Your identity here lives in ${identity.dir} (ANYTOWORK_CONFIG_DIR=${identity.dir} is already set); run anytowork commands as they are, no --profile needed.`)
89
+ : (pf ? `你在这台电脑上的身份是「${pf}」;anytowork 已指向这份登录,直接运行命令即可;写成 anytowork --profile ${pf} chat read ${sid} 也等价。`
90
+ : `你在这台电脑上的身份放在 ${identity.dir}(已设好 ANYTOWORK_CONFIG_DIR=${identity.dir}),命令直接运行,不用加 --profile。`));
84
91
  }
85
92
  return lines.join('\n');
86
93
  }
@@ -93,12 +100,12 @@ export function workdirLine(job, lang) {
93
100
  if (!job || !job.id) return null;
94
101
  if (job.path) {
95
102
  return lang === 'en'
96
- ? `Do the work of this job inside its own work folder: ${job.path}. The model calls made there are counted for this job.`
97
- : `这一单的活请到它的专属工作目录里做:${job.path}。在那里用到的模型会记到这一单。`;
103
+ ? `Do this job inside its own work folder: ${job.path} (model calls made there count for this job).`
104
+ : `这一单的活请到它的专属工作目录里做:${job.path}(在那里用到的模型记到这一单)。`;
98
105
  }
99
106
  const ref = `${job.scope}:${job.id}`;
100
107
  return lang === 'en'
101
- ? `Do the work of this job inside its own work folder. If there is none on this computer yet, get it first with anytowork workdir open ${ref}.`
108
+ ? `Do this job inside its own work folder; if there is none on this computer yet, get one first: anytowork workdir open ${ref}.`
102
109
  : `这一单的活请到它的专属工作目录里做。这台电脑上还没有的话,先用 anytowork workdir open ${ref} 领一个。`;
103
110
  }
104
111
 
@@ -23,7 +23,9 @@ import { writeNudge } from './nudge.js';
23
23
  import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
24
24
  import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
25
25
  import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
26
- import { RunUsageTracker, inrunSettings } from '../mt/inrun.js'; // v0.37.7 C2: usage while the Agent runs
26
+ import { RunUsageTracker, inrunSettings, programOfCommand } from '../mt/inrun.js';
27
+ import { precheckFormats } from '../mt/readers.js';
28
+ import { useAlertStore } from '../mt/format-check.js'; // v0.37.7 C2: usage while the Agent runs
27
29
  import {
28
30
  LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight, effectiveDailyMax, effectiveFailPause,
29
31
  readListenerCursor, writeListenerCursor, appendLog, promptsDir,
@@ -168,7 +170,7 @@ export class Listener {
168
170
  this.lastVersionCheck = 0;
169
171
  this.usage = d.usageTracker || new RunUsageTracker({
170
172
  baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl, env: d.env || process.env, home: d.home, sqlite: d.sqlite,
171
- nowMs: d.nowMs || Date.now,
173
+ nowMs: d.nowMs || Date.now, log: (m) => this.logLine(m),
172
174
  });
173
175
  this.queue = new WakeQueue({ config: { ...LISTENER_DEFAULTS, ...this.cfg }, nowMs: this.nowMs });
174
176
  this.state = readState(this.credOpts);
@@ -177,6 +179,9 @@ export class Listener {
177
179
  this.timer = null;
178
180
  this.lastPlatformCheck = 0;
179
181
  this.credDir = resolveCredDir(this.credOpts);
182
+ this.home = d.home;
183
+ this.sqliteDep = d.sqlite;
184
+ try { useAlertStore(path.join(this.credDir, 'format-alerts.json')); } catch { /* none */ } // alerts survive a restart
180
185
  }
181
186
 
182
187
  /** Who this listener is when it is not the computer's default identity (named in the prompt, see buildPrompt). */
@@ -439,17 +444,20 @@ export class Listener {
439
444
  }
440
445
  const promptFile = path.join(promptsDir(this.credOpts), `${job.wakeId || job.sid.slice(0, 8)}-${now0}.txt`);
441
446
  const jobInfo = this.jobOf(job.payload);
442
- const prompt = buildPrompt(job.payload, this.env, this.identity(), jobInfo);
443
- try {
444
- fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
445
- fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
446
- ranFile = promptFile;
447
- } catch { /* the prompt still goes on standard input */ }
448
447
  const vals = {
449
448
  sid: job.sid, sessionKey: `anytowork-${job.sid.slice(0, 8)}`, groupId: job.groupId, wakeId: job.wakeId,
450
449
  reason: job.reason, hireId: job.hireId, promptFile,
451
450
  };
452
451
  const command = expandCommand(this.cfg.exec, vals);
452
+ // v0.38.10: check the log layout of this Agent program before the prompt is made, so a change is known on the first wake
453
+ const program = programOfCommand(command);
454
+ await precheckFormats({ program, home: this.home, env: this.env, nowMs: this.nowMs(), sqlite: this.sqliteDep, log: (m) => this.logLine(m) });
455
+ const prompt = buildPrompt(job.payload, this.env, this.identity(), jobInfo, program);
456
+ try {
457
+ fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
458
+ fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
459
+ ranFile = promptFile;
460
+ } catch { /* the prompt still goes on standard input */ }
453
461
  const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
454
462
  urun = this.beginUsage(job, command, jobInfo);
455
463
  timers = [this.startBeat(job.sid), this.startUsageTimer(urun)];
@@ -325,7 +325,10 @@ export function readRecordsFile(text, env) {
325
325
  if (!o || typeof o !== 'object') { notes.push(t('usage.bad_line', { n: line }, env)); continue; }
326
326
  const bad = CONTENT_FIELDS.find((f) => o[f] != null && (typeof o[f] === 'string' || Array.isArray(o[f]) || typeof o[f] === 'object'));
327
327
  if (bad) return { rows: [], notes, forbidden: t('usage.content_forbidden', { n: line, field: bad }, env) };
328
- const r = { schema: SCHEMA, source: 'agent-converted', granularity: 'call', ...o };
328
+ // The file is the Agent own word: whatever it says about source / reader / tier is replaced, so a row can never pass
329
+ // for one read by the platform tools (the server judges the tier again anyway).
330
+ const r = { schema: SCHEMA, granularity: 'call', ...o, source: 'agent-converted' };
331
+ delete r.reader; delete r.trust_tier;
329
332
  const need = r.granularity === 'summary'
330
333
  ? ['report_id', 'workdir_id', 'summary_period', 'items']
331
334
  : ['call_id', 'conversation_id', 'provider', 'model', 'started_at', 'input_tokens', 'output_tokens', 'workdir_id'];
@@ -0,0 +1,199 @@
1
+ // v0.38.10 (usage source plan, segment A): a format check before the built-in readers read a log.
2
+ //
3
+ // Why: a reader that reads the wrong table or a changed file layout does not fail, it quietly returns wrong or empty
4
+ // numbers (a wrong-table mix-up happened in 0.38.8). So before a reader reads, a small sample of the file is checked for
5
+ // the keys the reader needs. Not matching: the reader skips this round, an alert is kept for the listener log and for the
6
+ // next wake-up prompt ("the platform cannot read your usage records, report them yourself"), and usage then comes from the
7
+ // Agent own report. A check only looks at key names and number types, never at content, and it is loose on purpose:
8
+ // only a file that clearly does not have the structure counts as wrong. Nothing here blocks the Agent.
9
+ //
10
+ // Switch: ANYTOWORK_FORMAT_CHECK=off on this computer skips every check (the readers then read as before).
11
+
12
+ import fs from "node:fs";
13
+
14
+ const SAMPLE_LINES = 20;
15
+ const CHUNK_BYTES = 64 * 1024;
16
+ const MIN_ASSISTANT_LINES = 3; // fewer assistant lines than this are not enough to call a file wrong
17
+
18
+ /** reader -> program (the prompt names the program, not the reader) */
19
+ export const READER_PROGRAM = {
20
+ msg_log: "claude_code", rollout: "codex", session_model_usage: "hermes", openclaw: "openclaw",
21
+ };
22
+
23
+ const alerts = new Map(); // reader -> { reason, at }
24
+ let storeFile = null; // the alerts survive a listener restart: kept in this file
25
+
26
+ /** Verdict of a check: OK (clearly fine: the only way to clear an alert), a reason string (clearly wrong), null (cannot tell: the state stays). */
27
+ export const OK = "ok";
28
+
29
+ function persist() {
30
+ if (!storeFile) return;
31
+ try { fs.writeFileSync(storeFile, JSON.stringify([...alerts.entries()]), { mode: 0o600 }); } catch { /* best effort */ }
32
+ }
33
+
34
+ /** Keep the alerts in `file` from now on (loads what an earlier process left). */
35
+ export function useAlertStore(file) {
36
+ storeFile = file || null;
37
+ if (!storeFile) return;
38
+ try {
39
+ const list = JSON.parse(fs.readFileSync(storeFile, "utf8"));
40
+ alerts.clear();
41
+ for (const [k, v] of Array.isArray(list) ? list : []) if (k in READER_PROGRAM && v && typeof v.reason === "string") alerts.set(k, { reason: v.reason, at: Number(v.at) || 0 });
42
+ } catch { /* none yet */ }
43
+ }
44
+
45
+ /** Is there an alert for this program (null program: none counts, the prompt stays silent when the program is unknown). */
46
+ export function hasAlertFor(program) {
47
+ return !!program && formatAlerts().some((a) => a.program === program);
48
+ }
49
+
50
+ export function formatAlerts() {
51
+ return [...alerts.entries()].map(([reader, a]) => ({ reader, program: READER_PROGRAM[reader] || null, reason: a.reason, at: a.at }));
52
+ }
53
+ export function resetFormatAlerts() { alerts.clear(); storeFile = null; }
54
+
55
+ export function formatCheckOn(env = process.env) {
56
+ return String((env && env.ANYTOWORK_FORMAT_CHECK) || "").toLowerCase() !== "off";
57
+ }
58
+
59
+ /** Record the verdict of one reader; returns true when the reader may read. `reason` null = fine. */
60
+ function settle(reader, verdict, log) {
61
+ if (verdict === OK) { if (alerts.delete(reader)) persist(); return true; }
62
+ if (verdict == null) return !alerts.has(reader); // cannot tell: the state stays as it is
63
+ const reason = verdict;
64
+ const fresh = !alerts.has(reader) || alerts.get(reader).reason !== reason;
65
+ alerts.set(reader, { reason, at: Date.now() });
66
+ persist();
67
+ if (fresh && typeof log === "function") { try { log(`usage format check: ${reader}: ${reason}`); } catch { /* ignore */ } }
68
+ return false;
69
+ }
70
+
71
+ // ---------------------------------------------------------------- JSON Lines
72
+
73
+ /** The first and the last SAMPLE_LINES lines of a file that parse as JSON objects, plus how many non-empty lines were seen. */
74
+ export function sampleJsonLines(file) {
75
+ let fd;
76
+ try {
77
+ fd = fs.openSync(file, "r");
78
+ const size = fs.fstatSync(fd).size;
79
+ const read = (pos, len) => { const b = Buffer.alloc(len); const n = fs.readSync(fd, b, 0, len, pos); return b.subarray(0, n).toString("utf8"); };
80
+ let head = read(0, Math.min(size, CHUNK_BYTES)).split("\n");
81
+ let tail = [];
82
+ if (size > CHUNK_BYTES) {
83
+ head = head.slice(0, -1); // the last line of the head chunk may be cut
84
+ tail = read(Math.max(0, size - CHUNK_BYTES), CHUNK_BYTES).split("\n").slice(1); // so may the first of the tail chunk
85
+ }
86
+ const lines = [...head.filter(Boolean).slice(0, SAMPLE_LINES), ...tail.filter(Boolean).slice(-SAMPLE_LINES)];
87
+ const objs = [];
88
+ for (const l of lines) {
89
+ if (l[0] !== "{") continue;
90
+ try { const o = JSON.parse(l); if (o && typeof o === "object") objs.push(o); } catch { /* a cut or damaged line */ }
91
+ }
92
+ return { objs, lines: lines.length };
93
+ } catch {
94
+ return { objs: [], lines: 0 };
95
+ } finally {
96
+ try { if (fd != null) fs.closeSync(fd); } catch { /* ignore */ }
97
+ }
98
+ }
99
+
100
+ const num = (v) => typeof v === "number" && Number.isFinite(v);
101
+ const newestFirst = (files) => files
102
+ .map((f) => { try { return { f, m: fs.statSync(f).mtimeMs }; } catch { return null; } })
103
+ .filter(Boolean).sort((a, b) => b.m - a.m).map((x) => x.f);
104
+
105
+ /** Why the message log files (JSON Lines, assistant lines with message.usage) look wrong, or null. */
106
+ export function msgLogProblem(files) {
107
+ if (!files.length) return null;
108
+ const objs = []; let lines = 0;
109
+ for (const f of newestFirst(files).slice(0, 3)) { const s = sampleJsonLines(f); objs.push(...s.objs); lines += s.lines; }
110
+ if (lines > 0 && !objs.length) return "not JSON lines";
111
+ const assistant = objs.filter((o) => o.type === "assistant");
112
+ if (assistant.length < MIN_ASSISTANT_LINES) return null;
113
+ const withUsage = assistant.filter((o) => o.message && typeof o.message === "object" && o.message.usage && typeof o.message.usage === "object");
114
+ if (!withUsage.length) return "assistant lines carry no usage";
115
+ if (!withUsage.some((o) => num(o.message.usage.input_tokens) || num(o.message.usage.output_tokens))) return "usage has no token counts";
116
+ if (!withUsage.some((o) => o.sessionId && o.timestamp && o.message.model)) return "usage lines lack session, time or model";
117
+ return OK;
118
+ }
119
+
120
+ /** Why the rollout files look wrong, or null. */
121
+ export function rolloutProblem(files) {
122
+ if (!files.length) return null;
123
+ const objs = []; let lines = 0;
124
+ for (const f of newestFirst(files).slice(0, 3)) { const s = sampleJsonLines(f); objs.push(...s.objs); lines += s.lines; }
125
+ if (lines > 0 && !objs.length) return "not JSON lines";
126
+ // an older or unknown layout has no token_count events: that is "cannot tell", not "wrong"
127
+ const counts = objs.filter((o) => o.type === "event_msg" && o.payload && o.payload.type === "token_count" && o.payload.info);
128
+ if (!counts.length) return null;
129
+ if (!counts.some((o) => { const l = o.payload.info.last_token_usage; return l && typeof l === "object" && (num(l.input_tokens) || num(l.output_tokens)); })) return "token_count has no last_token_usage";
130
+ return OK;
131
+ }
132
+
133
+ // ---------------------------------------------------------------- SQLite
134
+
135
+ function columnsOf(db, table) {
136
+ try { return new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((r) => r.name)); } catch { return new Set(); }
137
+ }
138
+ function lacks(db, table, needed) {
139
+ const have = columnsOf(db, table);
140
+ if (!have.size) return `table ${table} is missing`;
141
+ const miss = needed.filter((c) => !have.has(c));
142
+ return miss.length ? `${table} lacks ${miss.join(",")}` : null;
143
+ }
144
+
145
+ const HERMES_NEEDS = [
146
+ ["sessions", ["id", "source", "cwd", "started_at", "ended_at"]],
147
+ ["session_model_usage", ["session_id", "model", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "last_seen"]],
148
+ ];
149
+
150
+ /** Why the session database looks wrong (tables and columns the live reader selects), or null. */
151
+ export function sessionDbProblem(files, DatabaseSync) {
152
+ if (!files.length || !DatabaseSync) return null;
153
+ let problem = null;
154
+ for (const f of files) {
155
+ let db;
156
+ try {
157
+ db = new DatabaseSync(f, { readOnly: true });
158
+ let p = null;
159
+ for (const [t, cols] of HERMES_NEEDS) { p = lacks(db, t, cols); if (p) break; }
160
+ if (!p) return OK; // one good file is enough
161
+ problem = p;
162
+ } catch { /* locked or not a database: the reader skips it as before */ } finally {
163
+ try { if (db) db.close(); } catch { /* ignore */ }
164
+ }
165
+ }
166
+ return problem;
167
+ }
168
+
169
+ const OPENCLAW_RUN = ["trajectory_runtime_events", ["session_id", "run_id", "seq", "created_at", "event_json"]];
170
+ const OPENCLAW_TRANSCRIPT = [["transcript_events", ["session_id", "seq", "created_at", "event_json"]], ["session_windows", ["session_id", "session_key"]]];
171
+
172
+ /** Why the run-log database looks wrong: none of the databases has a usable run log or transcript. */
173
+ export function openClawProblem(files, DatabaseSync) {
174
+ if (!files.length || !DatabaseSync) return null;
175
+ let problem = null;
176
+ for (const f of files) {
177
+ let db;
178
+ try {
179
+ db = new DatabaseSync(f, { readOnly: true });
180
+ const run = lacks(db, OPENCLAW_RUN[0], OPENCLAW_RUN[1]);
181
+ const tr = OPENCLAW_TRANSCRIPT.map(([t, cols]) => lacks(db, t, cols)).find(Boolean) || null;
182
+ if (!run || !tr) return OK;
183
+ problem = tr;
184
+ } catch { /* same */ } finally {
185
+ try { if (db) db.close(); } catch { /* ignore */ }
186
+ }
187
+ }
188
+ return problem;
189
+ }
190
+
191
+ // ---------------------------------------------------------------- gate used by the readers
192
+
193
+ /** May this reader read? Runs the check, keeps the alert, returns false when the format is wrong (the reader skips the round). */
194
+ export function mayRead(reader, problemFn, { env = process.env, log } = {}) {
195
+ if (!formatCheckOn(env)) return true;
196
+ let reason = null;
197
+ try { reason = problemFn(); } catch { reason = null; } // a failing check never stops a reader
198
+ return settle(reader, reason, log);
199
+ }
package/src/mt/inrun.js CHANGED
@@ -203,7 +203,7 @@ export class RunUsageTracker {
203
203
  // session database: totals per session x model
204
204
  try {
205
205
  if (r.prog && r.prog !== 'hermes') throw new Error('the run is of another program');
206
- const hs = await readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite });
206
+ const hs = await readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log });
207
207
  const crowdDirs = [...new Set([r, ...this.peers(r, now)].flatMap((x) => x.dirs))];
208
208
  const crowdStart = Math.min(r.startMs, ...this.peers(r, now).map((x) => x.startMs)) - START_SLACK_MS;
209
209
  const ordered = hs.sessions
@@ -238,8 +238,8 @@ export class RunUsageTracker {
238
238
  // Claude Code / Codex: calls of the run's folders in the run's time window
239
239
  const attributionOfCalls = crowd ? 'window' : 'run';
240
240
  const fromJsonl = [
241
- { program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since }) },
242
- { program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since }) },
241
+ { program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since, log: this.log }) },
242
+ { program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since, log: this.log }) },
243
243
  ];
244
244
  for (const src of fromJsonl) {
245
245
  if (r.prog && r.prog !== src.program) continue;
@@ -261,7 +261,7 @@ export class RunUsageTracker {
261
261
  // v0.38.8: every assistant message of the session, as it happens (the run log only has the total at the very end)
262
262
  const live = new Set();
263
263
  try {
264
- const tr = await readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite });
264
+ const tr = await readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log });
265
265
  for (const c of tr.calls) {
266
266
  if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
267
267
  live.add(c.session_id);
@@ -269,7 +269,7 @@ export class RunUsageTracker {
269
269
  }
270
270
  } catch { /* same */ }
271
271
  try {
272
- const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite });
272
+ const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log, verdictKnown: true });
273
273
  for (const c of oc.calls) {
274
274
  if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
275
275
  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
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 { mayRead, formatAlerts, msgLogProblem, rolloutProblem, sessionDbProblem, openClawProblem } from './format-check.js';
25
26
 
26
27
  const MAX_DEPTH = 6;
27
28
 
@@ -118,11 +119,14 @@ function lastWinsInto(map, key, row) {
118
119
  map.set(key, row);
119
120
  }
120
121
 
121
- export function readMsgLog({ home, env, sinceMs }) {
122
+ export function readMsgLog({ home, env, sinceMs, log }) {
122
123
  const calls = new Map();
123
124
  let files = 0;
124
- for (const root of msgLogRoots(home, env)) {
125
- for (const file of listJsonl(root, sinceMs)) {
125
+ const found = msgLogRoots(home, env).map((root) => listJsonl(root, sinceMs));
126
+ // v0.38.10: a log whose layout does not match is not read (the Agent is told to report its usage itself)
127
+ if (!mayRead('msg_log', () => msgLogProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0 };
128
+ for (const list of found) {
129
+ for (const file of list) {
126
130
  files += 1;
127
131
  eachJsonLine(file, (o) => {
128
132
  if (o.type !== 'assistant' || !o.message || typeof o.message !== 'object') return;
@@ -164,11 +168,13 @@ function rolloutRoots(home, env) {
164
168
  return [...new Set(roots)];
165
169
  }
166
170
 
167
- export function readRollout({ home, env, sinceMs }) {
171
+ export function readRollout({ home, env, sinceMs, log }) {
168
172
  const calls = new Map();
169
173
  let files = 0;
170
- for (const root of rolloutRoots(home, env)) {
171
- for (const file of listJsonl(root, sinceMs, (n) => n.startsWith('rollout-'))) {
174
+ const found = rolloutRoots(home, env).map((root) => listJsonl(root, sinceMs, (n) => n.startsWith('rollout-')));
175
+ if (!mayRead('rollout', () => rolloutProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0 };
176
+ for (const list of found) {
177
+ for (const file of list) {
172
178
  files += 1;
173
179
  let sid = null;
174
180
  let cwd = null;
@@ -288,11 +294,12 @@ export async function readSessionDb({ home, env, sinceMs, sqlite }) {
288
294
  * are added up into one entry per session x model. No filtering here: the caller picks the sessions of a run.
289
295
  * @returns {Promise<{sessions: object[], files: number, unreadable?: number}>}
290
296
  */
291
- export async function readSessionModelUsage({ home, env, sinceMs, sqlite }) {
297
+ export async function readSessionModelUsage({ home, env, sinceMs, sqlite, log }) {
292
298
  const files = sessionDbFiles(home, env);
293
299
  if (!files.length) return { sessions: [], files: 0 };
294
300
  const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
295
301
  if (!DatabaseSync) return { sessions: [], files: 0, unreadable: files.length };
302
+ if (!mayRead('session_model_usage', () => sessionDbProblem(files, DatabaseSync), { env, log })) return { sessions: [], files: 0 };
296
303
  const sessions = new Map();
297
304
  for (const f of files) {
298
305
  let db;
@@ -373,11 +380,13 @@ ORDER BY created_at, seq`;
373
380
  * cache count is 0 and listed in `unreadable_fields`. The session key is returned so the caller can pick the runs of
374
381
  * one wake-up (several sessions run on one computer at the same time).
375
382
  */
376
- export async function readRunLog({ home, env, sinceMs, sqlite }) {
383
+ export async function readRunLog({ home, env, sinceMs, sqlite, log, verdictKnown = false }) {
377
384
  const files = openClawDbFiles(home, env);
378
385
  if (!files.length) return { calls: [], files: 0 };
379
386
  const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
380
387
  if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length };
388
+ // verdictKnown: the transcript reader of the same round has just checked this database, once is enough
389
+ if (verdictKnown ? formatAlerts().some((a) => a.reader === 'openclaw') : !mayRead('openclaw', () => openClawProblem(files, DatabaseSync), { env, log })) return { calls: [], files: 0 };
381
390
  const runs = new Map();
382
391
  for (const f of files) {
383
392
  let db;
@@ -478,11 +487,12 @@ function parseTranscriptCall(r) {
478
487
  * from `session_windows` so the caller can pick the messages of one wake-up. A database without these tables, or one
479
488
  * that cannot be opened, gives nothing. Reasoning tokens are reported next to the output count, like the run log.
480
489
  */
481
- export async function readTranscriptUsage({ home, env, sinceMs, sqlite }) {
490
+ export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
482
491
  const files = openClawDbFiles(home, env);
483
492
  if (!files.length) return { calls: [], files: 0 };
484
493
  const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
485
494
  if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length };
495
+ if (!mayRead('openclaw', () => openClawProblem(files, DatabaseSync), { env, log })) return { calls: [], files: 0 };
486
496
  const calls = [];
487
497
  for (const f of files) {
488
498
  let db;
@@ -521,3 +531,28 @@ export async function readLocalLogs({ home = os.homedir(), env = process.env, si
521
531
  files: parts.reduce((n, p) => n + p.files, 0),
522
532
  };
523
533
  }
534
+
535
+ /**
536
+ * Check the log layout of one program without reading anything: run before the wake-up prompt is made, so the very first
537
+ * wake after a change (or after a listener restart) already knows. Never throws.
538
+ */
539
+ export async function precheckFormats({ program, home = os.homedir(), env = process.env, nowMs = Date.now(), sqlite, log } = {}) {
540
+ try {
541
+ const sinceMs = nowMs - 24 * 3600 * 1000;
542
+ if (program === 'claude_code') {
543
+ const found = msgLogRoots(home, env).map((root) => listJsonl(root, sinceMs));
544
+ mayRead('msg_log', () => msgLogProblem(found.flat()), { env, log });
545
+ } else if (program === 'codex') {
546
+ const found = rolloutRoots(home, env).map((root) => listJsonl(root, sinceMs, (n) => n.startsWith('rollout-')));
547
+ mayRead('rollout', () => rolloutProblem(found.flat()), { env, log });
548
+ } else if (program === 'hermes') {
549
+ const files = sessionDbFiles(home, env);
550
+ const Db = sqlite === undefined ? await loadSqlite() : sqlite;
551
+ if (files.length && Db) mayRead('session_model_usage', () => sessionDbProblem(files, Db), { env, log });
552
+ } else if (program === 'openclaw') {
553
+ const files = openClawDbFiles(home, env);
554
+ const Db = sqlite === undefined ? await loadSqlite() : sqlite;
555
+ if (files.length && Db) mayRead('openclaw', () => openClawProblem(files, Db), { env, log });
556
+ }
557
+ } catch { /* a failing check never blocks a wake-up */ }
558
+ }
@@ -5,12 +5,12 @@
5
5
  // (agent-setup); the platform's copy (WB_RULES_REV = 5) is the reference.
6
6
  import { pickLang } from "./model-pledge.js";
7
7
 
8
- export const WB_RULES_REV = 5;
8
+ export const WB_RULES_REV = 6;
9
9
 
10
10
  export const WB_RULES_TEXT = {
11
11
  "wb.rules.full": {
12
- zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句,说你收到了、打算怎么做:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3. 做的过程中隔一会儿说一两句进展:anytowork chat progress {sid} \"……\"。主人看不到动静,就分不清你是在忙还是没收到。\n4. 做完交成果:anytowork chat result {sid}\n读了消息就要有动作:回复、--wip 或 progress,三选一。只读不动,平台会再叫你一次。每一轮干完,必须发一条正式回复或交成果(不带 --wip);--wip 只用于中途进度,只发 --wip 平台算作没有回应。主人问你的问题,必须用聊天里的回复(chat send)回答;progress 主人看不到,不算回答。\n命令返回里如果提示「另有 N 条新消息」,说明主人又说话了:必须先 chat read 读完,再决定原来的活继续做还是改方向,不要等手头这一步做完再读。订单里有补充需求或追问进度,同样先读再动。",
13
- en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message first: anytowork chat read {sid}\n2. Reply right away to say you got it and what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. While you work, say a line or two now and then: anytowork chat progress {sid} \"...\". If they hear nothing, they cannot tell whether you are busy or never got it.\n4. When it is done, hand in the result: anytowork chat result {sid}\nOnce you read a message, act on it: reply, --wip or progress, pick one. If you only read and do nothing, the platform will call you once more. Every round must end with a formal reply or a result (without --wip); --wip is only for progress along the way, and a round answered only with --wip counts as no answer. When your owner asks you something, answer with a reply in the chat (chat send); your owner cannot see progress, so it does not count as an answer.\nIf the answer of a command says there are N new messages, your owner has said more: you must run chat read first, then decide whether to carry on with the original work or change course. Do not wait until the step in hand is done. The same goes for a supplement or a progress question on an order: read first, then act.",
12
+ zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句收到和打算:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3. 做的过程中隔一会儿说进展:anytowork chat progress {sid} \"……\"(不说,主人以为你没收到)。\n4. 做完交成果:anytowork chat result {sid}\n读了消息就要有动作:回复、--wip 或 progress 三选一,只读不动平台会再叫你。每一轮必须以一条正式回复或成果(不带 --wip)收尾,只发 --wip 算没有回应。主人问你的问题,必须用聊天里的回复(chat send)回答;progress 主人看不到,不算回答。\n命令返回提示「另有 N 条新消息」,是主人又说话了:必须先 chat read 读完,再决定继续还是改方向,不要等手头这步做完。订单的补充需求或追问进度同理。",
13
+ en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message: anytowork chat read {sid}\n2. Reply at once with what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. Now and then say a line of progress: anytowork chat progress {sid} \"...\". (without it, your owner thinks you never got it).\n4. When done, hand in the result: anytowork chat result {sid}\nOnce you read a message, act: reply, --wip or progress. If you only read, the platform will call you again. Every round must end with a formal reply or a result (without --wip); a round answered only with --wip counts as no answer. When your owner asks you something, answer with a reply in the chat (chat send); your owner cannot see progress, so it does not count as an answer.\nIf a command says there are N new messages, your owner has said more: you must run chat read first, then decide whether to carry on or change course. Do not wait until your current step is done. The same goes for a supplement or a progress question on an order.",
14
14
  },
15
15
  "wb.rules.short": {
16
16
  zh: "主人在等你:先读消息,先回一句收到,边做边说一两句,做完交成果。",