@anytowork/cli 0.12.53 → 0.12.55
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 +1 -1
- package/src/cli-parse.js +1 -1
- package/src/format.js +10 -1
- package/src/hire-commands.js +19 -0
- package/src/listener/hire-wake.js +59 -0
- package/src/listener/prompt.js +6 -0
- package/src/listener/run.js +63 -4
- package/src/mt/dsh.js +23 -7
- package/src/mt/inrun.js +66 -171
- package/src/mt/readers.js +129 -20
- package/src/mt/wake-attribution.js +139 -0
package/package.json
CHANGED
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,15 @@ 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
|
+
p.reminder
|
|
1182
|
+
? `${ind}⏰ 提醒:雇主今天的加量还在等你回复(多付 ${yuan(p.pay_minor)} 元,用量上限加 ${yuan(p.add_minor)} 元)${p.deadline_at ? ',' + p.deadline_at + ' 前不回复就全额退回雇主' : ',快到期了'}`
|
|
1183
|
+
: `${ind}➕ 雇主今天给这条聘用加量:多付 ${yuan(p.pay_minor)} 元,今天的用量上限加 ${yuan(p.add_minor)} 元${p.deadline_at ? ',' + p.deadline_at + ' 前回复' : ''}`,
|
|
1184
|
+
`${ind}能接就同意,接不了就拒绝(拒绝或超时,雇主的钱全额退回):anytowork hire topup ${id} --accept(或 --reject)`,
|
|
1185
|
+
];
|
|
1186
|
+
}
|
|
1178
1187
|
case 'hire.reschedule':
|
|
1179
1188
|
return [
|
|
1180
1189
|
`${ind}📅 雇主想把入职日改成 ${p.new_start_date || '新的日期'},要你替主人确认`,
|
package/src/hire-commands.js
CHANGED
|
@@ -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,
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Always-on listener: waking the Agent for a hire event that waits for its answer (v0.38.41).
|
|
2
|
+
//
|
|
3
|
+
// Before this, the listener woke the Agent only for a workbench message (`wb.wake`). A hire event such as "you were
|
|
4
|
+
// picked, sign" or "the employer paid a top-up, accept or refuse" reached only whoever ran `anytowork poll`, so an Agent
|
|
5
|
+
// that is connected through the listener never heard of it. These events now start the Agent once, in a session of its
|
|
6
|
+
// own (the fixed key `hire-events`: there is no workbench session for them), with a prompt that names what waits and
|
|
7
|
+
// the commands to answer it. Informational hire events (start, wrap-up, stop for the day, left) do not wake the Agent.
|
|
8
|
+
|
|
9
|
+
import { hireEventLines } from '../format.js';
|
|
10
|
+
import { pickLang } from '../model-pledge.js';
|
|
11
|
+
|
|
12
|
+
/** The hire events that wait for an answer from the Agent and may end in a refund or a lost hire when nobody answers. */
|
|
13
|
+
export const WAKE_HIRE_EVENTS = new Set(['hire.to_sign', 'hire.topup', 'hire.reschedule']);
|
|
14
|
+
|
|
15
|
+
/** The session key every such run uses (placeholders {sid} and {session_key} of the start command). */
|
|
16
|
+
export const HIRE_WAKE_KEY = 'hire-events';
|
|
17
|
+
|
|
18
|
+
/** Events of one poll answer that should wake the Agent for a hire (an id is needed to tell a repeat from a new one). */
|
|
19
|
+
export function hireWakeEvents(events) {
|
|
20
|
+
return (events || []).filter((e) => e && WAKE_HIRE_EVENTS.has(e.event_type) && e.id != null);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** True when the event itself says its time to answer has already gone by (an old event met after a restart). */
|
|
24
|
+
export function hireEventExpired(e, nowMs) {
|
|
25
|
+
const dl = e && e.payload && e.payload.deadline_at ? Date.parse(e.payload.deadline_at) : NaN;
|
|
26
|
+
return Number.isFinite(dl) && dl < nowMs;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const EN_LINE = {
|
|
30
|
+
'hire.to_sign': (p) => `- You were picked for a hire${p.title ? ` "${p.title}"` : ''}${p.deadline_at ? `, sign before ${p.deadline_at}` : ''}: anytowork hire sign ${p.hire_id || '<hire id>'} (or hire decline)`,
|
|
31
|
+
'hire.topup': (p) => `- ${p.reminder ? 'Reminder: ' : ''}the employer paid a top-up for today${p.deadline_at ? `, answer before ${p.deadline_at}` : ''}; no answer in time = a full refund: anytowork hire topup ${p.hire_id || '<hire id>'} --accept | --reject`,
|
|
32
|
+
'hire.reschedule': (p) => `- The employer asks to move the start date to ${p.new_start_date || 'a new date'}: anytowork hire decide ${p.hire_id || '<hire id>'} --request ${p.request_id || '<request id>'} --accept | --reject`,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** The words handed to the Agent on standard input. */
|
|
36
|
+
export function hireWakePrompt(events, env = process.env) {
|
|
37
|
+
const lang = pickLang(env);
|
|
38
|
+
const list = hireWakeEvents(events);
|
|
39
|
+
if (lang === 'en') {
|
|
40
|
+
const lines = list.map((e) => EN_LINE[e.event_type]((e.payload) || {}));
|
|
41
|
+
return [
|
|
42
|
+
'[AnytoWork] There are hire events waiting for you (this is not a chat message).',
|
|
43
|
+
...lines,
|
|
44
|
+
'Run `anytowork poll` to see everything that waits and `anytowork hire mine` for your hires (a top-up shows there as well), then answer; stop when done.',
|
|
45
|
+
].join('\n');
|
|
46
|
+
}
|
|
47
|
+
const lines = [];
|
|
48
|
+
for (const e of list) {
|
|
49
|
+
const p = (e && e.payload) || {};
|
|
50
|
+
const own = hireEventLines(e).map((x) => `- ${x.trim()}`);
|
|
51
|
+
lines.push(...(own.length ? own : [`- ${e.event_type}`]));
|
|
52
|
+
if (p.reminder) lines.push(' (这是加量的到期提醒,快到回复截止时间了)');
|
|
53
|
+
}
|
|
54
|
+
return [
|
|
55
|
+
'[AnytoWork] 有招聘事件等你处理(不是聊天消息)。',
|
|
56
|
+
...lines,
|
|
57
|
+
'先运行 anytowork poll 看全部待办,再运行 anytowork hire mine 看你的聘用(加量也在里面);加量用 anytowork hire topup <招聘编号> --accept 或 --reject。处理完就结束。',
|
|
58
|
+
].join('\n');
|
|
59
|
+
}
|
package/src/listener/prompt.js
CHANGED
|
@@ -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
|
|
package/src/listener/run.js
CHANGED
|
@@ -20,6 +20,7 @@ import { WakeQueue } from './queue.js';
|
|
|
20
20
|
import { buildPrompt, testPrompt } from './prompt.js';
|
|
21
21
|
import { lt } from './text.js';
|
|
22
22
|
import { writeNudge } from './nudge.js';
|
|
23
|
+
import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
|
|
23
24
|
import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
|
|
24
25
|
import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
|
|
25
26
|
import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
|
|
@@ -258,9 +259,7 @@ export class Listener {
|
|
|
258
259
|
const p = job.payload || {};
|
|
259
260
|
const taskId = isSafeId(String(p.task_id || '')) ? String(p.task_id) : '';
|
|
260
261
|
if (!job.hireId && !taskId) return null;
|
|
261
|
-
|
|
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 });
|
|
262
|
+
return this.usage.begin({ sid: job.sid, wakeId: job.wakeId, command, startMs: this.nowMs(), wakeIds: job.wakeIds });
|
|
264
263
|
} catch {
|
|
265
264
|
return null;
|
|
266
265
|
}
|
|
@@ -310,7 +309,7 @@ export class Listener {
|
|
|
310
309
|
}
|
|
311
310
|
|
|
312
311
|
// ---- waking ----------------------------------------------------------------------------------------
|
|
313
|
-
/** Turn the events of one poll answer into queue entries;
|
|
312
|
+
/** Turn the events of one poll answer into queue entries; wb.wake, wake_test and the hire events that wait for an answer wake the Agent, everything else is ignored. */
|
|
314
313
|
handleEvents(events) {
|
|
315
314
|
// v0.36: a picked / signed event may carry the work folder of the job: set it up on this computer
|
|
316
315
|
for (const e of events || []) { const wp = workdirFromEvent(this.credOpts, e); if (wp) this.logLine(`workdir ${wp}`); }
|
|
@@ -320,6 +319,7 @@ export class Listener {
|
|
|
320
319
|
for (const e of events || []) {
|
|
321
320
|
if (e && e.event_type === 'wake_test') this.handleWakeTest(e);
|
|
322
321
|
}
|
|
322
|
+
this.handleHireEvents(events);
|
|
323
323
|
for (const e of events || []) {
|
|
324
324
|
if (!e || e.event_type !== 'wb.wake') continue;
|
|
325
325
|
const p = e.payload || {};
|
|
@@ -359,6 +359,65 @@ export class Listener {
|
|
|
359
359
|
this.pump();
|
|
360
360
|
}
|
|
361
361
|
|
|
362
|
+
/**
|
|
363
|
+
* v0.38.41: a hire event that waits for the Agent (picked: sign; top-up: accept or refuse; new start date: decide).
|
|
364
|
+
* One run for all such events of one poll answer, in the session `hire-events` (no workbench session needed). An event
|
|
365
|
+
* id that was already handled is not started twice, an event whose own deadline has passed is skipped, a run already
|
|
366
|
+
* going holds the next one back until it ends. Like a wake-up it stops while paused and counts against the daily limit.
|
|
367
|
+
*/
|
|
368
|
+
handleHireEvents(events) {
|
|
369
|
+
const fresh = hireWakeEvents(events);
|
|
370
|
+
if (!fresh.length) return;
|
|
371
|
+
if (!this.seenHire) this.seenHire = new Set();
|
|
372
|
+
const now = this.nowMs();
|
|
373
|
+
for (const e of fresh) {
|
|
374
|
+
const key = String(e.id);
|
|
375
|
+
if (this.seenHire.has(key)) continue;
|
|
376
|
+
this.seenHire.add(key);
|
|
377
|
+
if (this.seenHire.size > 200) this.seenHire.delete(this.seenHire.values().next().value);
|
|
378
|
+
if (hireEventExpired(e, now)) { this.logLine(`hire event id=${key} expired`); continue; }
|
|
379
|
+
if (this.isPaused()) { this.logLine(`hire event id=${key} paused`); continue; }
|
|
380
|
+
(this.hireWaiting || (this.hireWaiting = [])).push(e);
|
|
381
|
+
}
|
|
382
|
+
this.pumpHire();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
pumpHire() {
|
|
386
|
+
if (this.hireRunning || !this.hireWaiting || !this.hireWaiting.length || this.isPaused()) return;
|
|
387
|
+
const now = this.nowMs();
|
|
388
|
+
if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.hireWaiting = []; this.pause('cap'); return; }
|
|
389
|
+
const batch = this.hireWaiting.splice(0);
|
|
390
|
+
countRun(this.state, now);
|
|
391
|
+
this.save();
|
|
392
|
+
this.hireRunning = true;
|
|
393
|
+
const pr = this.runHireWake(batch).catch(() => {}).finally(() => { this.hireRunning = false; this.active.delete(pr); this.pumpHire(); });
|
|
394
|
+
this.active.add(pr);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async runHireWake(batch) {
|
|
398
|
+
const now0 = this.nowMs();
|
|
399
|
+
const key = HIRE_WAKE_KEY;
|
|
400
|
+
const firstId = String(batch[0].id);
|
|
401
|
+
const promptFile = path.join(promptsDir(this.credOpts), `hire-${firstId}-${now0}.txt`);
|
|
402
|
+
let wrote = false;
|
|
403
|
+
const prompt = hireWakePrompt(batch, this.env);
|
|
404
|
+
try {
|
|
405
|
+
fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
|
|
406
|
+
fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
|
|
407
|
+
wrote = true;
|
|
408
|
+
} catch { /* the prompt still goes on standard input */ }
|
|
409
|
+
try {
|
|
410
|
+
const hid = batch.map((e) => e.payload && e.payload.hire_id).find((h) => isSafeId(String(h || ''))) || '';
|
|
411
|
+
const vals = { sid: key, sessionKey: key, groupId: '', wakeId: firstId, reason: 'hire_event', hireId: hid ? String(hid) : '', promptFile };
|
|
412
|
+
const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
|
|
413
|
+
const res = await this.execCommand({ command: expandCommand(this.cfg.exec, vals), input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
|
|
414
|
+
const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
|
|
415
|
+
this.logLine(`hire wake ids=${batch.map((e) => e.id).join(',')} ${ok ? 'ok' : 'fail'} ms=${this.nowMs() - now0}`);
|
|
416
|
+
} finally {
|
|
417
|
+
if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
362
421
|
/**
|
|
363
422
|
* v0.37 PA-12: the platform started a wake-up test for this Agent (`wake_test`: {test_id, nonce, deadline_at, next_action}).
|
|
364
423
|
* Start the Agent once with a prompt that only asks it to answer the test. The isolation key is the fixed word
|
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
|
-
|
|
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
|
|
2
|
-
// WHILE the Agent runs and once more when it ends.
|
|
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
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
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
|
|
27
|
+
const KEEP_FINISHED_MS = 10 * 60 * 1000; // finished runs stay known this long
|
|
27
28
|
|
|
28
|
-
/** The
|
|
29
|
-
export function buildTaskRef({ sid, wakeId,
|
|
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 (
|
|
32
|
-
|
|
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. `
|
|
152
|
-
begin({ sid, wakeId,
|
|
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
|
-
|
|
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),
|
|
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
|
|
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
|
|
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
|
-
//
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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:
|
|
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(
|
|
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:
|
|
257
|
-
task_ref:
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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 >
|
|
328
|
-
if (live.has(c.session_id) || (state.perCallReported || {})[c.session_id]) continue; // the session already has its calls one by one
|
|
329
|
-
rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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')
|
|
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
|
|
534
|
-
if (
|
|
535
|
-
|
|
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,
|
|
645
|
+
transcriptCache.set(ck, parsed);
|
|
538
646
|
}
|
|
539
|
-
if (
|
|
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
|
+
}
|