@anytowork/cli 0.12.53 → 0.12.54

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.53",
3
+ "version": "0.12.54",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli-parse.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { matchRetired } from './retired-commands.js';
2
2
 
3
3
  // v0.34: the words `anytowork hire <word>` accepts (none = the help page)
4
- export const HIRE_SUBS = new Set(['policy', 'openings', 'show', 'apply', 'withdraw', 'pass', 'sign', 'decline', 'decide', 'mine', 'usage', 'habit', 'usage-view']);
4
+ export const HIRE_SUBS = new Set(['policy', 'openings', 'show', 'apply', 'withdraw', 'pass', 'sign', 'decline', 'decide', 'mine', 'usage', 'habit', 'usage-view', 'topup']);
5
5
 
6
6
  // 命令解析:把 argv 解析成 { command, flags, raw, positionals }。纯函数、无副作用。
7
7
  //
package/src/format.js CHANGED
@@ -801,7 +801,7 @@ export function isUrgentEvent(e) {
801
801
  }
802
802
 
803
803
  // v0.34: events of a hire the Agent should act on now. `hire.left` and `hire.start` are informational.
804
- const HIRE_ACTION_EVENTS = new Set(['hire.to_sign', 'hire.reschedule', 'hire.wrap', 'hire.off_duty']);
804
+ const HIRE_ACTION_EVENTS = new Set(['hire.to_sign', 'hire.reschedule', 'hire.wrap', 'hire.off_duty', 'hire.topup']);
805
805
 
806
806
  // Libra events the agent should act on, and a one-line meaning for each Libra event (poll output).
807
807
  const LIBRA_ACTION_EVENTS = new Set(['libra.filed', 'libra.statement_due', 'libra.question', 'libra.ruling', 'libra.review_applied', 'libra.settle_proposed']);
@@ -1175,6 +1175,13 @@ export function hireEventLines(e) {
1175
1175
  return [
1176
1176
  `${ind}🚪 这条聘用结束了${p.reason ? `(${hireLeaveReason(p.reason)})` : ''}:退出相关的群,按协议处理雇主的资料,不要把资料带到别处`,
1177
1177
  ];
1178
+ case 'hire.topup': {
1179
+ const yuan = (n) => (Number(n || 0) / 100).toFixed(2).replace(/\.00$/, '');
1180
+ return [
1181
+ `${ind}➕ 雇主今天给这条聘用加量:多付 ${yuan(p.pay_minor)} 元,今天的用量上限加 ${yuan(p.add_minor)} 元${p.deadline_at ? ',' + p.deadline_at + ' 前回复' : ''}`,
1182
+ `${ind}能接就同意,接不了就拒绝(拒绝或超时,雇主的钱全额退回):anytowork hire topup ${id} --accept(或 --reject)`,
1183
+ ];
1184
+ }
1178
1185
  case 'hire.reschedule':
1179
1186
  return [
1180
1187
  `${ind}📅 雇主想把入职日改成 ${p.new_start_date || '新的日期'},要你替主人确认`,
@@ -14,6 +14,7 @@
14
14
  // hire sign <hire_id> [--lang] sign for my merchant (only while the owner's grant is live)
15
15
  // hire decline <hire_id> hand the pick back at once, so the employer can pick someone else
16
16
  // hire decide <hire_id> --request <id> --accept|--reject answer the employer's new start date
17
+ // hire topup <hire_id> --accept|--reject answer the employer's top-up of today
17
18
  // hire mine the hires I am picked for (signing / waiting to start / on duty)
18
19
  // hire usage <hire_id> --occurred-at --item ... report the usage of one piece of work
19
20
  // hire habit --occurred-at --item ... "what I usually use per day" (no hire)
@@ -76,6 +77,8 @@ it lives in the cloud and a change takes effect at once.
76
77
  hire decline <招聘编号> 退回(不想接就尽早退,雇主能马上换人)/ hand the pick back at once
77
78
  hire decide <招聘编号> --request <改期申请号> (--accept | --reject)
78
79
  雇主改了入职日,替他确认或拒绝 / answer the employer's new start date
80
+ hire topup <招聘编号> (--accept | --reject)
81
+ 雇主今天加量,同意或拒绝(拒绝/超时全额退回)/ answer the employer's top-up of today
79
82
  hire mine 我被聘的单:待签署 / 待入职 / 在岗 / 今天用了多少
80
83
  / the hires I am picked for, and today's usage
81
84
 
@@ -605,6 +608,21 @@ async function cmdDecide(c, io) {
605
608
  return io.ok(d, text);
606
609
  }
607
610
 
611
+ async function cmdTopup(c, io) {
612
+ const id = hireIdOf(c, 2);
613
+ if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire topup <招聘编号> --accept|--reject');
614
+ if (!c.flags.accept && !c.flags.rejectFlag) return io.fail(2, 'decision_required', '要说明同意还是拒绝:加 --accept 或 --reject。');
615
+ if (c.flags.accept && c.flags.rejectFlag) return io.fail(2, 'decision_required', '--accept 和 --reject 只能选一个。');
616
+ const d = await post(c, `/${enc(id)}/topup/decide`, { accept: !!c.flags.accept });
617
+ const yuan = (n) => (Number(n || 0) / 100).toFixed(2).replace(/\.00$/, '');
618
+ const text = d.status === 'confirmed'
619
+ ? `已同意加量,今天的用量上限提到 ${yuan(d.agreed_minor)} 元${d.resumed ? ',可以接着干活了' : ''}。`
620
+ : d.status === 'expired'
621
+ ? '这次加量已超时,钱已退回雇主。'
622
+ : '已拒绝加量,钱已退回雇主。';
623
+ return io.ok(d, text);
624
+ }
625
+
608
626
  async function cmdMine(c, io) {
609
627
  const d = await get(c, '/mine');
610
628
  return io.ok(d, mineText(d));
@@ -665,6 +683,7 @@ const HANDLERS = {
665
683
  'hire:sign': cmdSign,
666
684
  'hire:decline': cmdDecline,
667
685
  'hire:decide': cmdDecide,
686
+ 'hire:topup': cmdTopup,
668
687
  'hire:mine': cmdMine,
669
688
  'hire:usage': cmdUsage,
670
689
  'hire:habit': cmdHabit,
@@ -7,6 +7,7 @@
7
7
  import { renderWbRules, boundaryLines, identityText } from '../wb-rules-text.js';
8
8
  import { pickLang } from '../model-pledge.js';
9
9
  import { hasAlertFor } from '../mt/format-check.js';
10
+ import { wakeLabelLine, WAKE_LABEL_RE } from '../mt/wake-attribution.js';
10
11
 
11
12
  const REWAKE_LINE = {
12
13
  zh: '刚才叫过你一次,还没看到你读消息。',
@@ -89,6 +90,11 @@ export function buildPrompt(payload, env = process.env, identity = null, job = n
89
90
  : (pf ? `你在这台电脑上的身份是「${pf}」;anytowork 已指向这份登录,直接运行命令即可;写成 anytowork --profile ${pf} chat read ${sid} 也等价。`
90
91
  : `你在这台电脑上的身份放在 ${identity.dir}(已设好 ANYTOWORK_CONFIG_DIR=${identity.dir}),命令直接运行,不用加 --profile。`));
91
92
  }
93
+ // v0.38.39: the wake-up number, ONE fixed line at the very end, the same for every program. Usage is matched to this wake-up by it.
94
+ const label = typeof p.wake_label === 'string' && p.wake_label.trim() ? p.wake_label.trim() : (typeof p.wake_id === 'string' && /^[0-9a-f-]{36}$/i.test(p.wake_id) ? wakeLabelLine(p.wake_id) : '');
95
+ WAKE_LABEL_RE.lastIndex = 0;
96
+ if (label && WAKE_LABEL_RE.test(label)) lines.push(label);
97
+ WAKE_LABEL_RE.lastIndex = 0;
92
98
  return lines.join('\n');
93
99
  }
94
100
 
@@ -258,9 +258,7 @@ export class Listener {
258
258
  const p = job.payload || {};
259
259
  const taskId = isSafeId(String(p.task_id || '')) ? String(p.task_id) : '';
260
260
  if (!job.hireId && !taskId) return null;
261
- const dirs = [this.cfg.cwd || process.cwd()];
262
- if (jobInfo && jobInfo.path) dirs.push(jobInfo.path);
263
- return this.usage.begin({ sid: job.sid, wakeId: job.wakeId, hireId: job.hireId, taskId, command, dirs, startMs: this.nowMs(), wakeIds: job.wakeIds });
261
+ return this.usage.begin({ sid: job.sid, wakeId: job.wakeId, command, startMs: this.nowMs(), wakeIds: job.wakeIds });
264
262
  } catch {
265
263
  return null;
266
264
  }
package/src/mt/dsh.js CHANGED
@@ -14,6 +14,7 @@
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import zlib from 'node:zlib';
17
+ import { labelsOf } from './wake-attribution.js';
17
18
 
18
19
  const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
19
20
  const MAX_FRAME_BYTES = 32 * 1024 * 1024; // one decoded frame is never larger than this
@@ -119,8 +120,20 @@ function applyEvent(st, o) {
119
120
  const cwd = typeof o.cwd === 'string' ? o.cwd : d.cwd;
120
121
  if (sid) st.sid = String(sid);
121
122
  if (typeof cwd === 'string') st.cwd = cwd;
123
+ if (typeof o.parentSession === 'string' && o.parentSession) st.parent = o.parentSession; // a sub-agent session
122
124
  return;
123
125
  }
126
+ // outside messages (source.kind = user; the other kinds are the program's own notes) and the end of an answer
127
+ if (o.type === 'user/message') {
128
+ const src = d.source && typeof d.source === 'object' ? d.source : null;
129
+ const t = Number(o.time);
130
+ if (src && src.kind === 'user' && Number.isFinite(t) && t > 0) {
131
+ const text = Array.isArray(d.content) ? d.content.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('\n') : String(d.content || '');
132
+ st.inputs.set(`${o.seq}`, { ms: t, labels: labelsOf(text) });
133
+ }
134
+ return;
135
+ }
136
+ if (o.type === 'turn/end') { const t = Number(o.time); if (Number.isFinite(t) && t > 0) st.turnEnds.add(t); return; }
124
137
  if (o.type !== 'assistant/message') return;
125
138
  const u = d.usage;
126
139
  const m = d.message && typeof d.message === 'object' ? d.message : null;
@@ -147,17 +160,17 @@ function applyEvent(st, o) {
147
160
  /** The calls of one session log file (all of them; the caller filters by time). Never throws. */
148
161
  export function readDshFile(file) {
149
162
  let buf;
150
- try { buf = fs.readFileSync(file); } catch { return { calls: [], cwd: null }; }
163
+ try { buf = fs.readFileSync(file); } catch { return { calls: [], cwd: null, sid: null, parent: null, inputs: [], turnEnds: [] }; }
151
164
  let st = cache.get(file);
152
165
  const head = buf.subarray(0, 48).toString('hex'); // a file replaced by another one is not mistaken for the same one
153
- 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)) };
166
+ if (!st || buf.length < st.size || st.head !== head) st = { head, size: 0, offset: 0, sid: null, cwd: null, calls: new Map(), inputs: new Map(), turnEnds: new Set(), parent: null, dir: path.basename(path.dirname(file)) };
154
167
  const { events, end } = decodeFrames(buf, st.offset);
155
168
  for (const o of events) applyEvent(st, o);
156
169
  st.offset = end;
157
170
  st.size = buf.length;
158
171
  if (cache.size >= CACHE_MAX) cache.clear();
159
172
  cache.set(file, st);
160
- return { calls: [...st.calls.values()].map((c) => ({ ...c, cwd: st.cwd })), cwd: st.cwd };
173
+ return { calls: [...st.calls.values()].map((c) => ({ ...c, cwd: st.cwd })), cwd: st.cwd, sid: st.sid || st.dir, parent: st.parent, inputs: [...st.inputs.values()], turnEnds: [...st.turnEnds] };
161
174
  }
162
175
 
163
176
  /**
@@ -167,11 +180,14 @@ export function readDshFile(file) {
167
180
  export function readDshCalls(roots, sinceMs) {
168
181
  const files = roots.flatMap((r) => listDshFiles(r, sinceMs));
169
182
  const found = roots.some((r) => { try { return fs.existsSync(r); } catch { return false; } });
170
- if (!files.length) return { found, files: 0, oldNode: false, calls: [] };
171
- if (!zstdSupported()) return { found, files: files.length, oldNode: true, calls: [] };
183
+ if (!files.length) return { found, files: 0, oldNode: false, calls: [], sessions: [] };
184
+ if (!zstdSupported()) return { found, files: files.length, oldNode: true, calls: [], sessions: [] };
172
185
  const byId = new Map();
186
+ const sessions = [];
173
187
  for (const f of files) {
174
- for (const c of readDshFile(f).calls) if (c.atMs >= sinceMs) byId.set(`${c.session_id}|${c.call_id}`, c);
188
+ const one = readDshFile(f);
189
+ sessions.push({ sid: one.sid, parent: one.parent, inputs: one.inputs, turnEnds: one.turnEnds });
190
+ for (const c of one.calls) if (c.atMs >= sinceMs) byId.set(`${c.session_id}|${c.call_id}`, c);
175
191
  }
176
- return { found, files: files.length, oldNode: false, calls: [...byId.values()] };
192
+ return { found, files: files.length, oldNode: false, calls: [...byId.values()], sessions };
177
193
  }
package/src/mt/inrun.js CHANGED
@@ -1,36 +1,36 @@
1
- // v0.37.7 (segment 4, C2 to C4): usage of the runs the always-on listener starts, read from this computer's own logs
2
- // WHILE the Agent runs and once more when it ends. The listener notes, for every run it starts: the session, the wake-up,
3
- // the hire / task, the start and end time and the folders. From that this module picks the calls that belong to the run
4
- // and sends them with a `task_ref`; nothing is asked of the Agent and no model is called.
1
+ // v0.37.7 (segment 4, C2 to C4), rebuilt in v0.38.39: usage of the runs the always-on listener starts, read from this computer's own
2
+ // logs WHILE the Agent runs and once more when it ends.
5
3
  //
6
- // Rows (`anytowork.usage.v2`, contract section 3.1 of the segment-4 plan):
7
- // - Claude Code / Codex logs: one row per call (granularity call), only calls of the run's folders in the run's time window;
8
- // - session database: one CUMULATIVE row per session x model (kind cumulative): the platform keeps the biggest value it saw and
9
- // adds only the difference, so sending the same totals again, or from another computer, never counts twice;
10
- // - run-log database: one row per run (granularity call), only runs of the session key named in the start command.
11
- // `attribution` is `run` (this run's time window + folders / session) or `window` (another run was going on at the same
12
- // time, so the owner of the call is not certain: shown on the platform, not priced).
13
- // Nothing here reads or sends prompts, answers or file contents; only numbers, model names, times and ids.
4
+ // Which calls belong to which wake-up is decided by the wake-up number the prompt carries (one fixed line at its end), never by
5
+ // folder or time window: every reader returns the same list of events and `attributeEvents` (wake-attribution.js) is the only place
6
+ // that cuts it into turns. This module only takes the calls of the wake-ups its runs answer and sends them.
7
+ //
8
+ // Rows (`anytowork.usage.v2`):
9
+ // - logs and transcripts that keep every call: one row per call (granularity call);
10
+ // - session database: one CUMULATIVE row per session x model (the platform keeps the biggest value it saw);
11
+ // - run-log database totals: one row per run, always `window` (shown, not priced: the log has no outside messages to read a number from).
12
+ // `attribution`: `run` (turn of one number: priced) or `window` (could not be told apart: shown, not priced).
13
+ // Each row carries `task_ref {wake_id, session_id, basis: 'wake_label', segment}`; the platform finds the hire from the wake-up itself.
14
+ // Nothing here sends prompts, answers or file contents; only numbers, model names, times and ids.
14
15
 
15
16
  import os from 'node:os';
16
17
  import path from 'node:path';
17
18
  import { readMsgLog, readRollout, readDshLog, readSessionModelUsage, readRunLog, readTranscriptUsage, guessProvider } from './readers.js';
18
19
  import { readState, writeState, sendRows, sha256, isZero, localKey } from './collect.js';
19
20
  import { readRegistry, workdirForPath } from './workdirs.js';
21
+ import { attributeEvents } from './wake-attribution.js';
20
22
 
21
23
  export const SCHEMA_V2 = 'anytowork.usage.v2';
22
24
  export const INRUN_DEFAULT_SEC = 60; // MT_INRUN_UPLOAD_SEC default (the platform sends `inrun_upload_sec` in listener.limits)
23
25
  const START_SLACK_MS = 5000; // a session / log line may be stamped a little before the start we noted
24
- const FINISH_GRACE_MS = 15_000; // and a little after the end
25
26
  const SETTLE_MS = 60_000; // a call seen less than this long ago may still be streaming into the log
26
- const KEEP_FINISHED_MS = 10 * 60 * 1000; // finished runs stay known this long (to tell who owns what in a crowd)
27
+ const KEEP_FINISHED_MS = 10 * 60 * 1000; // finished runs stay known this long
27
28
 
28
- /** The task a run belongs to: the session, the wake-up and the hire or task (ids the platform sent and the listener checked). */
29
- export function buildTaskRef({ sid, wakeId, hireId, taskId, wakeIds }) {
29
+ /** The reference a row carries: the wake-up number found in the prompt (the platform derives the hire / task from it). */
30
+ export function buildTaskRef({ sid, wakeId, segment, basis, wakeIds }) {
30
31
  const ref = { session_id: sid, wake_id: wakeId || '' };
31
- if (hireId) ref.hire_id = hireId; else if (taskId) ref.task_id = taskId;
32
- // v0.38.9: every wake-up this run answers (a merged job has several). The platform looks up which instructions each
33
- // wake-up covers; the Agent never names instruction ids itself.
32
+ if (basis) ref.basis = basis;
33
+ if (segment) ref.segment = segment;
34
34
  const ids = [...new Set((wakeIds || []).map(String).filter((x) => /^[0-9a-f-]{36}$/i.test(x)))].slice(-10);
35
35
  if (ids.length > 1) ref.wake_ids = ids;
36
36
  return ref;
@@ -55,30 +55,6 @@ export function inrunSettings(cfg, state, env = process.env) {
55
55
 
56
56
  function norm(p) { try { return path.resolve(String(p)); } catch { return null; } }
57
57
 
58
- /** A log folder belongs to a run when it is one of the run's folders or inside one (never inside the root or home folder). */
59
- function dirMatches(cwd, dirs, home, exactOnly = false) {
60
- const c = norm(cwd);
61
- if (!c) return false;
62
- for (const d of dirs) {
63
- if (c === d) return true;
64
- if (exactOnly || d === path.parse(d).root || d === home) continue;
65
- if (c.startsWith(d + path.sep)) return true;
66
- }
67
- return false;
68
- }
69
-
70
- /**
71
- * v0.38.36: folders that say nothing about which project a call belongs to: no folder at all, the home folder (and the one
72
- * above it), the root, the temp folders. A call from there is placed by the Agent's on-duty time window instead.
73
- */
74
- function unclearDir(cwd, home) {
75
- if (!cwd) return true;
76
- const c = norm(cwd);
77
- if (!c) return true;
78
- const vague = new Set([path.parse(c).root, norm(home), norm(path.dirname(home)), norm(os.tmpdir()), '/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp']);
79
- return vague.has(c);
80
- }
81
-
82
58
  /** The program a start command names (first word of a path or `exec`), or null when it is a wrapper we cannot tell. */
83
59
  export function programOfCommand(command) {
84
60
  const words = String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
@@ -93,13 +69,6 @@ export function programOfCommand(command) {
93
69
  return null;
94
70
  }
95
71
 
96
- function shareDir(a, b) { return a.dirs.some((d) => b.dirs.includes(d)); }
97
- function timeOverlap(a, b, now) {
98
- const aEnd = a.endMs == null ? now : a.endMs + FINISH_GRACE_MS;
99
- const bEnd = b.endMs == null ? now : b.endMs + FINISH_GRACE_MS;
100
- return a.startMs - START_SLACK_MS <= bEnd && b.startMs - START_SLACK_MS <= aEnd;
101
- }
102
-
103
72
  function callRow(c, ctx) {
104
73
  const row = {
105
74
  schema: SCHEMA_V2,
@@ -148,16 +117,16 @@ export class RunUsageTracker {
148
117
  this.chain = Promise.resolve(); // uploads one after another: they share one local state file
149
118
  }
150
119
 
151
- /** A run starts. `dirs`: the folders the Agent works in (the listener's cwd, the hire work folder). */
152
- begin({ sid, wakeId, hireId, taskId, command, dirs, startMs, wakeIds }) {
120
+ /** A run starts. `wakeIds`: every wake-up this run answers (a merged job has several). Folders are no longer used to tell runs apart. */
121
+ begin({ sid, wakeId, command, startMs, wakeIds }) {
153
122
  const now = this.nowMs();
154
123
  this.runs = this.runs.filter((x) => x.endMs == null || now - x.endMs < KEEP_FINISHED_MS);
124
+ const ids = new Set([...(wakeIds || []), wakeId].filter(Boolean).map((x) => String(x).toLowerCase()));
155
125
  const r = {
156
126
  seq: (this.seq += 1), sid, startMs: startMs != null ? startMs : now, endMs: null,
157
- taskRef: buildTaskRef({ sid, wakeId, hireId, taskId, wakeIds }),
158
- dirs: [...new Set((dirs || []).map(norm).filter(Boolean))],
127
+ wakeIds: ids,
159
128
  tokens: String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter((t) => t.length >= 4 && !t.startsWith('-') && /[:_-]/.test(t)),
160
- prog: programOfCommand(command), // v0.38.8: a run of one program never takes another program's sessions
129
+ prog: programOfCommand(command),
161
130
  cum: new Map(), // `session|model` -> totals already sent
162
131
  sentAny: false,
163
132
  };
@@ -165,7 +134,7 @@ export class RunUsageTracker {
165
134
  return r;
166
135
  }
167
136
 
168
- /** Queue one upload of what the run has so far (`final`: the run ended, no settle time, a short grace after the end). */
137
+ /** Queue one upload of what the run has so far (`final`: the run ended, no settle time). */
169
138
  upload(r, { final = false } = {}) {
170
139
  const next = this.chain.then(() => this.#upload(r, final)).catch(() => null);
171
140
  this.chain = next;
@@ -178,155 +147,82 @@ export class RunUsageTracker {
178
147
  return this.upload(r, { final: true });
179
148
  }
180
149
 
181
- peers(r, now) {
182
- return this.runs.filter((x) => x !== r && shareDir(x, r) && timeOverlap(x, r, now));
183
- }
184
-
185
- /**
186
- * Which run owns a session of the session database. The only run whose time fits owns it (sure). When several runs of one folder go on
187
- * at the same time, the sessions of that folder are handed out in the order the runs started (not sure: `window`).
188
- * `ordered`: the sessions of the folders of this crowd, by start time.
189
- */
190
- #hermesOwner(s, r, now, ordered) {
191
- // v0.38.36: a session with no clear folder is owned by the runs of this program that were on duty when it started
192
- const group = unclearDir(s.cwd, this.home) ? this.#onDuty('hermes', s.startedMs)
193
- : [r, ...this.peers(r, now)].sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
194
- const fits = group.filter((x) => s.startedMs >= x.startMs - START_SLACK_MS && (x.endMs == null || s.startedMs <= x.endMs + FINISH_GRACE_MS));
195
- if (!fits.length) return { owner: null, sure: false };
196
- if (fits.length === 1) return { owner: fits[0], sure: true };
197
- const rank = Math.max(0, ordered.findIndex((x) => x.id === s.id));
198
- return { owner: fits[Math.min(rank, fits.length - 1)], sure: false };
199
- }
200
-
201
- /** Runs of one program that were on duty at `ms`, in start order: the possible owners of a call with no clear folder. */
202
- #onDuty(program, ms) {
203
- return this.runs
204
- .filter((x) => x.prog === program && ms >= x.startMs - START_SLACK_MS && (x.endMs == null || ms <= x.endMs + FINISH_GRACE_MS))
205
- .sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
206
- }
207
-
208
150
  async #upload(r, final) {
209
- if (this.off) return null;
151
+ if (this.off || !r.wakeIds.size) return null;
210
152
  const now = this.nowMs();
211
153
  const since = r.startMs - START_SLACK_MS;
212
- const until = final ? (r.endMs != null ? r.endMs : now) + FINISH_GRACE_MS : now;
213
154
  const settleMs = final ? 0 : SETTLE_MS;
214
- const env = this.env;
215
- const home = this.home;
155
+ const { home, env } = this;
216
156
  const state = readState(this.credOpts);
217
157
  const registry = (() => { try { return readRegistry(this.credOpts); } catch { return {}; } })();
218
158
  const wdCache = new Map();
219
159
  const workdirOf = (cwd) => { try { const w = workdirForPath(cwd, registry, wdCache); return w ? w.workdir_id : null; } catch { return null; } };
220
- const crowd = this.peers(r, now).length > 0;
221
160
  const rows = [];
222
161
  const pendingCum = [];
223
162
  const heldSessions = [];
224
- const dropped = {}; // v0.38.36: calls read inside the window but not taken, by reason
225
- const drop = (k) => { dropped[k] = (dropped[k] || 0) + 1; };
226
163
 
227
- // session database: totals per session x model
228
- try {
229
- if (r.prog && r.prog !== 'hermes') throw new Error('the run is of another program');
230
- const hs = await readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log });
231
- const crowdDirs = [...new Set([r, ...this.peers(r, now)].flatMap((x) => x.dirs))];
232
- const crowdStart = Math.min(r.startMs, ...this.peers(r, now).map((x) => x.startMs)) - START_SLACK_MS;
233
- const ordered = hs.sessions
234
- .filter((s) => s.source !== 'cron' && s.startedMs >= crowdStart
235
- && (s.cwd && !unclearDir(s.cwd, home) ? dirMatches(s.cwd, crowdDirs, home, true) : r.prog === 'hermes'))
236
- .sort((a, b) => a.startedMs - b.startedMs);
237
- for (const s of hs.sessions) {
238
- if (s.source !== 'cron' && s.cwd && !unclearDir(s.cwd, home) && !dirMatches(s.cwd, crowdDirs, home, true) && s.startedMs >= since && s.startedMs <= until) drop('other_dir');
239
- }
240
- for (const s of ordered) {
241
- if (s.startedMs < since || s.startedMs > until) continue;
242
- const { owner, sure } = this.#hermesOwner(s, r, now, ordered);
243
- if (owner !== r) continue;
244
- heldSessions.push(s.id);
245
- for (const m of s.models) {
246
- const sig = `${s.id}|${m.model}`;
164
+ // 1. every reader gives the same event list; one shared function cuts it into turns
165
+ const events = [];
166
+ const tag = (read, program, reader) => {
167
+ try {
168
+ const out = read();
169
+ return Promise.resolve(out).then((o) => { for (const c of o.calls || []) c.__src = { program, reader }; for (const s of o.sessions || []) s.__src = { program: 'hermes', reader: 'cli:session_model_usage' }; events.push(...(o.events || [])); return o; }).catch(() => null);
170
+ } catch { return Promise.resolve(null); }
171
+ };
172
+ await Promise.all([
173
+ tag(() => readMsgLog({ home, env, sinceMs: since, log: this.log }), 'claude_code', 'cli:msg_log'),
174
+ tag(() => readRollout({ home, env, sinceMs: since, log: this.log }), 'codex', 'cli:rollout'),
175
+ tag(() => readDshLog({ home, env, sinceMs: since, log: this.log }), 'dsh', 'cli:dsh_log'),
176
+ tag(() => readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log }), 'hermes', 'cli:session_model_usage'),
177
+ tag(() => readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log }), 'openclaw', 'cli:transcript_db'),
178
+ ]);
179
+ const { rows: owned, dropped } = attributeEvents(events);
180
+ for (const o of owned) {
181
+ if (!r.wakeIds.has(o.wakeId)) continue;
182
+ const c = o.call;
183
+ const src = c.__src || {};
184
+ const taskRef = buildTaskRef({ sid: r.sid, wakeId: o.wakeId, segment: o.segment, basis: 'wake_label', wakeIds: [...r.wakeIds] });
185
+ if (c.models) {
186
+ // session database: one total per session x model, taken whole
187
+ if (c.startedMs < since) continue;
188
+ heldSessions.push(c.id);
189
+ for (const m of c.models) {
190
+ const sig = `${c.id}|${m.model}`;
247
191
  const totals = `${m.input_tokens}|${m.output_tokens}|${m.cache_write_tokens}|${m.cache_read_tokens}|${m.reasoning_tokens}`;
248
192
  if (r.cum.get(sig) === totals) continue;
249
193
  const row = {
250
194
  schema: SCHEMA_V2, kind: 'cumulative', granularity: 'cumulative',
251
- source_session_key: s.id, conversation_id: s.id,
195
+ source_session_key: c.id, conversation_id: c.id,
252
196
  provider: guessProvider(m.model), model: m.model.slice(0, 120),
253
- started_at: isoSec(s.startedMs), ended_at: isoSec(s.lastSeenMs || s.startedMs),
197
+ started_at: isoSec(c.startedMs), ended_at: isoSec(c.lastSeenMs || c.startedMs),
254
198
  input_tokens: m.input_tokens, output_tokens: m.output_tokens, cache_write_tokens: m.cache_write_tokens, cache_read_tokens: m.cache_read_tokens,
255
199
  reasoning_tokens: m.reasoning_tokens,
256
- program: 'hermes', reader: 'cli:session_model_usage', attribution: sure ? 'run' : 'window',
257
- task_ref: r.taskRef, source: 'local-log',
200
+ program: 'hermes', reader: 'cli:session_model_usage', attribution: o.attribution,
201
+ task_ref: taskRef, source: 'local-log',
258
202
  };
259
203
  if (isZero(row)) continue;
260
204
  rows.push(row);
261
205
  pendingCum.push([sig, totals]);
262
206
  }
207
+ continue;
263
208
  }
264
- } catch { /* unreadable: the next round tries again */ }
265
-
266
- // Claude Code / Codex: calls of the run's folders in the run's time window
267
- const attributionOfCalls = crowd ? 'window' : 'run';
268
- const fromJsonl = [
269
- { program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since, log: this.log }) },
270
- { program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since, log: this.log }) },
271
- { program: 'dsh', reader: 'cli:dsh_log', read: () => readDshLog({ home, env, sinceMs: since, log: this.log }) },
272
- ];
273
- for (const src of fromJsonl) {
274
- if (r.prog && r.prog !== src.program) continue;
275
- try {
276
- const inWin = src.read().calls.filter((c) => c.seenMs >= since && c.seenMs <= until && c.seenMs <= now - settleMs);
277
- // v0.38.36: the folder of a call only adds or excludes. A clear folder of this run takes it, a clear folder of another
278
- // project drops it; no / home / temp folder: the run of this program that was on duty at that moment owns it (several:
279
- // handed out by session in start order, `window`; the ones left over stay unassigned and are counted, never taken by a guess).
280
- const vagueConvs = [];
281
- for (const c of inWin) if (unclearDir(c.cwd, home) && !vagueConvs.includes(c.conversation_id)) vagueConvs.push(c.conversation_id);
282
- for (const c of inWin) {
283
- let attribution = attributionOfCalls;
284
- if (c.cwd && dirMatches(c.cwd, r.dirs, home)) {
285
- // clear folder of this run
286
- } else if (!unclearDir(c.cwd, home)) {
287
- drop('other_dir');
288
- continue;
289
- } else if (r.prog !== src.program) {
290
- drop('unknown_program');
291
- continue;
292
- } else {
293
- const duty = this.#onDuty(src.program, c.seenMs);
294
- if (!duty.includes(r)) continue;
295
- attribution = 'run';
296
- if (duty.length > 1) {
297
- const rank = vagueConvs.indexOf(c.conversation_id);
298
- if (rank >= duty.length) { if (duty[0] === r) drop('crowd'); continue; }
299
- if (duty[rank] !== r) continue;
300
- attribution = 'window';
301
- }
302
- }
303
- rows.push(callRow(c, { program: src.program, reader: src.reader, attribution, taskRef: r.taskRef, workdirId: workdirOf(c.cwd) }));
304
- }
305
- } catch { /* one unreadable log never blocks the others */ }
209
+ if (c.seenMs < since || c.seenMs > now - settleMs) continue;
210
+ rows.push(callRow(c, { program: src.program, reader: src.reader, attribution: o.attribution, taskRef, workdirId: workdirOf(c.cwd) }));
306
211
  }
307
212
 
308
- // run-log database: runs of the session key the start command names
213
+ // 2. run-log database totals of the session key the start command names: no outside messages in it, so shown only
309
214
  if (r.tokens.length && (!r.prog || r.prog === 'openclaw')) {
310
215
  const mine = (c) => {
311
216
  const key = c.session_key || '';
312
217
  return r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
313
218
  };
314
- // v0.38.8: every assistant message of the session, as it happens (the run log only has the total at the very end)
315
- const live = new Set();
316
- try {
317
- const tr = await readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log });
318
- for (const c of tr.calls) {
319
- if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
320
- live.add(c.session_id);
321
- rows.push(callRow(c, { program: 'openclaw', reader: 'cli:transcript_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
322
- }
323
- } catch { /* same */ }
219
+ const live = new Set(owned.filter((o) => o.call.__src && o.call.__src.reader === 'cli:transcript_db').map((o) => o.call.session_id));
324
220
  try {
325
221
  const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log, verdictKnown: true });
326
222
  for (const c of oc.calls) {
327
- if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
328
- 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
329
- rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
223
+ if (c.seenMs < since || c.seenMs > now - settleMs || !mine(c)) continue;
224
+ if (live.has(c.session_id) || (state.perCallReported || {})[c.session_id]) continue; // the session already has its calls one by one
225
+ rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution: 'window', taskRef: buildTaskRef({ sid: r.sid, wakeId: [...r.wakeIds][0], basis: 'session_key' }) }));
330
226
  }
331
227
  } catch { /* same */ }
332
228
  }
@@ -371,4 +267,3 @@ export class RunUsageTracker {
371
267
  function markSummariesSent(state, sessionIds) {
372
268
  for (const id of sessionIds) state.sent[`s:s-${sha256(String(id)).slice(0, 32)}`] = Date.now();
373
269
  }
374
-
package/src/mt/readers.js CHANGED
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import { createHash } from 'node:crypto';
24
24
  import zlib from 'node:zlib';
25
25
  import { dshRoots, readDshCalls } from './dsh.js';
26
+ import { labelsOf } from './wake-attribution.js';
26
27
  import { mayRead, formatAlerts, msgLogProblem, rolloutProblem, sessionDbProblem, openClawProblem } from './format-check.js';
27
28
 
28
29
  const MAX_DEPTH = 6;
@@ -50,6 +51,13 @@ function int(v) {
50
51
  return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
51
52
  }
52
53
 
54
+ /** Milliseconds of a log time exactly (the `iso` helper below cuts to whole seconds). */
55
+ function exactMs(v) {
56
+ if (typeof v === 'number') return Number.isFinite(v) ? (v < 1e12 ? v * 1000 : v) : null;
57
+ const t = Date.parse(String(v));
58
+ return Number.isNaN(t) ? null : t;
59
+ }
60
+
53
61
  function iso(v) {
54
62
  if (v == null || v === '') return null;
55
63
  const d = typeof v === 'number' ? new Date(v < 1e12 ? v * 1000 : v) : new Date(String(v));
@@ -92,6 +100,22 @@ function mergeInto(map, row) {
92
100
  const end = row.ended_at || row.started_at;
93
101
  if (end && end > (old.ended_at || old.started_at)) old.ended_at = end;
94
102
  old.seenMs = Math.max(old.seenMs, row.seenMs);
103
+ if (row.atMs != null) old.atMs = old.atMs != null ? Math.min(old.atMs, row.atMs) : row.atMs;
104
+ }
105
+
106
+ // ---------------------------------------------------------------- unified events (see wake-attribution.js)
107
+ // Every reader below returns `events` next to `calls`: only WHAT HAPPENED in the log (an outside message came in, an answer
108
+ // ended, a sub-agent belongs to a session, a model call was made). Which wake-up a call belongs to is decided in one place
109
+ // (wake-attribution.js), never here. Only the wake-up numbers found in an outside message are copied out of its text.
110
+
111
+ function callEvents(calls, sessionOf) {
112
+ return calls.map((c) => ({ kind: 'call', session: sessionOf(c), ms: c.atMs != null ? c.atMs : (Date.parse(c.started_at) || c.seenMs), call: c }));
113
+ }
114
+
115
+ function textOfBlocks(content) {
116
+ if (typeof content === 'string') return content;
117
+ if (!Array.isArray(content)) return '';
118
+ return content.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('\n');
95
119
  }
96
120
 
97
121
  // ---------------------------------------------------------------- msgLog
@@ -116,20 +140,34 @@ function lastWinsInto(map, key, row) {
116
140
  row.started_at = times[0];
117
141
  row.ended_at = times[times.length - 1] > times[0] ? times[times.length - 1] : null;
118
142
  row.seenMs = Math.max(old.seenMs, row.seenMs);
143
+ if (old.atMs != null && row.atMs != null) row.atMs = Math.min(old.atMs, row.atMs);
119
144
  }
120
145
  map.set(key, row);
121
146
  }
122
147
 
123
148
  export function readMsgLog({ home, env, sinceMs, log }) {
124
149
  const calls = new Map();
150
+ const events = [];
125
151
  let files = 0;
126
152
  const found = msgLogRoots(home, env).map((root) => listJsonl(root, sinceMs));
127
153
  // v0.38.10: a log whose layout does not match is not read (the Agent is told to report its usage itself)
128
- if (!mayRead('msg_log', () => msgLogProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0 };
154
+ if (!mayRead('msg_log', () => msgLogProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0, events: [] };
129
155
  for (const list of found) {
130
156
  for (const file of list) {
131
157
  files += 1;
158
+ const linked = new Set();
132
159
  eachJsonLine(file, (o) => {
160
+ // sub-agent files live in <session>/subagents/ and may carry their own session id: they follow the folder's session
161
+ if (o.sessionId && !linked.has(o.sessionId) && /[\\/]subagents[\\/]/.test(file)) {
162
+ linked.add(o.sessionId);
163
+ const parent = path.basename(path.dirname(path.dirname(file)));
164
+ if (parent !== String(o.sessionId)) events.push({ kind: 'link', session: String(o.sessionId), parent });
165
+ }
166
+ if (o.type === 'user') { if (!/[\\/]subagents[\\/]/.test(file)) claudeInput(o, events); return; }
167
+ if (o.type === 'assistant' && o.sessionId && o.message && o.message.stop_reason === 'end_turn' && !o.isSidechain) {
168
+ const t = Date.parse(o.timestamp);
169
+ if (Number.isFinite(t)) events.push({ kind: 'turn_end', session: String(o.sessionId), ms: t });
170
+ }
133
171
  if (o.type !== 'assistant' || !o.message || typeof o.message !== 'object') return;
134
172
  const m = o.message;
135
173
  const u = m.usage;
@@ -146,6 +184,7 @@ export function readMsgLog({ home, env, sinceMs, log }) {
146
184
  provider: guessProvider(m.model),
147
185
  model: String(m.model),
148
186
  started_at: at,
187
+ atMs: Date.parse(o.timestamp),
149
188
  ended_at: null,
150
189
  input_tokens: int(u.input_tokens),
151
190
  output_tokens: int(u.output_tokens),
@@ -157,7 +196,19 @@ export function readMsgLog({ home, env, sinceMs, log }) {
157
196
  });
158
197
  }
159
198
  }
160
- return { calls: [...calls.values()], summaries: [], files };
199
+ const list = [...calls.values()];
200
+ return { calls: list, summaries: [], files, events: [...events, ...callEvents(list, (c) => c.conversation_id)] };
201
+ }
202
+
203
+ /** An outside message of a Claude Code log: not a tool result, not a program-made note, not a compaction summary, not a sub-agent's task. */
204
+ function claudeInput(o, events) {
205
+ if (!o.sessionId || o.isMeta || o.isCompactSummary || o.isSidechain || o.toolUseResult !== undefined) return;
206
+ const m = o.message;
207
+ if (!m || m.role !== 'user') return;
208
+ const t = Date.parse(o.timestamp);
209
+ if (!Number.isFinite(t)) return;
210
+ if (Array.isArray(m.content) && m.content.some((b) => b && b.type === 'tool_result')) return;
211
+ events.push({ kind: 'input', session: String(o.sessionId), ms: t, labels: labelsOf(textOfBlocks(m.content)) });
161
212
  }
162
213
 
163
214
  // ---------------------------------------------------------------- rollout
@@ -169,11 +220,14 @@ function rolloutRoots(home, env) {
169
220
  return [...new Set(roots)];
170
221
  }
171
222
 
223
+ const CODEX_SYSTEM_TEXT = /^\s*(<environment_context>|<user_instructions>|<INSTRUCTIONS>|<permissions|# AGENTS\.md)/;
224
+
172
225
  export function readRollout({ home, env, sinceMs, log }) {
173
226
  const calls = new Map();
227
+ const events = [];
174
228
  let files = 0;
175
229
  const found = rolloutRoots(home, env).map((root) => listJsonl(root, sinceMs, (n) => n.startsWith('rollout-')));
176
- if (!mayRead('rollout', () => rolloutProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0 };
230
+ if (!mayRead('rollout', () => rolloutProblem(found.flat()), { env, log })) return { calls: [], summaries: [], files: 0, events: [] };
177
231
  for (const list of found) {
178
232
  for (const file of list) {
179
233
  files += 1;
@@ -181,8 +235,23 @@ export function readRollout({ home, env, sinceMs, log }) {
181
235
  let cwd = null;
182
236
  let provider = null;
183
237
  let model = null;
238
+ const key = `rollout:${path.basename(file)}`; // one session per file, whatever session ids the file names inside
239
+ let lastIn = null;
184
240
  eachJsonLine(file, (o) => {
185
241
  const p = o.payload && typeof o.payload === 'object' ? o.payload : {};
242
+ const t = Date.parse(o.timestamp);
243
+ // the same message is written twice (response item and event); the second copy is dropped
244
+ const outside = (text) => {
245
+ if (!Number.isFinite(t) || CODEX_SYSTEM_TEXT.test(text)) return;
246
+ const labels = labelsOf(text);
247
+ const sig = `${text.length}|${labels.join(',')}|${text.slice(0, 120)}`;
248
+ if (lastIn && lastIn.sig === sig && Math.abs(lastIn.t - t) <= 10_000) return;
249
+ lastIn = { sig, t };
250
+ events.push({ kind: 'input', session: key, ms: t, labels });
251
+ };
252
+ if (o.type === 'response_item' && p.type === 'message' && p.role === 'user') { outside(textOfBlocks(p.content)); return; }
253
+ if (o.type === 'event_msg' && p.type === 'user_message') { outside(typeof p.message === 'string' ? p.message : ''); return; }
254
+ if (o.type === 'event_msg' && (p.type === 'task_complete' || p.type === 'turn_complete') && Number.isFinite(t)) { events.push({ kind: 'turn_end', session: key, ms: t }); return; }
186
255
  if (o.type === 'session_meta') {
187
256
  sid = p.id || sid;
188
257
  cwd = typeof p.cwd === 'string' ? p.cwd : cwd;
@@ -206,6 +275,8 @@ export function readRollout({ home, env, sinceMs, log }) {
206
275
  // A call id the log does not give: session + running total (stable when the file is read again).
207
276
  const callId = `${sid}:${totalTokens != null ? totalTokens : at}`;
208
277
  mergeInto(calls, {
278
+ attrSession: key,
279
+ atMs: t,
209
280
  call_id: callId,
210
281
  conversation_id: String(sid),
211
282
  provider: String(provider || guessProvider(model)).toLowerCase(),
@@ -222,7 +293,8 @@ export function readRollout({ home, env, sinceMs, log }) {
222
293
  });
223
294
  }
224
295
  }
225
- return { calls: [...calls.values()], summaries: [], files };
296
+ const list = [...calls.values()];
297
+ return { calls: list, summaries: [], files, events: [...events, ...callEvents(list, (c) => c.attrSession)] };
226
298
  }
227
299
 
228
300
  // ---------------------------------------------------------------- dsh (DeepSeek Harness, v0.38.20)
@@ -234,7 +306,8 @@ export function readRollout({ home, env, sinceMs, log }) {
234
306
  */
235
307
  export function readDshLog({ home, env, sinceMs }) {
236
308
  const r = readDshCalls(dshRoots(home, env), sinceMs);
237
- if (r.oldNode) return { calls: [], summaries: [], files: 0, unreadable: r.files };
309
+ if (r.oldNode) return { calls: [], summaries: [], files: 0, unreadable: r.files, events: [] };
310
+ const sess = (x) => String(x).replace(/^session-/, '');
238
311
  const calls = r.calls.filter((c) => c.model).map((c) => ({
239
312
  call_id: c.call_id,
240
313
  conversation_id: c.session_id,
@@ -248,8 +321,16 @@ export function readDshLog({ home, env, sinceMs }) {
248
321
  cache_read_tokens: c.cache_read_tokens,
249
322
  cwd: c.cwd,
250
323
  seenMs: c.atMs,
324
+ atMs: c.atMs,
251
325
  }));
252
- return { calls, summaries: [], files: r.files };
326
+ const events = [];
327
+ for (const s of r.sessions || []) {
328
+ const id = sess(s.sid);
329
+ if (s.parent) events.push({ kind: 'link', session: id, parent: sess(s.parent) });
330
+ else for (const i of s.inputs) events.push({ kind: 'input', session: id, ms: i.ms, labels: i.labels });
331
+ for (const ms of s.turnEnds) events.push({ kind: 'turn_end', session: id, ms });
332
+ }
333
+ return { calls, summaries: [], files: r.files, events: [...events, ...callEvents(calls, (c) => sess(c.conversation_id))] };
253
334
  }
254
335
 
255
336
  // ---------------------------------------------------------------- sessionDb
@@ -324,11 +405,12 @@ export async function readSessionDb({ home, env, sinceMs, sqlite }) {
324
405
  */
325
406
  export async function readSessionModelUsage({ home, env, sinceMs, sqlite, log }) {
326
407
  const files = sessionDbFiles(home, env);
327
- if (!files.length) return { sessions: [], files: 0 };
408
+ if (!files.length) return { sessions: [], files: 0, events: [] };
328
409
  const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
329
- if (!DatabaseSync) return { sessions: [], files: 0, unreadable: files.length };
330
- if (!mayRead('session_model_usage', () => sessionDbProblem(files, DatabaseSync), { env, log })) return { sessions: [], files: 0 };
410
+ if (!DatabaseSync) return { sessions: [], files: 0, unreadable: files.length, events: [] };
411
+ if (!mayRead('session_model_usage', () => sessionDbProblem(files, DatabaseSync), { env, log })) return { sessions: [], files: 0, events: [] };
331
412
  const sessions = new Map();
413
+ const events = [];
332
414
  for (const f of files) {
333
415
  let db;
334
416
  try {
@@ -358,11 +440,23 @@ export async function readSessionModelUsage({ home, env, sinceMs, sqlite, log })
358
440
  m.cache_write_tokens += int(r.cw);
359
441
  m.reasoning_tokens += int(r.r);
360
442
  }
443
+ // outside messages of those sessions (role user, not a compaction summary); one session = one total, so no per-call times
444
+ for (const s of sessions.values()) {
445
+ if (s.fileKey !== f && s.fileKey !== undefined) continue;
446
+ s.fileKey = f;
447
+ try {
448
+ for (const u of db.prepare("SELECT content, timestamp FROM messages WHERE session_id = ? AND role = 'user' AND COALESCE(_compressed_summary, 0) = 0").all(s.id)) {
449
+ events.push({ kind: 'input', session: s.id, ms: Math.round(Number(u.timestamp) * 1000), labels: labelsOf(u.content) });
450
+ }
451
+ } catch { /* a database without these columns: no numbers, nothing priced */ }
452
+ }
361
453
  } catch { /* a locked or different file: skip it */ } finally {
362
454
  try { if (db) db.close(); } catch { /* ignore */ }
363
455
  }
364
456
  }
365
- return { sessions: [...sessions.values()], files: files.length };
457
+ const list = [...sessions.values()];
458
+ for (const s of list) events.push({ kind: 'call', session: s.id, ms: s.startedMs, whole: true, call: s });
459
+ return { sessions: list, files: files.length, events };
366
460
  }
367
461
 
368
462
  // ---------------------------------------------------------------- run-log database (v0.37.7 C4)
@@ -463,7 +557,7 @@ export async function readRunLog({ home, env, sinceMs, sqlite, log, verdictKnown
463
557
  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
464
558
  FROM transcript_events e LEFT JOIN session_windows w ON w.session_id = e.session_id
465
559
  WHERE e.created_at >= ? AND (e.event_json IS NULL
466
- OR (json_extract(e.event_json, '$.type') = 'message' AND json_extract(e.event_json, '$.message.role') = 'assistant'))
560
+ OR (json_extract(e.event_json, '$.type') = 'message' AND json_extract(e.event_json, '$.message.role') IN ('assistant', 'user')))
467
561
  ORDER BY e.created_at, e.seq`;
468
562
 
469
563
  const TRANSCRIPT_MAX_BYTES = 4 * 1024 * 1024; // the database itself caps one event at 4 MB; anything that expands past it is not read
@@ -479,6 +573,17 @@ function transcriptEvent(r) {
479
573
  } catch { return null; }
480
574
  }
481
575
 
576
+ /** An outside message of the run-log program: role user and no `provenance` (inter-session / system notes carry one). */
577
+ function parseTranscriptInput(r) {
578
+ const ev = transcriptEvent(r);
579
+ const m = ev && ev.type === 'message' ? ev.message : null;
580
+ if (!m || m.role !== 'user' || m.provenance) return null;
581
+ const at = iso(m.timestamp) || iso(ev.timestamp) || iso(r.c);
582
+ const t = at ? (exactMs(m.timestamp) ?? exactMs(ev.timestamp) ?? Date.parse(at)) : NaN;
583
+ if (!Number.isFinite(t)) return null;
584
+ return { kind: 'input', session: String(r.sid), ms: t, labels: labelsOf(textOfBlocks(m.content)) };
585
+ }
586
+
482
587
  function parseTranscriptCall(r) {
483
588
  const ev = transcriptEvent(r);
484
589
  const m = ev && ev.type === 'message' ? ev.message : null;
@@ -497,6 +602,7 @@ function parseTranscriptCall(r) {
497
602
  provider: String(m.provider || guessProvider(m.model)).toLowerCase(),
498
603
  model: String(m.model),
499
604
  started_at: at,
605
+ atMs: exactMs(m.timestamp) ?? exactMs(ev.timestamp) ?? Number(r.c),
500
606
  ended_at: null,
501
607
  seenMs: Date.parse(at),
502
608
  input_tokens: int(u.input),
@@ -517,11 +623,12 @@ function parseTranscriptCall(r) {
517
623
  */
518
624
  export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
519
625
  const files = openClawDbFiles(home, env);
520
- if (!files.length) return { calls: [], files: 0 };
626
+ if (!files.length) return { calls: [], files: 0, events: [] };
521
627
  const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
522
- if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length };
523
- if (!mayRead('openclaw', () => openClawProblem(files, DatabaseSync), { env, log })) return { calls: [], files: 0 };
628
+ if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length, events: [] };
629
+ if (!mayRead('openclaw', () => openClawProblem(files, DatabaseSync), { env, log })) return { calls: [], files: 0, events: [] };
524
630
  const calls = [];
631
+ const events = [];
525
632
  for (const f of files) {
526
633
  let db;
527
634
  try {
@@ -530,19 +637,21 @@ export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
530
637
  if (!have.has('transcript_events') || !have.has('session_windows')) continue;
531
638
  for (const r of db.prepare(TRANSCRIPT_SQL).all(sinceMs)) {
532
639
  const ck = `${f}|${r.sid}:${r.seq}`;
533
- let call = transcriptCache.get(ck);
534
- if (call === undefined) {
535
- call = parseTranscriptCall(r);
640
+ let parsed = transcriptCache.get(ck);
641
+ if (parsed === undefined) {
642
+ const input = parseTranscriptInput(r);
643
+ parsed = { call: input ? null : parseTranscriptCall(r), input };
536
644
  if (transcriptCache.size >= TRANSCRIPT_CACHE_MAX) transcriptCache.clear();
537
- transcriptCache.set(ck, call);
645
+ transcriptCache.set(ck, parsed);
538
646
  }
539
- if (call) calls.push({ ...call, session_key: typeof r.skey === 'string' ? r.skey : null });
647
+ if (parsed.input) events.push(parsed.input);
648
+ if (parsed.call) calls.push({ ...parsed.call, session_key: typeof r.skey === 'string' ? r.skey : null });
540
649
  }
541
650
  } catch { /* a locked or different file: skip it */ } finally {
542
651
  try { if (db) db.close(); } catch { /* ignore */ }
543
652
  }
544
653
  }
545
- return { calls, files: files.length };
654
+ return { calls, files: files.length, events: [...events, ...callEvents(calls, (c) => c.session_id)] };
546
655
  }
547
656
 
548
657
  /**
@@ -0,0 +1,139 @@
1
+ // v0.38.39: ONE program-independent rule set that says which wake-up (hence which hire) a model call belongs to.
2
+ //
3
+ // The wake-up prompt ends with one fixed line carrying the wake-up number (`wakeLabelLine`). Every program's log reader turns its
4
+ // own log into the SAME list of events (below) and hands it to `attributeEvents`. Nothing in this file knows a program.
5
+ //
6
+ // Event list (what a reader produces), one object per event, any order:
7
+ // { kind: 'input', session, ms, text | labels } a message from OUTSIDE the Agent: the person, the platform wake-up, a heartbeat,
8
+ // a background callback. NOT: model replies, tool output, title requests,
9
+ // compaction summaries, system injections, the prompt a parent gave a sub-agent.
10
+ // { kind: 'turn_end', session, ms } (optional) the Agent finished answering; lets us see a message that arrived
11
+ // while it was still working
12
+ // { kind: 'link', session, parent } `session` is a sub-agent of `parent` (follows the parent's turn)
13
+ // { kind: 'call', session, ms, call, whole? } one model call (`call` passes through untouched). `whole: true` = the log only
14
+ // has the total of a whole session
15
+ //
16
+ // HOW TO ADD A PROGRAM: write one reader that returns these events (see `events` of readMsgLog / readRollout / readDshLog /
17
+ // readTranscriptUsage / readSessionModelUsage in readers.js) and list it in inrun.js. No attribution code is written per program.
18
+ // A log that cannot be turned into these events is only shown on the platform, never priced.
19
+ //
20
+ // Rules (all here, once)
21
+ // 1. Only an `input` event can carry a number; nothing else is ever read for one.
22
+ // 2. A turn runs from a numbered input to the next input of any kind: calls in between belong to that number. A later input with
23
+ // no number cuts the turn: calls after it belong to nobody.
24
+ // 3. A sub-agent session follows its parent session's turn at the time of the call.
25
+ // 4. What cannot be split is `window` (shown, never priced): one input with two numbers, another number arriving while the Agent
26
+ // was still working on the previous turn, a whole-session total whose session has more than one number.
27
+ // 5. No number / no input seen -> not taken (counted in `dropped`).
28
+
29
+ import { createHash } from 'node:crypto';
30
+
31
+ export const WAKE_LABEL_RE = /\[aw-wake:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]/gi;
32
+ export const TURN_GAP_MS = 90_000; // readers with no turn_end: an input this soon after the last activity arrived mid-turn
33
+
34
+ /** The one fixed line appended to every wake-up prompt (the same for all programs). */
35
+ export function wakeLabelLine(wakeId) {
36
+ return `[aw-wake:${String(wakeId).toLowerCase()}]`;
37
+ }
38
+
39
+ /** The distinct wake-up numbers named in a text (lower case, first seen first). */
40
+ export function labelsOf(text) {
41
+ const out = [];
42
+ const s = String(text == null ? '' : text);
43
+ WAKE_LABEL_RE.lastIndex = 0;
44
+ for (let m = WAKE_LABEL_RE.exec(s); m; m = WAKE_LABEL_RE.exec(s)) {
45
+ const id = m[1].toLowerCase();
46
+ if (!out.includes(id)) out.push(id);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ function segmentId(session, key) {
52
+ return createHash('sha256').update(`${session}|${key}`).digest('hex').slice(0, 16);
53
+ }
54
+
55
+ function rootOf(links, session) {
56
+ let s = session;
57
+ const seen = new Set();
58
+ while (links.has(s) && !seen.has(s)) { seen.add(s); s = links.get(s); }
59
+ return s;
60
+ }
61
+
62
+ /**
63
+ * @param {object[]} events see the top of this file
64
+ * @param {{turnGapMs?: number}} [opts]
65
+ * @returns {{rows: {call: object, wakeId: string, segment: string, attribution: 'run'|'window', reason?: string}[], dropped: Record<string, number>}}
66
+ */
67
+ export function attributeEvents(events, opts = {}) {
68
+ const gap = opts.turnGapMs != null ? opts.turnGapMs : TURN_GAP_MS;
69
+ const links = new Map();
70
+ const bySession = new Map();
71
+ let order = 0;
72
+ for (const e of events || []) {
73
+ if (!e || typeof e !== 'object') continue;
74
+ if (e.kind === 'link') { if (e.session && e.parent && e.session !== e.parent) links.set(String(e.session), String(e.parent)); continue; }
75
+ if (!['input', 'turn_end', 'call'].includes(e.kind) || e.session == null || !Number.isFinite(Number(e.ms))) continue;
76
+ const item = { ...e, session: String(e.session), ms: Number(e.ms), order: (order += 1) };
77
+ if (!bySession.has(item.session)) bySession.set(item.session, []);
78
+ bySession.get(item.session).push(item);
79
+ }
80
+ const rank = { input: 0, turn_end: 1, call: 2 };
81
+ const sortEv = (a, b) => a.ms - b.ms || rank[a.kind] - rank[b.kind] || a.order - b.order;
82
+
83
+ // inputs and turn ends of top-level sessions only: a sub-agent's own "inputs" are its parent's prompt to it, never external
84
+ const timeline = new Map(); // session -> [{ ms, seg }]
85
+ const wholeLabels = new Map(); // session -> distinct numbers over all its inputs
86
+ for (const [session, list] of bySession) {
87
+ if (links.has(session)) continue;
88
+ list.sort(sortEv);
89
+ const hasTurnEnd = list.some((e) => e.kind === 'turn_end');
90
+ const tl = [];
91
+ const distinct = [];
92
+ let seg = null;
93
+ let open = false;
94
+ let lastActMs = null;
95
+ for (const e of list) {
96
+ if (e.kind === 'turn_end') { open = false; continue; }
97
+ if (e.kind === 'call') { open = true; lastActMs = e.ms; continue; }
98
+ const labels = e.labels ? [...new Set(e.labels.map((x) => String(x).toLowerCase()))] : labelsOf(e.text);
99
+ for (const l of labels) if (!distinct.includes(l)) distinct.push(l);
100
+ const midTurn = hasTurnEnd ? open : (lastActMs != null && e.ms - lastActMs < gap);
101
+ let next;
102
+ if (labels.length === 0) next = { id: segmentId(session, e.ms), wakeId: null, window: false, reason: 'unnumbered_input' };
103
+ else if (labels.length > 1) next = { id: segmentId(session, e.ms), wakeId: labels[0], window: true, reason: 'two_numbers' };
104
+ else if (seg && seg.wakeId === labels[0] && !seg.window && midTurn) next = seg;
105
+ else if (seg && seg.wakeId && midTurn && seg.wakeId !== labels[0]) next = { id: segmentId(session, e.ms), wakeId: labels[0], window: true, reason: 'mid_turn_other_number' };
106
+ else next = { id: segmentId(session, e.ms), wakeId: labels[0], window: false };
107
+ if (next !== seg) tl.push({ ms: e.ms, seg: next });
108
+ seg = next;
109
+ open = true;
110
+ lastActMs = e.ms;
111
+ }
112
+ timeline.set(session, tl);
113
+ wholeLabels.set(session, distinct);
114
+ }
115
+
116
+ const rows = [];
117
+ const dropped = {};
118
+ const drop = (k) => { dropped[k] = (dropped[k] || 0) + 1; };
119
+ for (const [session, list] of bySession) {
120
+ for (const e of list) {
121
+ if (e.kind !== 'call') continue;
122
+ const root = rootOf(links, session);
123
+ const tl = timeline.get(root);
124
+ if (!tl || !tl.length) { drop('no_input'); continue; }
125
+ if (e.whole) {
126
+ const ids = wholeLabels.get(root) || [];
127
+ if (!ids.length) { drop('no_number'); continue; }
128
+ rows.push({ call: e.call, wakeId: ids[0], segment: segmentId(root, 'whole'), attribution: ids.length === 1 ? 'run' : 'window', reason: ids.length === 1 ? undefined : 'two_numbers' });
129
+ continue;
130
+ }
131
+ let cur = null;
132
+ for (const t of tl) { if (t.ms <= e.ms) cur = t.seg; else break; }
133
+ if (!cur) { drop('before_input'); continue; }
134
+ if (!cur.wakeId) { drop('cut_by_unnumbered_input'); continue; }
135
+ rows.push({ call: e.call, wakeId: cur.wakeId, segment: cur.id, attribution: cur.window ? 'window' : 'run', reason: cur.reason });
136
+ }
137
+ }
138
+ return { rows, dropped };
139
+ }