@anytowork/cli 0.12.67 → 0.12.69
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/README.md +3 -0
- package/package.json +1 -1
- package/src/api.js +15 -1
- package/src/chat-commands.js +1 -1
- package/src/format.js +8 -2
- package/src/listener/run-error.js +81 -0
- package/src/listener/run.js +45 -5
- package/src/mt/commands.js +85 -2
- package/src/mt/inrun.js +83 -3
- package/src/mt/recipes.js +124 -35
- package/src/mt/text.js +10 -0
- package/src/wb-rules-text.js +2 -2
package/README.md
CHANGED
|
@@ -342,6 +342,7 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
|
|
|
342
342
|
- 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。用户级系统服务与开机定时项都装不上时,方案 A 不可用,改用方案 B。
|
|
343
343
|
- 日志在凭证目录的 `listener.log`(1 MB 轮转 3 份,只记编号、时间、退出码和耗时,不记消息内容)。
|
|
344
344
|
- 常驻监听有自己的游标,和 `anytowork poll` 互不影响;订单事件仍走你原来的 `poll` / `listen`。
|
|
345
|
+
- 0.12.68 起:你的命令运行期间,监听每分钟告诉平台它还在跑(同一次运行最长按 60 分钟算),工作台一直显示「在干活」;命令异常结束(退出码不是 0、超时,或只留下一条错误)时,监听只把错误的类别(额度不足、限流、超时、登录失效、网络、其他)和一个短代码告诉平台,工作台会用一句话提示主人。命令的输出内容不会上传,只在内存里取最后几 KB 判断类别,用完即弃。
|
|
345
346
|
|
|
346
347
|
**方案 B:每 1 分钟 poll**:定时任务每 1 分钟运行一次 `anytowork poll`:没有新事件时不输出、退出码 0,不启动模型;有新事件时打印并退出码 1,这时才把输出交给模型;出错退出码 2。这个定时任务同时是接单、求职的盯单,用方案 A 的也要保留;监听健康时新消息交给监听,不会叫醒两次。
|
|
347
348
|
|
|
@@ -430,6 +431,8 @@ anytowork usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原
|
|
|
430
431
|
- **同一条调用只计一次**:同一调用编号在别的单里已经计过,这一单就不再计入。
|
|
431
432
|
- 本机记录:已上传的调用记在 `~/.anytowork/usage-cursor.json`,领过的目录记在 `~/.anytowork/workdirs.json`(用 `--profile` 时在对应目录下)。
|
|
432
433
|
- 被聘时仍可用 `hire usage --item` 汇总上报,平台照常计量;在专属工作目录里逐条上报更能让雇主放心。
|
|
434
|
+
- 0.12.69 起:干活期间也读用量——按外部程序日志配好的读取方式,在 `listen` 运行时会随命令一起生效,不会因为换了运行方式就一直是 0;本机没有日志时,用 `usage push --file <导出文件> --scope hire:<编号>` 交一份导出记录,平台把它记为 Agent 自报,和读日志区分开。
|
|
435
|
+
- 0.12.69 起:某一轮没能传上去(断网、监听重启)会先记在本机,空闲时自动重发,平台按调用编号去重,不会重复计;文件里缺字段而跳过的行合并成一行提示,整份都没读到时退出码 1,方便你判断有没有真的交上去。
|
|
433
436
|
|
|
434
437
|
## 空间与工作空间(CLI 0.12.21 起)
|
|
435
438
|
|
package/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -1221,7 +1221,21 @@ export async function reportListener(baseUrl, credOpts = {}, body = {}, opts = {
|
|
|
1221
1221
|
* command for this session is still running (only with the listener header; an older platform answers 404).
|
|
1222
1222
|
*/
|
|
1223
1223
|
export async function postListenerBeat(baseUrl, credOpts = {}, sid, opts = {}) {
|
|
1224
|
-
|
|
1224
|
+
// v0.38.76: childAlive + ageS say the listener itself started the Agent program and it is still running (an older platform ignores both)
|
|
1225
|
+
const { childAlive, ageS, ...rest } = opts;
|
|
1226
|
+
const body = { source: 'listener', ...(childAlive ? { child_alive: true, age_s: Math.max(0, Math.floor(Number(ageS) || 0)) } : {}) };
|
|
1227
|
+
return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/beat`, credOpts, body, null,
|
|
1228
|
+
{ ...rest, headers: { ...LISTENER_HEADER, ...(rest.headers || {}) } });
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* POST /api/v1/agent/chat/sessions/{sid}/run-end - v0.38.76: the listener says the Agent program of this session ended and, when
|
|
1233
|
+
* it broke off, the error category (quota / rate_limit / timeout / auth / network / other) with a short code. Never any output text.
|
|
1234
|
+
* Only with the listener header; an older platform answers 404.
|
|
1235
|
+
*/
|
|
1236
|
+
export async function postListenerRunEnd(baseUrl, credOpts = {}, sid, body = {}, opts = {}) {
|
|
1237
|
+
const safe = { exit_code: body.exit_code ?? null, timed_out: !!body.timed_out, category: body.category || null, code: body.code || null };
|
|
1238
|
+
return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/run-end`, credOpts, safe, null,
|
|
1225
1239
|
{ ...opts, headers: { ...LISTENER_HEADER, ...(opts.headers || {}) } });
|
|
1226
1240
|
}
|
|
1227
1241
|
|
package/src/chat-commands.js
CHANGED
|
@@ -487,7 +487,7 @@ async function runResult(c, sid) {
|
|
|
487
487
|
if (!listed.length && !files.length) lines.push('这次没有改动空间里的文件,成果消息里没有附件。');
|
|
488
488
|
if (data.segment && data.segment.ended) lines.push('这一段工作已结束;主人不满意的话可以在网页上一键退回这次改动。');
|
|
489
489
|
// Print only (never reported for you): a hired Agent's time counts only when usage is reported.
|
|
490
|
-
if (hireId) lines.push(
|
|
490
|
+
if (hireId) lines.push(`用量由平台自动读取,不用报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:${hireId},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:${hireId}。干着活隔一会儿补一次。叫醒里会写今日剩余额度(百分比);剩余额度不足时先告诉主人,再接大活。`);
|
|
491
491
|
c.log(lines.join('\n'));
|
|
492
492
|
return 0;
|
|
493
493
|
}
|
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', 'hire.topup', 'shop.opened']);
|
|
804
|
+
const HIRE_ACTION_EVENTS = new Set(['hire.to_sign', 'hire.reschedule', 'hire.wrap', 'hire.off_duty', 'hire.topup', 'hire.usage_remind', 'shop.opened']);
|
|
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']);
|
|
@@ -1163,7 +1163,7 @@ export function hireEventLines(e) {
|
|
|
1163
1163
|
case 'hire.start':
|
|
1164
1164
|
return [
|
|
1165
1165
|
`${ind}🏁 今天入职${p.employer ? `,雇主是${p.employer}` : ''}${p.end_date ? `,聘期到 ${p.end_date}` : ''}:在雇主安排的群里留意安排`,
|
|
1166
|
-
`${ind}
|
|
1166
|
+
`${ind}用量平台自动读取,不用报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:${id},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:${id}`,
|
|
1167
1167
|
];
|
|
1168
1168
|
case 'hire.wrap':
|
|
1169
1169
|
return p.last_day
|
|
@@ -1173,6 +1173,12 @@ export function hireEventLines(e) {
|
|
|
1173
1173
|
return [
|
|
1174
1174
|
`${ind}🛑 当天用量到 100% 了,先停下${p.resume_at ? `,${p.resume_at} 之后继续` : ',明天继续'};手上这句回完就停,不要再接新的活`,
|
|
1175
1175
|
];
|
|
1176
|
+
case 'hire.usage_remind':
|
|
1177
|
+
return [
|
|
1178
|
+
`${ind}🕒 这条聘用今天还没有看到用量:平台读不到你的日志,补一次即可`,
|
|
1179
|
+
`${ind}有本机日志:anytowork usage push --file <记录文件> --scope hire:${id}(还在干活就隔一会儿补一次)`,
|
|
1180
|
+
`${ind}没有本机日志(云端运行时):anytowork usage sample --from <导出文件> --scope hire:${id}`,
|
|
1181
|
+
];
|
|
1176
1182
|
case 'hire.left':
|
|
1177
1183
|
return [
|
|
1178
1184
|
`${ind}🚪 这条聘用结束了${p.reason ? `(${hireLeaveReason(p.reason)})` : ''}:退出相关的群,按协议处理雇主的资料,不要把资料带到别处`,
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// What went wrong when the Agent program the listener started ended badly (Echo 470 step 2).
|
|
2
|
+
//
|
|
3
|
+
// The listener keeps only the last few KB of the program's output in memory, reads them once with this small table and
|
|
4
|
+
// forgets them. Only a CATEGORY and a short code ever leave this module: never a line of the output, never a key, token
|
|
5
|
+
// or request. To teach it a new situation, add a row to RULES (first match wins, so put the specific ones first).
|
|
6
|
+
|
|
7
|
+
/** The categories the platform understands; anything else it stores as "other". */
|
|
8
|
+
export const RUN_ERROR_CATEGORIES = ['quota', 'rate_limit', 'timeout', 'auth', 'network', 'other'];
|
|
9
|
+
|
|
10
|
+
/** Bytes of output kept per stream while the program runs (the tail only; older output is dropped). */
|
|
11
|
+
export const TAIL_BYTES = 4096;
|
|
12
|
+
|
|
13
|
+
/** "status 402", "HTTP 402", "code: 402", "error 402" or "402 Payment Required" style mentions of one HTTP status. */
|
|
14
|
+
function status(n) {
|
|
15
|
+
return new RegExp(`(?:status(?:\\s*code)?|http|code|error|err)\\D{0,12}\\b${n}\\b|\\b${n}\\b\\s*(?:-|:)?\\s*(?:payment|too many|unauthori|forbidden|insufficient|error|client error)`, 'i');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Ordered rows: [category, short code, patterns]. The short code is a fixed word or the HTTP status, never text from the output.
|
|
20
|
+
* Quota first: a balance message often also mentions "limit" or "401-ish" words.
|
|
21
|
+
*/
|
|
22
|
+
export const RULES = [
|
|
23
|
+
['quota', '402', [
|
|
24
|
+
status(402),
|
|
25
|
+
/insufficient[\s_-]*(?:balance|funds|quota|credits?|account)|(?:balance|quota|credits?)\s*(?:is\s*)?(?:insufficient|exhausted|exceeded|depleted|used up|too low)|out of (?:credits?|quota|balance)|payment required|billing[^\n]{0,30}(?:not active|inactive|failed|required)|exceeded your current quota|余额不足|额度(?:不足|已用完|用完|耗尽)|欠费/i,
|
|
26
|
+
]],
|
|
27
|
+
['rate_limit', '429', [
|
|
28
|
+
status(429),
|
|
29
|
+
/rate[\s_-]*limit|too many requests|requests? per (?:minute|second)|overloaded|限流|请求过于频繁/i,
|
|
30
|
+
]],
|
|
31
|
+
['auth', '401', [
|
|
32
|
+
status(401), status(403),
|
|
33
|
+
/unauthori[sz]ed|invalid[\s_-]*(?:api[\s_-]*)?key|incorrect api key|authentication[\s_-]*(?:failed|error|required)|invalid[\s_-]*token|token (?:expired|has expired)|forbidden|认证失败|密钥(?:无效|错误)/i,
|
|
34
|
+
]],
|
|
35
|
+
['timeout', 'timeout', [
|
|
36
|
+
/timed? ?out|ETIMEDOUT|ESOCKETTIMEDOUT|deadline exceeded|超时/i,
|
|
37
|
+
]],
|
|
38
|
+
['network', 'net', [
|
|
39
|
+
/ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|socket hang up|getaddrinfo|connection (?:refused|reset|error|closed)|network (?:error|is unreachable)|fetch failed|网络(?:错误|异常)/i,
|
|
40
|
+
]],
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Put one ended run down to a category.
|
|
45
|
+
* @param {{code?: number|null, timedOut?: boolean, error?: string, signal?: string|null, tail?: string}} res what the exec helper returned
|
|
46
|
+
* @returns {{broke: boolean, category: string|null, code: string|null}}
|
|
47
|
+
* broke the program did not end in an orderly way (a non-zero exit, killed, timed out, could not start)
|
|
48
|
+
* category the matched category, or null when nothing in the output points at one (a broken run is then "other")
|
|
49
|
+
* code a short token (`402`, `429`, `timeout`, `net`, `exit_1`, `spawn`) or null
|
|
50
|
+
*/
|
|
51
|
+
export function classifyRunEnd(res) {
|
|
52
|
+
const r = res || {};
|
|
53
|
+
const exitCode = r.code == null ? null : Number(r.code);
|
|
54
|
+
const broke = !!r.timedOut || !!r.error || exitCode !== 0;
|
|
55
|
+
const text = String(r.tail || '').slice(-TAIL_BYTES);
|
|
56
|
+
let category = null;
|
|
57
|
+
let code = null;
|
|
58
|
+
if (r.timedOut) { category = 'timeout'; code = 'timeout'; }
|
|
59
|
+
else if (r.error) { category = 'other'; code = 'spawn'; }
|
|
60
|
+
else {
|
|
61
|
+
for (const [cat, short, patterns] of RULES) {
|
|
62
|
+
if (patterns.some((p) => p.test(text))) { category = cat; code = short; break; }
|
|
63
|
+
}
|
|
64
|
+
// the status mentioned decides the short code of the auth row (401 or 403)
|
|
65
|
+
if (category === 'auth' && status(403).test(text) && !status(401).test(text)) code = '403';
|
|
66
|
+
}
|
|
67
|
+
if (broke && !category) {
|
|
68
|
+
category = 'other';
|
|
69
|
+
code = exitCode != null ? `exit_${Math.abs(exitCode) % 1000}` : (r.signal ? 'signal' : 'exit');
|
|
70
|
+
}
|
|
71
|
+
return { broke, category, code };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A bounded tail buffer: keeps the last `max` characters of what is pushed in. */
|
|
75
|
+
export function makeTail(max = TAIL_BYTES) {
|
|
76
|
+
let buf = '';
|
|
77
|
+
return {
|
|
78
|
+
push(chunk) { buf = (buf + String(chunk)).slice(-max); },
|
|
79
|
+
text() { return buf; },
|
|
80
|
+
};
|
|
81
|
+
}
|
package/src/listener/run.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { spawn } from 'node:child_process';
|
|
15
|
-
import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, LISTENER_HEADER } from '../api.js';
|
|
15
|
+
import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, postListenerRunEnd, LISTENER_HEADER } from '../api.js';
|
|
16
16
|
import { readCursor } from '../poll-state.js';
|
|
17
17
|
import { resolveCredDir } from '../profile.js';
|
|
18
18
|
import { CLI_VERSION } from '../client-version.js';
|
|
@@ -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 { classifyRunEnd, makeTail } from './run-error.js'; // v0.38.76: why a run broke off (category only)
|
|
23
24
|
import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
|
|
24
25
|
import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
|
|
25
26
|
import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
|
|
@@ -112,22 +113,28 @@ export function buildRunEnv({ base, cfg, vals, credDir }) {
|
|
|
112
113
|
return env;
|
|
113
114
|
}
|
|
114
115
|
|
|
115
|
-
/** Start the command through the system shell; resolves with {code, timedOut, error
|
|
116
|
+
/** Start the command through the system shell; resolves with {code, timedOut, error?, signal?, tail}. Never rejects. v0.38.76: tail = last few KB of its output, memory only. */
|
|
116
117
|
export function defaultExec({ command, input, env, cwd, timeoutMs }) {
|
|
117
118
|
return new Promise((resolve) => {
|
|
118
119
|
let done = false;
|
|
119
120
|
let timedOut = false;
|
|
120
121
|
let timer = null;
|
|
121
122
|
const finish = (r) => { if (done) return; done = true; if (timer) clearTimeout(timer); resolve(r); };
|
|
123
|
+
const tail = makeTail();
|
|
122
124
|
let child;
|
|
123
125
|
try {
|
|
124
126
|
child = spawn(command, {
|
|
125
|
-
shell: true, env, cwd: cwd || undefined, stdio: ['pipe', '
|
|
127
|
+
shell: true, env, cwd: cwd || undefined, stdio: ['pipe', 'pipe', 'pipe'],
|
|
126
128
|
detached: process.platform !== 'win32', windowsHide: true,
|
|
127
129
|
});
|
|
128
130
|
} catch { return finish({ code: null, timedOut: false, error: 'spawn' }); }
|
|
129
131
|
child.on('error', () => finish({ code: null, timedOut: false, error: 'spawn' }));
|
|
130
|
-
child.on('close', (code) => finish({ code, timedOut }));
|
|
132
|
+
child.on('close', (code, signal) => finish({ code, timedOut, signal: signal || null, tail: tail.text() }));
|
|
133
|
+
for (const st of [child.stdout, child.stderr]) {
|
|
134
|
+
if (!st) continue;
|
|
135
|
+
st.on('data', (d) => tail.push(d));
|
|
136
|
+
st.on('error', () => {});
|
|
137
|
+
}
|
|
131
138
|
child.stdin.on('error', () => { /* the command may not read its input */ });
|
|
132
139
|
try { child.stdin.end(input); } catch { /* same */ }
|
|
133
140
|
timer = setTimeout(() => {
|
|
@@ -165,6 +172,7 @@ export class Listener {
|
|
|
165
172
|
this.shouldStop = d.listenShouldStop || (() => false);
|
|
166
173
|
this.autoCollect = d.autoCollect || autoCollect;
|
|
167
174
|
this.env = d.env || process.env;
|
|
175
|
+
this.runEndOff = false; // v0.38.76: the platform has no run-end route (older version): stop trying
|
|
168
176
|
this.beatOff = false; // v0.37.7 C1: the platform has no beat route (older version): stop trying
|
|
169
177
|
this.installedVersion = d.installedVersion || installedVersionOnDisk;
|
|
170
178
|
this.versionCheckMs = Number(d.versionCheckMs || p.cfg && p.cfg.versionCheckMs) || VERSION_CHECK_MS;
|
|
@@ -238,10 +246,13 @@ export class Listener {
|
|
|
238
246
|
startBeat(sid) {
|
|
239
247
|
const every = this.cfg.beatEveryMs != null ? Number(this.cfg.beatEveryMs) : BEAT_EVERY_MS;
|
|
240
248
|
if (!(every > 0) || this.beatOff) return null;
|
|
249
|
+
const startedAt = this.nowMs();
|
|
241
250
|
const t = setInterval(async () => {
|
|
242
251
|
if (this.beatOff) return;
|
|
243
252
|
try {
|
|
244
|
-
|
|
253
|
+
// v0.38.76: this listener started the program itself and it has not ended: say so, and for how long
|
|
254
|
+
const ageS = Math.max(0, Math.round((this.nowMs() - startedAt) / 1000));
|
|
255
|
+
await postListenerBeat(this.baseUrl, this.credOpts, sid, { fetchImpl: this.fetchImpl, childAlive: true, ageS });
|
|
245
256
|
} catch (e) {
|
|
246
257
|
// 404: an older platform without the route. 403: the platform did not take it for a listener call. Both: stop for good.
|
|
247
258
|
if (e && (e.status === 404 || e.status === 403)) { this.beatOff = true; this.logLine(`beat off status=${e.status}`); }
|
|
@@ -251,6 +262,30 @@ export class Listener {
|
|
|
251
262
|
return t;
|
|
252
263
|
}
|
|
253
264
|
|
|
265
|
+
/**
|
|
266
|
+
* v0.38.76 (Echo 470 step 2): the program of this session ended. Tell the platform (no more "working") and, when it broke
|
|
267
|
+
* off or left an error behind, which CATEGORY it was (quota / rate_limit / timeout / auth / network / other) with a short
|
|
268
|
+
* code. No line of the program output is sent. An older platform without the route is asked once, then left alone.
|
|
269
|
+
* Never throws.
|
|
270
|
+
*/
|
|
271
|
+
async reportRunEnd(sid, res) {
|
|
272
|
+
if (this.runEndOff) return;
|
|
273
|
+
try {
|
|
274
|
+
const r = classifyRunEnd(res);
|
|
275
|
+
const body = { exit_code: res && res.code != null ? Number(res.code) : null, timed_out: !!(res && res.timedOut), category: r.category, code: r.code };
|
|
276
|
+
if (r.broke) this.logLine(`run_end sid=${String(sid).slice(0, 8)} category=${r.category} code=${r.code}`);
|
|
277
|
+
let t;
|
|
278
|
+
try {
|
|
279
|
+
await Promise.race([
|
|
280
|
+
postListenerRunEnd(this.baseUrl, this.credOpts, sid, body, { fetchImpl: this.fetchImpl }),
|
|
281
|
+
new Promise((r) => { t = setTimeout(r, 8000); }),
|
|
282
|
+
]);
|
|
283
|
+
} finally { clearTimeout(t); }
|
|
284
|
+
} catch (e) {
|
|
285
|
+
if (e && (e.status === 404 || e.status === 403)) { this.runEndOff = true; this.logLine(`run_end off status=${e.status}`); }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
254
289
|
/** v0.37.7 C2: note a run that belongs to a hire / task; its usage is read from the local logs while it runs. */
|
|
255
290
|
beginUsage(job, command, jobInfo) {
|
|
256
291
|
try {
|
|
@@ -527,6 +562,7 @@ export class Listener {
|
|
|
527
562
|
for (const t of timers) if (t) clearInterval(t);
|
|
528
563
|
}
|
|
529
564
|
if (urun) await within(this.usage.finish(urun), FINAL_UPLOAD_WAIT_MS);
|
|
565
|
+
await this.reportRunEnd(job.sid, res);
|
|
530
566
|
const ok = res && res.code === 0 && !res.timedOut && !res.error;
|
|
531
567
|
const ms = this.nowMs() - now0;
|
|
532
568
|
const why = !res ? 'spawn' : (res.timedOut ? 'timeout' : (res.error ? 'spawn' : `exit_${res.code}`));
|
|
@@ -601,6 +637,10 @@ export class Listener {
|
|
|
601
637
|
}
|
|
602
638
|
// v0.36: while nothing is running, send new model call records every 10 minutes (no model, nothing spent)
|
|
603
639
|
if (!this.active.size) await this.autoCollect({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, env: this.env, nowMs: this.nowMs() });
|
|
640
|
+
// 2026-11-27: runs whose last usage upload did not get through (network down, restart) are sent again (at most every 5 minutes)
|
|
641
|
+
if (!this.active.size && this.usage && typeof this.usage.backfill === 'function') {
|
|
642
|
+
try { await this.usage.backfill(); } catch { /* never blocks the loop */ }
|
|
643
|
+
}
|
|
604
644
|
const started = this.nowMs();
|
|
605
645
|
let data;
|
|
606
646
|
try {
|
package/src/mt/commands.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
9
10
|
import { authedGetWithRefresh, authedPostWithRefresh, authedPutWithRefresh } from '../api.js';
|
|
10
11
|
import { UPGRADE_COMMAND } from '../client-version.js';
|
|
11
12
|
import { t, MT_HELP } from './text.js';
|
|
@@ -15,6 +16,8 @@ import {
|
|
|
15
16
|
parseScope, parseSince, isZero, localKey, errorCode, SCHEMA, CONTENT_FIELDS,
|
|
16
17
|
} from './collect.js';
|
|
17
18
|
import { cmdSample } from './sample.js';
|
|
19
|
+
import { RECIPES, parseRecipeText, RecipeError } from './recipes.js';
|
|
20
|
+
import { SCHEMA_V2 } from './inrun.js';
|
|
18
21
|
|
|
19
22
|
export { MT_HELP };
|
|
20
23
|
const POLICY_PATH = '/api/v1/agent/model-policy';
|
|
@@ -338,6 +341,10 @@ export function readRecordsFile(text, env) {
|
|
|
338
341
|
});
|
|
339
342
|
}
|
|
340
343
|
let zero = 0;
|
|
344
|
+
// 2026-11-27: collect missing-field skips into a one-line summary.
|
|
345
|
+
// 697 identical lines are unreadable for both Agents and humans.
|
|
346
|
+
let skipCount = 0;
|
|
347
|
+
let firstSkipField = null;
|
|
341
348
|
for (const { o, n: line } of items) {
|
|
342
349
|
if (!o || typeof o !== 'object') { notes.push(t('usage.bad_line', { n: line }, env)); continue; }
|
|
343
350
|
const bad = CONTENT_FIELDS.find((f) => o[f] != null && (typeof o[f] === 'string' || Array.isArray(o[f]) || typeof o[f] === 'object'));
|
|
@@ -350,10 +357,11 @@ export function readRecordsFile(text, env) {
|
|
|
350
357
|
? ['report_id', 'workdir_id', 'summary_period', 'items']
|
|
351
358
|
: ['call_id', 'conversation_id', 'provider', 'model', 'started_at', 'input_tokens', 'output_tokens', 'workdir_id'];
|
|
352
359
|
const miss = need.find((f) => r[f] == null || r[f] === '');
|
|
353
|
-
if (miss) {
|
|
360
|
+
if (miss) { skipCount += 1; if (!firstSkipField) firstSkipField = miss; continue; }
|
|
354
361
|
if (isZero(r)) { zero += 1; continue; }
|
|
355
362
|
rows.push(r);
|
|
356
363
|
}
|
|
364
|
+
if (skipCount) notes.push(t('usage.skipped_summary', { n: skipCount, field: firstSkipField }, env));
|
|
357
365
|
if (zero) notes.push(t('usage.zero_skipped', { n: zero }, env));
|
|
358
366
|
return { rows, notes, forbidden: null };
|
|
359
367
|
}
|
|
@@ -366,14 +374,89 @@ function readFileArg(c) {
|
|
|
366
374
|
}
|
|
367
375
|
}
|
|
368
376
|
|
|
377
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* 2026-11-27: one call of an export file as a usage row of one hire. Self-reported (source agent-converted, reader "export"):
|
|
381
|
+
* the platform shows it as the Agent own word, never as read by the CLI. The call id is the call's own id in the export
|
|
382
|
+
* (message_id), never the file name, so the same call exported again under another name is a duplicate on the platform.
|
|
383
|
+
* The hire is matched by the platform from the time of the call (inside the hire days, the Agent is the hired one).
|
|
384
|
+
*/
|
|
385
|
+
export function exportRow(call, hireId) {
|
|
386
|
+
return {
|
|
387
|
+
schema: SCHEMA_V2,
|
|
388
|
+
granularity: 'call',
|
|
389
|
+
call_id: `export:${call.source_id}`.slice(0, 200),
|
|
390
|
+
conversation_id: 'export',
|
|
391
|
+
provider: String(call.provider || 'unknown').toLowerCase().slice(0, 60),
|
|
392
|
+
model: String(call.model).slice(0, 120),
|
|
393
|
+
started_at: call.started_at,
|
|
394
|
+
input_tokens: call.input_tokens,
|
|
395
|
+
output_tokens: call.output_tokens,
|
|
396
|
+
cache_write_tokens: call.cache_write_tokens || 0,
|
|
397
|
+
cache_read_tokens: call.cache_read_tokens || 0,
|
|
398
|
+
program: 'agent-export',
|
|
399
|
+
reader: 'export',
|
|
400
|
+
attribution: 'run',
|
|
401
|
+
task_ref: { hire_id: hireId, session_id: 'export' },
|
|
402
|
+
source: 'agent-converted',
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** `usage push --file <export.jsonl> --scope hire:<id>`: the file shape `usage sample --from` takes, sent for one hire. */
|
|
407
|
+
async function cmdPushExport(c, recipe, text) {
|
|
408
|
+
const sf = scopeFlag(c);
|
|
409
|
+
if (sf.error || !sf.scope || sf.scope.scope !== 'hire' || !UUID_RE.test(String(sf.scope.id))) {
|
|
410
|
+
return c.fail(2, 'hire_scope_required', t('usage.export_need_hire', {}, c.env));
|
|
411
|
+
}
|
|
412
|
+
const sinceMs = c.flags.since != null ? parseSince(c.flags.since, c.nowMs()) : null;
|
|
413
|
+
if (c.flags.since != null && sinceMs == null) return c.fail(2, 'bad_since', t('usage.bad_since', {}, c.env));
|
|
414
|
+
let parsed;
|
|
415
|
+
try {
|
|
416
|
+
parsed = parseRecipeText(recipe, text, { file: path.basename(String(c.flags.file)), session: null });
|
|
417
|
+
} catch (e) {
|
|
418
|
+
if (e instanceof RecipeError) return c.fail(2, 'recipe_bad_line', t('usage.export_bad_line', { msg: e.message }, c.env));
|
|
419
|
+
throw e;
|
|
420
|
+
}
|
|
421
|
+
const state = readState(c.credOpts);
|
|
422
|
+
const rows = parsed.rows
|
|
423
|
+
.filter((x) => sinceMs == null || x.atMs >= sinceMs)
|
|
424
|
+
.map((x) => exportRow(x, String(sf.scope.id).toLowerCase()))
|
|
425
|
+
.filter((r) => !isZero(r) && !state.sent[localKey(r)]);
|
|
426
|
+
if (!rows.length) {
|
|
427
|
+
if (c.flags.json) c.log(JSON.stringify({ ok: true, sent: null })); else c.log(t('usage.nothing_new', {}, c.env));
|
|
428
|
+
return 0;
|
|
429
|
+
}
|
|
430
|
+
const tot = await sendRows({ baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, rows, state, nowMs: c.nowMs() });
|
|
431
|
+
writeState(c.credOpts, state, c.nowMs());
|
|
432
|
+
if (c.flags.json) {
|
|
433
|
+
c.log(JSON.stringify({ ok: !tot.error, sent: { ...tot, error: tot.error ? String(tot.error.message || tot.error) : null } }));
|
|
434
|
+
} else if (tot.featureOff) {
|
|
435
|
+
c.log(t('usage.feature_off', {}, c.env));
|
|
436
|
+
} else {
|
|
437
|
+
if (tot.total) for (const l of describeSend(tot, c.env)) c.log(l);
|
|
438
|
+
if (tot.error) c.err(t('usage.send_failed', { msg: tot.error.message || String(tot.error) }, c.env));
|
|
439
|
+
}
|
|
440
|
+
return tot.error ? 1 : 0;
|
|
441
|
+
}
|
|
442
|
+
|
|
369
443
|
async function cmdPush(c) {
|
|
370
444
|
if (!c.flags.file) return c.fail(2, 'file_required', t('usage.need_file', {}, c.env));
|
|
371
445
|
const f = readFileArg(c);
|
|
372
446
|
if (f.error) return c.fail(2, 'read_failed', f.error);
|
|
447
|
+
// 2026-11-27: an export file (a runtime with no local log) goes through the same recipe as the job-seeking check
|
|
448
|
+
const exportRecipe = RECIPES.find((r) => r.sniff && r.sniff(String(f.text || '').slice(0, 65536)));
|
|
449
|
+
if (exportRecipe) return cmdPushExport(c, exportRecipe, f.text);
|
|
373
450
|
const got = readRecordsFile(f.text, c.env);
|
|
374
451
|
if (got.forbidden) return c.fail(2, 'mt_content_forbidden', got.forbidden);
|
|
375
452
|
if (!c.flags.json) for (const l of got.notes) c.err(l);
|
|
376
|
-
|
|
453
|
+
// 2026-11-27: all-skipped (e.g. wrong file format) exits 1 so the Agent knows nothing was sent
|
|
454
|
+
if (!got.rows.length) {
|
|
455
|
+
const allSkipped = got.notes.some((n) => /skipped_summary|skipped/.test(n));
|
|
456
|
+
if (c.flags.json) c.log(JSON.stringify({ ok: !allSkipped, sent: null, notes: got.notes }));
|
|
457
|
+
else { for (const l of got.notes) c.err(l); c.log(t('usage.nothing_new', {}, c.env)); }
|
|
458
|
+
return allSkipped ? 1 : 0;
|
|
459
|
+
}
|
|
377
460
|
const state = readState(c.credOpts);
|
|
378
461
|
const tot = await sendRows({ baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, rows: got.rows, state, nowMs: c.nowMs() });
|
|
379
462
|
if (!tot.error && !tot.featureOff) await noteRecordMode({ baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, state, tot });
|
package/src/mt/inrun.js
CHANGED
|
@@ -12,6 +12,12 @@
|
|
|
12
12
|
// `attribution`: `run` (turn of one number: priced) or `window` (could not be told apart: shown, not priced).
|
|
13
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
14
|
// Nothing here sends prompts, answers or file contents; only numbers, model names, times and ids.
|
|
15
|
+
//
|
|
16
|
+
// 2026-11-27: every recipe with an outside-input rule (recipes.js, e.g. Antigravity) is read here too, through the same event list,
|
|
17
|
+
// so a program added as a recipe for the job-seeking check is also read while it works (before, only the five hand-written readers
|
|
18
|
+
// were listed and an Antigravity hire stayed at 0). A run whose last upload did not get through (network down, listener restarted)
|
|
19
|
+
// is kept in the local state (`pending_runs`) and sent again by `backfill()` from the idle loop; the platform and the local `sent`
|
|
20
|
+
// list de-duplicate, so nothing is counted twice.
|
|
15
21
|
|
|
16
22
|
import os from 'node:os';
|
|
17
23
|
import path from 'node:path';
|
|
@@ -19,12 +25,16 @@ import { readMsgLog, readRollout, readDshLog, readSessionModelUsage, readRunLog,
|
|
|
19
25
|
import { readState, writeState, sendRows, sha256, isZero, localKey } from './collect.js';
|
|
20
26
|
import { readRegistry, workdirForPath } from './workdirs.js';
|
|
21
27
|
import { attributeEvents } from './wake-attribution.js';
|
|
28
|
+
import { liveRecipes, readRecipeEvents, recipeProgramOf } from './recipes.js';
|
|
22
29
|
|
|
23
30
|
export const SCHEMA_V2 = 'anytowork.usage.v2';
|
|
24
31
|
export const INRUN_DEFAULT_SEC = 60; // MT_INRUN_UPLOAD_SEC default (the platform sends `inrun_upload_sec` in listener.limits)
|
|
25
32
|
const START_SLACK_MS = 5000; // a session / log line may be stamped a little before the start we noted
|
|
26
33
|
const SETTLE_MS = 60_000; // a call seen less than this long ago may still be streaming into the log
|
|
27
34
|
const KEEP_FINISHED_MS = 10 * 60 * 1000; // finished runs stay known this long
|
|
35
|
+
const PENDING_KEEP_MS = 48 * 3600 * 1000; // a run not confirmed sent is tried again this long (the platform takes late rows for 72 h)
|
|
36
|
+
const BACKFILL_EVERY_MS = 5 * 60 * 1000; // the idle loop tries the re-send at most this often
|
|
37
|
+
const PENDING_MAX = 200; // runs kept for a re-send (the oldest go first)
|
|
28
38
|
|
|
29
39
|
/** The reference a row carries: the wake-up number found in the prompt (the platform derives the hire / task from it). */
|
|
30
40
|
export function buildTaskRef({ sid, wakeId, segment, basis, wakeIds }) {
|
|
@@ -65,10 +75,17 @@ export function programOfCommand(command) {
|
|
|
65
75
|
if (b === 'claude') return 'claude_code';
|
|
66
76
|
if (b === 'codex') return 'codex';
|
|
67
77
|
if (b === 'dsh') return 'dsh';
|
|
78
|
+
const viaRecipe = recipeProgramOf(b);
|
|
79
|
+
if (viaRecipe) return viaRecipe;
|
|
68
80
|
}
|
|
69
81
|
return null;
|
|
70
82
|
}
|
|
71
83
|
|
|
84
|
+
/** The local key of a run (its session and wake-up numbers): the same run gives the same key in any process. */
|
|
85
|
+
function runKey(sid, wakeIds) {
|
|
86
|
+
return sha256(`${sid}|${[...wakeIds].sort().join(',')}`).slice(0, 24);
|
|
87
|
+
}
|
|
88
|
+
|
|
72
89
|
function callRow(c, ctx) {
|
|
73
90
|
const row = {
|
|
74
91
|
schema: SCHEMA_V2,
|
|
@@ -130,10 +147,69 @@ export class RunUsageTracker {
|
|
|
130
147
|
cum: new Map(), // `session|model` -> totals already sent
|
|
131
148
|
sentAny: false,
|
|
132
149
|
};
|
|
150
|
+
r.key = runKey(sid, ids);
|
|
133
151
|
this.runs.push(r);
|
|
152
|
+
if (ids.size) this.#queue(() => this.#remember(r));
|
|
134
153
|
return r;
|
|
135
154
|
}
|
|
136
155
|
|
|
156
|
+
#queue(fn) {
|
|
157
|
+
const next = this.chain.then(fn).catch(() => null);
|
|
158
|
+
this.chain = next;
|
|
159
|
+
return next;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Note the run in the local state until its last upload got through, so another process can send it later. */
|
|
163
|
+
#remember(r) {
|
|
164
|
+
const state = readState(this.credOpts);
|
|
165
|
+
const pend = state.pending_runs && typeof state.pending_runs === 'object' ? state.pending_runs : {};
|
|
166
|
+
pend[r.key] = { sid: r.sid, wake_ids: [...r.wakeIds], start_ms: r.startMs, tokens: r.tokens, prog: r.prog };
|
|
167
|
+
const keys = Object.keys(pend).sort((a, b) => (pend[a].start_ms || 0) - (pend[b].start_ms || 0));
|
|
168
|
+
while (keys.length > PENDING_MAX) delete pend[keys.shift()];
|
|
169
|
+
state.pending_runs = pend;
|
|
170
|
+
writeState(this.credOpts, state, this.nowMs());
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Called by the idle loop: send again every run whose last upload did not get through (network down, the listener
|
|
175
|
+
* restarted or was upgraded in between). Runs still working in this process are left alone; runs older than two days are
|
|
176
|
+
* dropped. Returns {runs} = runs sent through this time.
|
|
177
|
+
*/
|
|
178
|
+
backfill({ force = false } = {}) {
|
|
179
|
+
const now = this.nowMs();
|
|
180
|
+
if (this.off) return Promise.resolve({ runs: 0 });
|
|
181
|
+
if (!force && this.lastBackfillMs != null && now - this.lastBackfillMs < BACKFILL_EVERY_MS) return Promise.resolve({ runs: 0, skipped: true });
|
|
182
|
+
this.lastBackfillMs = now;
|
|
183
|
+
return this.#queue(() => this.#backfill(now)).then((x) => x || { runs: 0 });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #backfill(now) {
|
|
187
|
+
const state = readState(this.credOpts);
|
|
188
|
+
const pend = state.pending_runs && typeof state.pending_runs === 'object' ? state.pending_runs : {};
|
|
189
|
+
const working = new Set(this.runs.filter((x) => x.endMs == null).map((x) => x.key));
|
|
190
|
+
const todo = [];
|
|
191
|
+
let changed = false;
|
|
192
|
+
for (const [k, p] of Object.entries(pend)) {
|
|
193
|
+
if (working.has(k)) continue;
|
|
194
|
+
const ok = p && Number.isFinite(Number(p.start_ms)) && Array.isArray(p.wake_ids) && p.wake_ids.length;
|
|
195
|
+
if (!ok || now - Number(p.start_ms) > PENDING_KEEP_MS) { delete pend[k]; changed = true; continue; }
|
|
196
|
+
todo.push([k, p]);
|
|
197
|
+
}
|
|
198
|
+
if (changed) { state.pending_runs = pend; writeState(this.credOpts, state, now); }
|
|
199
|
+
let runs = 0;
|
|
200
|
+
for (const [k, p] of todo) {
|
|
201
|
+
const r = {
|
|
202
|
+
seq: 0, key: k, sid: p.sid, startMs: Number(p.start_ms), endMs: now,
|
|
203
|
+
wakeIds: new Set(p.wake_ids.map((x) => String(x).toLowerCase())),
|
|
204
|
+
tokens: Array.isArray(p.tokens) ? p.tokens : [], prog: p.prog || null, cum: new Map(), sentAny: false,
|
|
205
|
+
};
|
|
206
|
+
const res = await this.#upload(r, true);
|
|
207
|
+
if (res && res.ok) runs += 1;
|
|
208
|
+
if (this.off) break;
|
|
209
|
+
}
|
|
210
|
+
return { runs };
|
|
211
|
+
}
|
|
212
|
+
|
|
137
213
|
/** Queue one upload of what the run has so far (`final`: the run ended, no settle time). */
|
|
138
214
|
upload(r, { final = false } = {}) {
|
|
139
215
|
const next = this.chain.then(() => this.#upload(r, final)).catch(() => null);
|
|
@@ -175,6 +251,8 @@ export class RunUsageTracker {
|
|
|
175
251
|
tag(() => readDshLog({ home, env, sinceMs: since, log: this.log }), 'dsh', 'cli:dsh_log'),
|
|
176
252
|
tag(() => readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log }), 'hermes', 'cli:session_model_usage'),
|
|
177
253
|
tag(() => readTranscriptUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log }), 'openclaw', 'cli:transcript_db'),
|
|
254
|
+
// every recipe with an outside-input rule (no per-program code here)
|
|
255
|
+
...liveRecipes().map((rc) => tag(() => readRecipeEvents(rc, { home, sinceMs: since }), rc.program || rc.id, `cli:recipe:${rc.id}`)),
|
|
178
256
|
]);
|
|
179
257
|
const { rows: owned, dropped } = attributeEvents(events);
|
|
180
258
|
for (const o of owned) {
|
|
@@ -246,10 +324,12 @@ export class RunUsageTracker {
|
|
|
246
324
|
fresh.push(row);
|
|
247
325
|
}
|
|
248
326
|
if (final) markSummariesSent(state, heldSessions);
|
|
249
|
-
|
|
327
|
+
const settled = () => { if (final && state.pending_runs && r.key) delete state.pending_runs[r.key]; };
|
|
328
|
+
if (!fresh.length) { settled(); if (final || nDropped) writeState(this.credOpts, state, now); return { sent: 0, dropped, ok: true }; }
|
|
250
329
|
const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
|
|
251
|
-
if (tot.featureOff) this.off = true;
|
|
330
|
+
if (tot.featureOff) { this.off = true; settled(); }
|
|
252
331
|
if (!tot.error && !tot.featureOff) {
|
|
332
|
+
settled();
|
|
253
333
|
if (fresh.some((x) => x.reader === 'cli:transcript_db')) {
|
|
254
334
|
// remembered across rounds (and restarts): a later round that cannot read the transcript must not add the run total
|
|
255
335
|
state.perCallReported = state.perCallReported || {};
|
|
@@ -261,7 +341,7 @@ export class RunUsageTracker {
|
|
|
261
341
|
this.log(`usage: uploaded ${fresh.length} rows wake=${[...r.wakeIds].join(",") || "-"}`);
|
|
262
342
|
}
|
|
263
343
|
writeState(this.credOpts, state, now);
|
|
264
|
-
return { sent: fresh.length, tot, dropped };
|
|
344
|
+
return { sent: fresh.length, tot, dropped, ok: !tot.error && !tot.featureOff };
|
|
265
345
|
}
|
|
266
346
|
}
|
|
267
347
|
|
package/src/mt/recipes.js
CHANGED
|
@@ -25,8 +25,15 @@
|
|
|
25
25
|
// file name or folder walk: it is used only for a single --from file whose first line passes sniff
|
|
26
26
|
// strictLines (optional) every non-empty line must be a JSON object; anything else is refused, never skipped
|
|
27
27
|
// dedupeRequired (optional) a matching line without the dedupeKey value is refused
|
|
28
|
+
// program (optional) the program name sent with in-run usage rows (defaults to id)
|
|
29
|
+
// commands (optional) start-command words that name this program (`agy` -> antigravity) for the always-on listener
|
|
30
|
+
// input (optional) {lineFilter, text, time}: which lines are a message from OUTSIDE the Agent (the person / the
|
|
31
|
+
// platform wake-up). With it the recipe also gives the shared event list of wake-attribution.js, so the
|
|
32
|
+
// usage of work done while hired is read live by the always-on listener (inrun.js) with no other code.
|
|
33
|
+
// Without it the recipe is only used by the job-seeking check (and never priced during work).
|
|
28
34
|
//
|
|
29
|
-
// Adding an Agent: append one object to RECIPES. No other file changes
|
|
35
|
+
// Adding an Agent: append one object to RECIPES. No other file changes (the job-seeking check, the in-run upload of the
|
|
36
|
+
// always-on listener and its later re-send all read RECIPES).
|
|
30
37
|
|
|
31
38
|
import fs from "node:fs";
|
|
32
39
|
import os from "node:os";
|
|
@@ -54,6 +61,11 @@ export const RECIPES = [
|
|
|
54
61
|
required: ["model", "time", "input", "output"],
|
|
55
62
|
modelSuffixes: ["-low", "-medium", "-high", "-xhigh", "-sonar", "-tiered"],
|
|
56
63
|
sessionFrom: "dir",
|
|
64
|
+
// 2026-11-27: the prompt the listener hands over (it ends with the wake-up number) is the one USER_INPUT line of a run.
|
|
65
|
+
// System lines (SYSTEM_SDK / SYSTEM) and model replies (MODEL GENERIC) are never read for a number.
|
|
66
|
+
program: "antigravity",
|
|
67
|
+
commands: ["agy", "antigravity"],
|
|
68
|
+
input: { lineFilter: { source: "USER_EXPLICIT", type: "USER_INPUT" }, text: "content", time: "created_at" },
|
|
57
69
|
},
|
|
58
70
|
// v0.38.71: a file an Agent exported by hand (its usage lives in a runtime database, not in a local log). One JSON object
|
|
59
71
|
// per line: message_id (the call, written twice keeps the last), model, input_tokens, output_tokens, created_at (unix
|
|
@@ -230,6 +242,7 @@ function rowOf(recipe, obj, entry, lineNo) {
|
|
|
230
242
|
const id = isEmpty(step) ? path.basename(entry.file) + ":" + lineNo : String(step);
|
|
231
243
|
return {
|
|
232
244
|
call_id: (entry.session || path.basename(entry.file)) + ":" + id,
|
|
245
|
+
source_id: isEmpty(step) ? null : String(step), // the call's own id in the log (message_id / step), null when it has none
|
|
233
246
|
conversation_id: entry.session || null,
|
|
234
247
|
provider: guessProvider(model),
|
|
235
248
|
model,
|
|
@@ -262,12 +275,8 @@ function walk(dir, root, depth, out, recipe, sinceMs) {
|
|
|
262
275
|
}
|
|
263
276
|
}
|
|
264
277
|
|
|
265
|
-
/**
|
|
266
|
-
|
|
267
|
-
* { found, calls, files, lines, models, sample, client }. Throws RecipeError when a matching line is broken.
|
|
268
|
-
*/
|
|
269
|
-
export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, roots = null } = {}) {
|
|
270
|
-
checkRecipe(recipe);
|
|
278
|
+
/** The files a recipe reads: `roots` overrides the recipe folders (used by --from). */
|
|
279
|
+
function recipeFiles(recipe, { home = os.homedir(), sinceMs = 0, roots = null } = {}) {
|
|
271
280
|
const baseRoots = roots || expandRoots(recipe, home);
|
|
272
281
|
const files = [];
|
|
273
282
|
const seenFiles = new Set();
|
|
@@ -288,41 +297,80 @@ export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, root
|
|
|
288
297
|
files.push(f);
|
|
289
298
|
}
|
|
290
299
|
}
|
|
291
|
-
|
|
292
|
-
|
|
300
|
+
return files;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function textOf(v) {
|
|
304
|
+
if (v == null) return "";
|
|
305
|
+
return typeof v === "string" ? v : JSON.stringify(v);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Parse the text of one log file with a recipe. `entry` = {file, session}. Returns {rows, inputs, lines}:
|
|
310
|
+
* rows = one per call (a step written again keeps the last line), inputs = outside messages {ms, text} (only with
|
|
311
|
+
* `withInputs` and a recipe that has an `input` rule). Throws RecipeError when a matching call line is broken.
|
|
312
|
+
*/
|
|
313
|
+
export function parseRecipeText(recipe, text, entry, { withInputs = false } = {}) {
|
|
314
|
+
checkRecipe(recipe);
|
|
315
|
+
const inputRule = withInputs && recipe.input ? recipe.input : null;
|
|
293
316
|
// a line that cannot match need not be parsed: every matching line holds the first filter value somewhere
|
|
294
317
|
const needle = String(Object.values(recipe.lineFilter || {})[0] || "");
|
|
318
|
+
const inNeedle = inputRule ? String(Object.values(inputRule.lineFilter || {})[0] || "") : "";
|
|
319
|
+
const rows = [];
|
|
320
|
+
const inputs = [];
|
|
321
|
+
const at = new Map();
|
|
322
|
+
let lines = 0;
|
|
323
|
+
const list = String(text == null ? "" : text).split("\n");
|
|
324
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
325
|
+
const raw = list[i];
|
|
326
|
+
if (recipe.strictLines && raw.trim() === "") continue;
|
|
327
|
+
if (!raw || (!recipe.strictLines && raw[0] !== "{")) continue;
|
|
328
|
+
const maybeCall = !needle || raw.indexOf(needle) !== -1;
|
|
329
|
+
const maybeInput = !!inputRule && (!inNeedle || raw.indexOf(inNeedle) !== -1);
|
|
330
|
+
if (!maybeCall && !maybeInput) continue;
|
|
331
|
+
let obj;
|
|
332
|
+
try { obj = JSON.parse(raw); } catch {
|
|
333
|
+
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON line");
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
337
|
+
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON object");
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (maybeInput && matchesFilter(inputRule, obj)) {
|
|
341
|
+
// an outside message with no usable time carries no number (its calls are then not taken), never an error
|
|
342
|
+
const ms = toMs(fieldOf(obj, inputRule.time || recipe.fields.time));
|
|
343
|
+
if (ms != null) inputs.push({ ms, text: textOf(fieldOf(obj, inputRule.text || "content")) });
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (!maybeCall || !matchesFilter(recipe, obj)) continue;
|
|
347
|
+
lines += 1;
|
|
348
|
+
const row = rowOf(recipe, obj, entry, i + 1);
|
|
349
|
+
const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
|
|
350
|
+
const key = isEmpty(step) ? entry.file + ":" + (i + 1) : entry.file + ":" + String(step);
|
|
351
|
+
if (at.has(key)) rows[at.get(key)] = row; // a step written again: the last line wins
|
|
352
|
+
else { at.set(key, rows.length); rows.push(row); }
|
|
353
|
+
}
|
|
354
|
+
return { rows, inputs, lines };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Read one recipe. `roots` overrides the recipe folders (used by --from). Returns
|
|
359
|
+
* { found, calls, files, lines, models, sample, client }. Throws RecipeError when a matching line is broken.
|
|
360
|
+
*/
|
|
361
|
+
export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, roots = null } = {}) {
|
|
362
|
+
checkRecipe(recipe);
|
|
363
|
+
const files = recipeFiles(recipe, { home, sinceMs, roots });
|
|
364
|
+
const calls = [];
|
|
365
|
+
const models = new Set();
|
|
295
366
|
let lines = 0;
|
|
296
367
|
let sample = null;
|
|
297
368
|
for (const entry of files) {
|
|
298
369
|
let text;
|
|
299
370
|
try { text = fs.readFileSync(entry.file, "utf8"); } catch { continue; }
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
const
|
|
303
|
-
for (let i = 0; i < list.length; i += 1) {
|
|
304
|
-
const raw = list[i];
|
|
305
|
-
if (recipe.strictLines && raw.trim() === "") continue;
|
|
306
|
-
if (!raw || (!recipe.strictLines && raw[0] !== "{")) continue;
|
|
307
|
-
if (needle && raw.indexOf(needle) === -1) continue;
|
|
308
|
-
let obj;
|
|
309
|
-
try { obj = JSON.parse(raw); } catch {
|
|
310
|
-
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON line");
|
|
311
|
-
continue;
|
|
312
|
-
}
|
|
313
|
-
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
314
|
-
if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON object");
|
|
315
|
-
continue;
|
|
316
|
-
}
|
|
317
|
-
if (!matchesFilter(recipe, obj)) continue;
|
|
318
|
-
lines += 1;
|
|
319
|
-
const row = rowOf(recipe, obj, entry, i + 1);
|
|
320
|
-
const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
|
|
321
|
-
const key = isEmpty(step) ? entry.file + ":" + (i + 1) : entry.file + ":" + String(step);
|
|
322
|
-
if (at.has(key)) rows[at.get(key)] = row; // a step written again: the last line wins
|
|
323
|
-
else { at.set(key, rows.length); rows.push(row); }
|
|
324
|
-
}
|
|
325
|
-
for (const row of rows) {
|
|
371
|
+
const p = parseRecipeText(recipe, text, entry);
|
|
372
|
+
lines += p.lines;
|
|
373
|
+
for (const row of p.rows) {
|
|
326
374
|
calls.push(row);
|
|
327
375
|
models.add(row.model);
|
|
328
376
|
if (!sample) sample = row;
|
|
@@ -342,6 +390,47 @@ export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, root
|
|
|
342
390
|
};
|
|
343
391
|
}
|
|
344
392
|
|
|
393
|
+
/**
|
|
394
|
+
* 2026-11-27: one recipe as the shared event list of wake-attribution.js (what the hand-written readers give), so the
|
|
395
|
+
* always-on listener reads the usage of work done while hired with the same recipe the job-seeking check uses.
|
|
396
|
+
* Returns {calls, events, files, refused}. A recipe without an `input` rule gives no events (nothing can be attributed).
|
|
397
|
+
* A file with a broken call line is left out whole (counted in `refused`, never read as 0) and never blocks the others.
|
|
398
|
+
*/
|
|
399
|
+
export function readRecipeEvents(recipe, { home = os.homedir(), sinceMs = 0, roots = null } = {}) {
|
|
400
|
+
checkRecipe(recipe);
|
|
401
|
+
const files = recipeFiles(recipe, { home, sinceMs, roots });
|
|
402
|
+
const calls = [];
|
|
403
|
+
const events = [];
|
|
404
|
+
let refused = 0;
|
|
405
|
+
for (const entry of files) {
|
|
406
|
+
let text;
|
|
407
|
+
try { text = fs.readFileSync(entry.file, "utf8"); } catch { continue; }
|
|
408
|
+
let p;
|
|
409
|
+
try { p = parseRecipeText(recipe, text, entry, { withInputs: true }); } catch (e) {
|
|
410
|
+
if (e instanceof RecipeError) { refused += 1; continue; }
|
|
411
|
+
throw e;
|
|
412
|
+
}
|
|
413
|
+
const session = entry.session || entry.file;
|
|
414
|
+
for (const row of p.rows) calls.push(row);
|
|
415
|
+
if (!recipe.input) continue;
|
|
416
|
+
for (const inp of p.inputs) events.push({ kind: "input", session, ms: inp.ms, text: inp.text });
|
|
417
|
+
for (const row of p.rows) events.push({ kind: "call", session, ms: row.atMs, call: row });
|
|
418
|
+
}
|
|
419
|
+
return { calls, events, files: files.length, refused };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Recipes the always-on listener reads while an Agent works: a default folder and an outside-input rule. */
|
|
423
|
+
export function liveRecipes() {
|
|
424
|
+
return RECIPES.filter((r) => !r.sniff && (r.roots || []).length && r.input);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** The program a start-command word names through a recipe (`agy` -> "antigravity"), or null. */
|
|
428
|
+
export function recipeProgramOf(word) {
|
|
429
|
+
const w = String(word || "").toLowerCase();
|
|
430
|
+
const r = RECIPES.find((x) => (x.commands || []).includes(w));
|
|
431
|
+
return r ? (r.program || r.id) : null;
|
|
432
|
+
}
|
|
433
|
+
|
|
345
434
|
/** A --from path that belongs to a recipe, or null. Checked before the hand-written path shapes. */
|
|
346
435
|
export function recipeForPath(abs, st) {
|
|
347
436
|
if (!st) return null;
|
package/src/mt/text.js
CHANGED
|
@@ -94,6 +94,11 @@ const TEXT = {
|
|
|
94
94
|
'usage.send_failed': { zh: '上传没有完成({msg}),下次会自动补传。', en: 'Sending did not finish ({msg}); it will be retried next time.' },
|
|
95
95
|
'usage.upgrade': { zh: '建议升级命令行到 {min} 或更高:{cmd}', en: 'Please upgrade the CLI to {min} or later: {cmd}' },
|
|
96
96
|
'usage.need_file': { zh: '缺少文件:anytowork usage push --file <records.jsonl>', en: 'File missing: anytowork usage push --file <records.jsonl>' },
|
|
97
|
+
'usage.export_need_hire': {
|
|
98
|
+
zh: '这是导出的用量文件,要说明算在哪一单:anytowork usage push --file <文件> --scope hire:<招聘编号>',
|
|
99
|
+
en: 'This is an exported usage file; say which hire it belongs to: anytowork usage push --file <file> --scope hire:<hire id>',
|
|
100
|
+
},
|
|
101
|
+
'usage.export_bad_line': { zh: '文件里有一行读不了,整份没有上传:{msg}', en: 'A line of the file cannot be read; nothing was sent: {msg}' },
|
|
97
102
|
'usage.read_failed': { zh: '读不了这个文件:{msg}', en: 'Cannot read the file: {msg}' },
|
|
98
103
|
'usage.bad_line': { zh: '第 {n} 行不是合法 JSON,已跳过。', en: 'Line {n} is not valid JSON; skipped.' },
|
|
99
104
|
'usage.content_forbidden': {
|
|
@@ -101,6 +106,8 @@ const TEXT = {
|
|
|
101
106
|
en: 'Line {n} carries a content field ({field}). Send metadata only: model, token counts, times, call id; never prompts or answers. Nothing was sent.',
|
|
102
107
|
},
|
|
103
108
|
'usage.missing_field': { zh: '第 {n} 行缺少 {field},已跳过。', en: 'Line {n} has no {field}; skipped.' },
|
|
109
|
+
// 2026-11-27: aggregate skips into one line instead of one-per-row
|
|
110
|
+
'usage.skipped_summary': { zh: '{n} 行因缺少 {field} 被跳过,请确认文件格式正确(usage sample 的导出格式请用 anytowork usage sample --from)。', en: '{n} rows skipped (missing {field}). To send a session-export file, use: anytowork usage sample --from <file>.' },
|
|
104
111
|
'usage.zero_skipped': { zh: '{n} 行 token 全为 0,没有上传。', en: '{n} lines had all token counts at 0 and were not sent.' },
|
|
105
112
|
'usage.bad_scope': { zh: '--scope 写法是 task:<任务编号> 或 hire:<招聘编号>。', en: '--scope is task:<task id> or hire:<hire id>.' },
|
|
106
113
|
'usage.bad_since': { zh: '--since 写法是时间(2026-11-16T08:00:00Z)或时长(30m、6h、3d)。', en: '--since is a time (2026-11-16T08:00:00Z) or a duration (30m, 6h, 3d).' },
|
|
@@ -225,6 +232,9 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
|
|
|
225
232
|
/ read the usual log files on this computer and send the calls made inside work folders
|
|
226
233
|
usage push --file <records.jsonl> 读不了本机日志时,让你的 Agent 按标准格式(anytowork.usage.v1)自己转换后上传
|
|
227
234
|
/ send records your Agent converted to the standard format itself
|
|
235
|
+
usage push --file <导出文件.jsonl> --scope hire:<招聘编号>
|
|
236
|
+
用量在运行环境里、本机没有日志时:把和求职检查同样格式的导出文件算到这一单(算 Agent 自报)
|
|
237
|
+
/ no local log: send the same export file the job-seeking check takes for this hire (self-reported)
|
|
228
238
|
usage check [--scope ...] [--file <records.jsonl>]
|
|
229
239
|
本机先查一遍(重复的调用编号、时间与数字),再对照平台上的结果
|
|
230
240
|
/ check locally (repeated call ids, times, numbers), then compare with the platform
|
package/src/wb-rules-text.js
CHANGED
|
@@ -23,8 +23,8 @@ export const WB_RULES_TEXT = {
|
|
|
23
23
|
},
|
|
24
24
|
// Extra paragraph for a hired Agent: full once per session, short afterwards.
|
|
25
25
|
"wb.rules.hire": {
|
|
26
|
-
zh: "
|
|
27
|
-
en: "You were hired: the platform reads your usage by itself, so you do not need to report it; if it cannot read it, it will tell you, and then
|
|
26
|
+
zh: "你是被聘来的:用量由平台自动读取,不用另外报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:{hire_id},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:{hire_id}。干着活隔一会儿补一次。叫醒里会写今日剩余额度(百分比);剩余额度不足时先告诉主人,再接大活。",
|
|
27
|
+
en: "You were hired: the platform reads your usage by itself, so you do not need to report it; if it cannot read it, it will tell you, and then report once: with a local log use anytowork usage push --file <log file> --scope hire:{hire_id}; with no local log (a cloud runtime) use anytowork usage sample --from <exported file> --scope hire:{hire_id}. Report every so often as you work. Each wake-up states your remaining quota for today in percent; when it is low, tell your owner first, then take on big work.",
|
|
28
28
|
},
|
|
29
29
|
"wb.rules.hire.short": {
|
|
30
30
|
zh: "用量平台自动读。",
|