@anytowork/cli 0.12.52 → 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 +1 -1
- package/src/cli-parse.js +1 -1
- package/src/format.js +8 -1
- package/src/hire-commands.js +19 -0
- package/src/listener/prompt.js +6 -0
- package/src/listener/run.js +1 -3
- package/src/mt/collect.js +4 -3
- package/src/mt/commands.js +11 -1
- package/src/mt/dsh.js +23 -7
- package/src/mt/inrun.js +75 -126
- package/src/mt/readers.js +138 -20
- package/src/mt/sample.js +5 -2
- package/src/mt/text.js +2 -0
- 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,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 || '新的日期'},要你替主人确认`,
|
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,
|
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
|
@@ -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
|
-
|
|
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/collect.js
CHANGED
|
@@ -154,15 +154,16 @@ export async function gatherLocal({ credOpts, scope = null, sinceMs, nowMs = Dat
|
|
|
154
154
|
const cache = new Map();
|
|
155
155
|
const rows = [];
|
|
156
156
|
let outside = 0;
|
|
157
|
+
let noCwd = 0; // v0.38.36: part of `outside` whose log line has no folder at all
|
|
157
158
|
const pick = (cwd) => {
|
|
158
159
|
const wd = workdirForPath(cwd, registry, cache);
|
|
159
|
-
if (!wd) { outside += 1; return null; }
|
|
160
|
+
if (!wd) { outside += 1; if (!cwd) noCwd += 1; return null; }
|
|
160
161
|
if (scope && !(wd.scope === scope.scope && String(wd.scope_id) === String(scope.id))) return null;
|
|
161
162
|
return wd;
|
|
162
163
|
};
|
|
163
164
|
for (const c of logs.calls) { const wd = pick(c.cwd); if (wd) rows.push(callRow(c, wd)); }
|
|
164
165
|
for (const s of logs.summaries) { const wd = pick(s.cwd); if (wd) rows.push(summaryRow(s, wd)); }
|
|
165
|
-
return { rows, found: logs.calls.length + logs.summaries.length, outside, files: logs.files };
|
|
166
|
+
return { rows, found: logs.calls.length + logs.summaries.length, outside, noCwd, files: logs.files };
|
|
166
167
|
}
|
|
167
168
|
|
|
168
169
|
// ---------------------------------------------------------------- sending
|
|
@@ -257,7 +258,7 @@ export async function collectUsage({ baseUrl, credOpts, fetchImpl, scope = null,
|
|
|
257
258
|
if (!dryRun && state.sent[k]) continue;
|
|
258
259
|
fresh.push(r);
|
|
259
260
|
}
|
|
260
|
-
const res = { found: g.found, outside: g.outside, files: g.files, inWorkdir: g.rows.length, zero, rows: fresh, sent: null };
|
|
261
|
+
const res = { found: g.found, outside: g.outside, noCwd: g.noCwd || 0, files: g.files, inWorkdir: g.rows.length, zero, rows: fresh, sent: null };
|
|
261
262
|
if (dryRun || !fresh.length) {
|
|
262
263
|
if (!dryRun) { state.last_collect_at = new Date(nowMs).toISOString(); state.last_ok_at = state.last_collect_at; writeState(credOpts, state, nowMs); }
|
|
263
264
|
return res;
|
package/src/mt/commands.js
CHANGED
|
@@ -242,9 +242,17 @@ export function describeSend(tot, env) {
|
|
|
242
242
|
return lines;
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
+
/** v0.38.36: how many log lines were left out and why (no folder in the log line / folder is not a work folder). */
|
|
246
|
+
function droppedLine(res, env) {
|
|
247
|
+
const out = res.outside || 0;
|
|
248
|
+
if (!out) return [];
|
|
249
|
+
const noCwd = res.noCwd || 0;
|
|
250
|
+
return [t('usage.dropped', { n: out, nocwd: noCwd, other: out - noCwd }, env)];
|
|
251
|
+
}
|
|
252
|
+
|
|
245
253
|
export function describeCollect(res, env, { dryRun = false } = {}) {
|
|
246
254
|
if (!res.found && !res.files) return [t('usage.no_logs', {}, env)];
|
|
247
|
-
if (!res.inWorkdir) return res.found ? [t('usage.none_in_workdir', { n: res.found }, env)] : [t('usage.nothing_new', {}, env)];
|
|
255
|
+
if (!res.inWorkdir) return res.found ? [t('usage.none_in_workdir', { n: res.found }, env), ...droppedLine(res, env)] : [t('usage.nothing_new', {}, env)];
|
|
248
256
|
const lines = [];
|
|
249
257
|
if (dryRun) {
|
|
250
258
|
lines.push(t('usage.dry_title', { n: res.rows.length }, env));
|
|
@@ -266,8 +274,10 @@ export function describeCollect(res, env, { dryRun = false } = {}) {
|
|
|
266
274
|
}
|
|
267
275
|
for (const [model, a] of per) lines.push(t('usage.dry_model', { model, in: n(a.in), out: n(a.out), cw: n(a.cw), cr: n(a.cr) }, env));
|
|
268
276
|
}
|
|
277
|
+
lines.push(...droppedLine(res, env));
|
|
269
278
|
return lines;
|
|
270
279
|
}
|
|
280
|
+
lines.push(...droppedLine(res, env));
|
|
271
281
|
if (res.zero) lines.push(t('usage.zero_skipped', { n: res.zero }, env));
|
|
272
282
|
if (!res.sent) { lines.push(t('usage.nothing_new', {}, env)); return lines; }
|
|
273
283
|
if (res.sent.featureOff) { lines.push(t('usage.feature_off', {}, env)); return lines; }
|
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,18 +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
58
|
/** The program a start command names (first word of a path or `exec`), or null when it is a wrapper we cannot tell. */
|
|
71
59
|
export function programOfCommand(command) {
|
|
72
60
|
const words = String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
|
|
@@ -81,13 +69,6 @@ export function programOfCommand(command) {
|
|
|
81
69
|
return null;
|
|
82
70
|
}
|
|
83
71
|
|
|
84
|
-
function shareDir(a, b) { return a.dirs.some((d) => b.dirs.includes(d)); }
|
|
85
|
-
function timeOverlap(a, b, now) {
|
|
86
|
-
const aEnd = a.endMs == null ? now : a.endMs + FINISH_GRACE_MS;
|
|
87
|
-
const bEnd = b.endMs == null ? now : b.endMs + FINISH_GRACE_MS;
|
|
88
|
-
return a.startMs - START_SLACK_MS <= bEnd && b.startMs - START_SLACK_MS <= aEnd;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
72
|
function callRow(c, ctx) {
|
|
92
73
|
const row = {
|
|
93
74
|
schema: SCHEMA_V2,
|
|
@@ -136,16 +117,16 @@ export class RunUsageTracker {
|
|
|
136
117
|
this.chain = Promise.resolve(); // uploads one after another: they share one local state file
|
|
137
118
|
}
|
|
138
119
|
|
|
139
|
-
/** A run starts. `
|
|
140
|
-
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 }) {
|
|
141
122
|
const now = this.nowMs();
|
|
142
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()));
|
|
143
125
|
const r = {
|
|
144
126
|
seq: (this.seq += 1), sid, startMs: startMs != null ? startMs : now, endMs: null,
|
|
145
|
-
|
|
146
|
-
dirs: [...new Set((dirs || []).map(norm).filter(Boolean))],
|
|
127
|
+
wakeIds: ids,
|
|
147
128
|
tokens: String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter((t) => t.length >= 4 && !t.startsWith('-') && /[:_-]/.test(t)),
|
|
148
|
-
prog: programOfCommand(command),
|
|
129
|
+
prog: programOfCommand(command),
|
|
149
130
|
cum: new Map(), // `session|model` -> totals already sent
|
|
150
131
|
sentAny: false,
|
|
151
132
|
};
|
|
@@ -153,7 +134,7 @@ export class RunUsageTracker {
|
|
|
153
134
|
return r;
|
|
154
135
|
}
|
|
155
136
|
|
|
156
|
-
/** 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). */
|
|
157
138
|
upload(r, { final = false } = {}) {
|
|
158
139
|
const next = this.chain.then(() => this.#upload(r, final)).catch(() => null);
|
|
159
140
|
this.chain = next;
|
|
@@ -166,124 +147,93 @@ export class RunUsageTracker {
|
|
|
166
147
|
return this.upload(r, { final: true });
|
|
167
148
|
}
|
|
168
149
|
|
|
169
|
-
peers(r, now) {
|
|
170
|
-
return this.runs.filter((x) => x !== r && shareDir(x, r) && timeOverlap(x, r, now));
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* 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
|
|
175
|
-
* at the same time, the sessions of that folder are handed out in the order the runs started (not sure: `window`).
|
|
176
|
-
* `ordered`: the sessions of the folders of this crowd, by start time.
|
|
177
|
-
*/
|
|
178
|
-
#hermesOwner(s, r, now, ordered) {
|
|
179
|
-
const group = [r, ...this.peers(r, now)].sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
|
|
180
|
-
const fits = group.filter((x) => s.startedMs >= x.startMs - START_SLACK_MS && (x.endMs == null || s.startedMs <= x.endMs + FINISH_GRACE_MS));
|
|
181
|
-
if (!fits.length) return { owner: null, sure: false };
|
|
182
|
-
if (fits.length === 1) return { owner: fits[0], sure: true };
|
|
183
|
-
const rank = Math.max(0, ordered.findIndex((x) => x.id === s.id));
|
|
184
|
-
return { owner: fits[Math.min(rank, fits.length - 1)], sure: false };
|
|
185
|
-
}
|
|
186
|
-
|
|
187
150
|
async #upload(r, final) {
|
|
188
|
-
if (this.off) return null;
|
|
151
|
+
if (this.off || !r.wakeIds.size) return null;
|
|
189
152
|
const now = this.nowMs();
|
|
190
153
|
const since = r.startMs - START_SLACK_MS;
|
|
191
|
-
const until = final ? (r.endMs != null ? r.endMs : now) + FINISH_GRACE_MS : now;
|
|
192
154
|
const settleMs = final ? 0 : SETTLE_MS;
|
|
193
|
-
const env = this
|
|
194
|
-
const home = this.home;
|
|
155
|
+
const { home, env } = this;
|
|
195
156
|
const state = readState(this.credOpts);
|
|
196
157
|
const registry = (() => { try { return readRegistry(this.credOpts); } catch { return {}; } })();
|
|
197
158
|
const wdCache = new Map();
|
|
198
159
|
const workdirOf = (cwd) => { try { const w = workdirForPath(cwd, registry, wdCache); return w ? w.workdir_id : null; } catch { return null; } };
|
|
199
|
-
const crowd = this.peers(r, now).length > 0;
|
|
200
160
|
const rows = [];
|
|
201
161
|
const pendingCum = [];
|
|
202
162
|
const heldSessions = [];
|
|
203
163
|
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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}`;
|
|
220
191
|
const totals = `${m.input_tokens}|${m.output_tokens}|${m.cache_write_tokens}|${m.cache_read_tokens}|${m.reasoning_tokens}`;
|
|
221
192
|
if (r.cum.get(sig) === totals) continue;
|
|
222
193
|
const row = {
|
|
223
194
|
schema: SCHEMA_V2, kind: 'cumulative', granularity: 'cumulative',
|
|
224
|
-
source_session_key:
|
|
195
|
+
source_session_key: c.id, conversation_id: c.id,
|
|
225
196
|
provider: guessProvider(m.model), model: m.model.slice(0, 120),
|
|
226
|
-
started_at: isoSec(
|
|
197
|
+
started_at: isoSec(c.startedMs), ended_at: isoSec(c.lastSeenMs || c.startedMs),
|
|
227
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,
|
|
228
199
|
reasoning_tokens: m.reasoning_tokens,
|
|
229
|
-
program: 'hermes', reader: 'cli:session_model_usage', attribution:
|
|
230
|
-
task_ref:
|
|
200
|
+
program: 'hermes', reader: 'cli:session_model_usage', attribution: o.attribution,
|
|
201
|
+
task_ref: taskRef, source: 'local-log',
|
|
231
202
|
};
|
|
232
203
|
if (isZero(row)) continue;
|
|
233
204
|
rows.push(row);
|
|
234
205
|
pendingCum.push([sig, totals]);
|
|
235
206
|
}
|
|
207
|
+
continue;
|
|
236
208
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
// Claude Code / Codex: calls of the run's folders in the run's time window
|
|
240
|
-
const attributionOfCalls = crowd ? 'window' : 'run';
|
|
241
|
-
const fromJsonl = [
|
|
242
|
-
{ program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since, log: this.log }) },
|
|
243
|
-
{ program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since, log: this.log }) },
|
|
244
|
-
{ program: 'dsh', reader: 'cli:dsh_log', read: () => readDshLog({ home, env, sinceMs: since, log: this.log }) },
|
|
245
|
-
];
|
|
246
|
-
for (const src of fromJsonl) {
|
|
247
|
-
if (r.prog && r.prog !== src.program) continue;
|
|
248
|
-
try {
|
|
249
|
-
for (const c of src.read().calls) {
|
|
250
|
-
if (c.seenMs < since || c.seenMs > until || c.seenMs > now - settleMs) continue;
|
|
251
|
-
if (!c.cwd) continue;
|
|
252
|
-
// v0.38.33: DSH records the folder it was started from (the home folder), not the Agent's work folder. A run that
|
|
253
|
-
// the start command names as dsh takes the dsh calls made from the home folder inside its own time window.
|
|
254
|
-
const harnessHome = src.program === 'dsh' && r.prog === 'dsh' && norm(c.cwd) === norm(home);
|
|
255
|
-
if (!harnessHome && !dirMatches(c.cwd, r.dirs, home)) continue;
|
|
256
|
-
rows.push(callRow(c, { program: src.program, reader: src.reader, attribution: attributionOfCalls, taskRef: r.taskRef, workdirId: workdirOf(c.cwd) }));
|
|
257
|
-
}
|
|
258
|
-
} 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) }));
|
|
259
211
|
}
|
|
260
212
|
|
|
261
|
-
// 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
|
|
262
214
|
if (r.tokens.length && (!r.prog || r.prog === 'openclaw')) {
|
|
263
215
|
const mine = (c) => {
|
|
264
216
|
const key = c.session_key || '';
|
|
265
217
|
return r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
|
|
266
218
|
};
|
|
267
|
-
|
|
268
|
-
const live = new Set();
|
|
269
|
-
try {
|
|
270
|
-
const tr = await readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log });
|
|
271
|
-
for (const c of tr.calls) {
|
|
272
|
-
if (c.seenMs < since || c.seenMs > until || !mine(c)) continue;
|
|
273
|
-
live.add(c.session_id);
|
|
274
|
-
rows.push(callRow(c, { program: 'openclaw', reader: 'cli:transcript_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
|
|
275
|
-
}
|
|
276
|
-
} 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));
|
|
277
220
|
try {
|
|
278
221
|
const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log, verdictKnown: true });
|
|
279
222
|
for (const c of oc.calls) {
|
|
280
|
-
if (c.seenMs < since || c.seenMs >
|
|
281
|
-
if (live.has(c.session_id) || (state.perCallReported || {})[c.session_id]) continue; // the session already has its calls one by one
|
|
282
|
-
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' }) }));
|
|
283
226
|
}
|
|
284
227
|
} catch { /* same */ }
|
|
285
228
|
}
|
|
286
229
|
|
|
230
|
+
const nDropped = Object.values(dropped).reduce((x, y) => x + y, 0);
|
|
231
|
+
if (nDropped) {
|
|
232
|
+
this.lastDropped = dropped;
|
|
233
|
+
this.log(`usage: ${nDropped} calls not taken (${Object.entries(dropped).map(([k, v]) => `${k} x${v}`).join(', ')})`);
|
|
234
|
+
state.lastDropped = { at: new Date(now).toISOString(), reasons: dropped };
|
|
235
|
+
}
|
|
236
|
+
|
|
287
237
|
// what was already sent is not sent again (calls: the local list shared with the idle upload)
|
|
288
238
|
const seen = new Set();
|
|
289
239
|
const fresh = [];
|
|
@@ -296,7 +246,7 @@ export class RunUsageTracker {
|
|
|
296
246
|
fresh.push(row);
|
|
297
247
|
}
|
|
298
248
|
if (final) markSummariesSent(state, heldSessions);
|
|
299
|
-
if (!fresh.length) { if (final) writeState(this.credOpts, state, now); return { sent: 0 }; }
|
|
249
|
+
if (!fresh.length) { if (final || nDropped) writeState(this.credOpts, state, now); return { sent: 0, dropped }; }
|
|
300
250
|
const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
|
|
301
251
|
if (tot.featureOff) this.off = true;
|
|
302
252
|
if (!tot.error && !tot.featureOff) {
|
|
@@ -309,7 +259,7 @@ export class RunUsageTracker {
|
|
|
309
259
|
r.sentAny = true;
|
|
310
260
|
}
|
|
311
261
|
writeState(this.credOpts, state, now);
|
|
312
|
-
return { sent: fresh.length, tot };
|
|
262
|
+
return { sent: fresh.length, tot, dropped };
|
|
313
263
|
}
|
|
314
264
|
}
|
|
315
265
|
|
|
@@ -317,4 +267,3 @@ export class RunUsageTracker {
|
|
|
317
267
|
function markSummariesSent(state, sessionIds) {
|
|
318
268
|
for (const id of sessionIds) state.sent[`s:s-${sha256(String(id)).slice(0, 32)}`] = Date.now();
|
|
319
269
|
}
|
|
320
|
-
|
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
|
/**
|
|
@@ -552,6 +661,15 @@ export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
|
|
|
552
661
|
*/
|
|
553
662
|
export async function readLocalLogs({ home = os.homedir(), env = process.env, sinceMs = 0, nowMs = Date.now(), settleMs = 60_000, sqlite } = {}) {
|
|
554
663
|
const parts = [readMsgLog({ home, env, sinceMs }), readRollout({ home, env, sinceMs }), readDshLog({ home, env, sinceMs }), await readSessionDb({ home, env, sinceMs, sqlite })];
|
|
664
|
+
// v0.38.36: the run-log program too. The transcript (one call per assistant message) and the run log (one total per run) describe the
|
|
665
|
+
// same sessions: a session that has its calls one by one is taken from the transcript only, so the two never add up twice.
|
|
666
|
+
try {
|
|
667
|
+
const tr = await readTranscriptUsage({ home, env, sinceMs, sqlite });
|
|
668
|
+
const rl = await readRunLog({ home, env, sinceMs, sqlite, verdictKnown: true });
|
|
669
|
+
const live = new Set(tr.calls.map((c) => c.session_id));
|
|
670
|
+
parts.push({ calls: tr.calls.map((c) => ({ ...c, reader: 'transcript_db' })), summaries: [], files: tr.files || 0 });
|
|
671
|
+
parts.push({ calls: rl.calls.filter((c) => !live.has(c.session_id)).map((c) => ({ ...c, reader: 'run_db' })), summaries: [], files: rl.files || 0 });
|
|
672
|
+
} catch { /* an unreadable run-log database never blocks the other logs */ }
|
|
555
673
|
const cut = nowMs - settleMs;
|
|
556
674
|
return {
|
|
557
675
|
calls: parts.flatMap((p) => p.calls).filter((c) => c.seenMs <= cut),
|
package/src/mt/sample.js
CHANGED
|
@@ -563,7 +563,8 @@ async function gatherSample(c, tz) {
|
|
|
563
563
|
}
|
|
564
564
|
const g = got[0];
|
|
565
565
|
if (g.inWin.every((x) => unpriceable(x.model))) return { unreadable: 'model' };
|
|
566
|
-
|
|
566
|
+
const noModel = g.inWin.filter((x) => String(x.model || '').trim() === '').length;
|
|
567
|
+
return { sample: buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }), client: clientOf(g.src.reader, g.entries), drops: { old: g.calls.length - g.inWin.length, nomodel: noModel } };
|
|
567
568
|
}
|
|
568
569
|
|
|
569
570
|
function resultLines(d, env) {
|
|
@@ -588,6 +589,7 @@ export async function cmdSample(c) {
|
|
|
588
589
|
let body;
|
|
589
590
|
let summary = null;
|
|
590
591
|
let client = null;
|
|
592
|
+
let drops = null;
|
|
591
593
|
if (c.flags.unreadable != null) {
|
|
592
594
|
const reason = String(c.flags.unreadable).replace(/\s+/g, ' ').trim();
|
|
593
595
|
if (!reason || reason.length > REASON_MAX) return c.fail(2, 'bad_reason', t('sample.bad_reason', { max: REASON_MAX }, env));
|
|
@@ -609,7 +611,7 @@ export async function cmdSample(c) {
|
|
|
609
611
|
return 2;
|
|
610
612
|
}
|
|
611
613
|
body = g.sample || { kind: KIND, unreadable: true, reason: reasonText(g.unreadable, env) };
|
|
612
|
-
if (g.sample) { summary = summarize(g.sample); client = g.client; }
|
|
614
|
+
if (g.sample) { summary = summarize(g.sample); client = g.client; drops = g.drops || null; }
|
|
613
615
|
}
|
|
614
616
|
const clientField = client ? { client } : {};
|
|
615
617
|
const clientLine = client ? [t('sample.client', { v: `${client.name} · ${client.entries.join(', ')}` }, env)] : [];
|
|
@@ -622,6 +624,7 @@ export async function cmdSample(c) {
|
|
|
622
624
|
c.log(t('sample.dry_title', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
|
|
623
625
|
for (const l of clientLine) c.log(l);
|
|
624
626
|
c.log(t('sample.dry_models', { v: summary.models.map((m) => `${m.model} ${m.share}%`).join(', ') }, env));
|
|
627
|
+
if (drops && (drops.old || drops.nomodel)) c.log(t('sample.dry_dropped', drops, env));
|
|
625
628
|
}
|
|
626
629
|
c.log(t('sample.own_only', {}, env));
|
|
627
630
|
return 0;
|
package/src/mt/text.js
CHANGED
|
@@ -76,6 +76,8 @@ const TEXT = {
|
|
|
76
76
|
zh: '找到了 {n} 条模型调用记录,但都不在专属工作目录里,没有上传。接了单先 anytowork workdir open <单号>,在那个目录里干活。',
|
|
77
77
|
en: 'Found {n} model calls, but none inside a work folder, so nothing was sent. After you get a job, run anytowork workdir open <id> and work inside that folder.',
|
|
78
78
|
},
|
|
79
|
+
'usage.dropped': { zh: '未上传 {n} 条:日志没有目录 {nocwd},不在工作目录 {other}。', en: 'Left out {n}: no folder in the log {nocwd}, not in a work folder {other}.' },
|
|
80
|
+
'sample.dry_dropped': { zh: ' 未计入:超出 30 天 {old},没有模型名 {nomodel}', en: ' Left out: older than 30 days {old}, no model name {nomodel}' },
|
|
79
81
|
'usage.nothing_new': { zh: '没有新的模型调用记录要上传。', en: 'No new model call records to send.' },
|
|
80
82
|
'usage.dry_title': { zh: '试运行(不上传):找到 {n} 条可上传的记录', en: 'Dry run (nothing sent): {n} records ready to send' },
|
|
81
83
|
'usage.dry_workdir': { zh: ' {wd}({scope}):{n} 条', en: ' {wd} ({scope}): {n} records' },
|
|
@@ -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
|
+
}
|