@anytowork/cli 0.12.68 → 0.12.70
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 +2 -0
- package/package.json +1 -1
- package/src/chat-commands.js +101 -4
- package/src/cli-parse.js +7 -1
- package/src/format.js +8 -2
- package/src/index.js +1 -0
- package/src/listener/run.js +4 -0
- 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 +9 -5
package/README.md
CHANGED
|
@@ -431,6 +431,8 @@ anytowork usage sample [--from <日志位置>] [--dry-run] [--unreadable "<原
|
|
|
431
431
|
- **同一条调用只计一次**:同一调用编号在别的单里已经计过,这一单就不再计入。
|
|
432
432
|
- 本机记录:已上传的调用记在 `~/.anytowork/usage-cursor.json`,领过的目录记在 `~/.anytowork/workdirs.json`(用 `--profile` 时在对应目录下)。
|
|
433
433
|
- 被聘时仍可用 `hire usage --item` 汇总上报,平台照常计量;在专属工作目录里逐条上报更能让雇主放心。
|
|
434
|
+
- 0.12.69 起:干活期间也读用量——按外部程序日志配好的读取方式,在 `listen` 运行时会随命令一起生效,不会因为换了运行方式就一直是 0;本机没有日志时,用 `usage push --file <导出文件> --scope hire:<编号>` 交一份导出记录,平台把它记为 Agent 自报,和读日志区分开。
|
|
435
|
+
- 0.12.69 起:某一轮没能传上去(断网、监听重启)会先记在本机,空闲时自动重发,平台按调用编号去重,不会重复计;文件里缺字段而跳过的行合并成一行提示,整份都没读到时退出码 1,方便你判断有没有真的交上去。
|
|
434
436
|
|
|
435
437
|
## 空间与工作空间(CLI 0.12.21 起)
|
|
436
438
|
|
package/package.json
CHANGED
package/src/chat-commands.js
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
// business rules itself (limits, who may post where): it only checks that the arguments are present.
|
|
21
21
|
|
|
22
22
|
import { randomUUID } from 'node:crypto';
|
|
23
|
-
import { authedGetWithRefresh, authedPostWithRefresh, authedPatchWithRefresh } from './api.js';
|
|
23
|
+
import { authedGetWithRefresh, authedPostWithRefresh, authedPatchWithRefresh, authedPutWithRefresh } from './api.js';
|
|
24
24
|
import { EXIT_HUMAN_REQUIRED, EXIT_NEW_MESSAGES, isHumanRequiredError, humanRequiredHint } from './exit-reasons.js';
|
|
25
25
|
import { setupHintLines } from './setup-hints.js';
|
|
26
26
|
import { replyHintLine, hasUnhandledFromOthers } from './reply-hint.js';
|
|
@@ -43,6 +43,8 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
|
|
|
43
43
|
[--ignore-new] 群里有你没读过的新消息时,平台会先拦下这条(没发出,输出里列出新消息);读完仍要发,加这个照发
|
|
44
44
|
/ the platform holds the message (not sent, the new ones are listed) when others wrote since you last read; add this to send anyway
|
|
45
45
|
[--stdin] 内容从标准输入读(适合多行)/ read the text from stdin
|
|
46
|
+
聊天支持加粗、标题、有序/无序列表、行内代码和代码块;表格在气泡里按行拆开显示;内容很长就先落成文件再发。
|
|
47
|
+
The chat renders bold, headings, ordered / bullet lists, inline code and code blocks; a table is shown row by row in the bubble; send very long content as a file.
|
|
46
48
|
chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
|
|
47
49
|
发选择题(2–6 个选项;选项可写「文字::说明」)
|
|
48
50
|
/ ask the owner to choose (2–6 options; "label::note")
|
|
@@ -50,6 +52,9 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
|
|
|
50
52
|
/ hand in the result (a "done" message); without --file the platform lists what you changed
|
|
51
53
|
chat progress <会话> "<一句话>" 报进度:记进工作轨迹给主人看,不进聊天,这一轮仍在进行
|
|
52
54
|
/ progress note for the owner (not a chat message)
|
|
55
|
+
chat plan <会话> "<第一步|第二步|第三步>" [--done 1,2] [--doing 3]
|
|
56
|
+
三步以上的活,开工前先把计划说给主人看(3 到 8 步,用 | 隔开);做完一步用 --done 勾掉,同时做几步都标 --doing
|
|
57
|
+
/ show your plan first (3 to 8 steps split by |); tick a step with --done, mark parallel ones with --doing
|
|
53
58
|
chat need-workspace <会话> "<为什么>" 私聊还没选工作空间时,请主人选一个 / ask the owner to pick a workspace
|
|
54
59
|
chat recall <消息编号> 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
|
|
55
60
|
/ take back one of your own messages (within 2 minutes; otherwise send a correction)
|
|
@@ -72,7 +77,7 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
|
|
|
72
77
|
Space pulls / pushes are recorded under the current session; use --session <session> or --session none.
|
|
73
78
|
所有 chat 命令支持 --json。 All chat commands accept --json.`;
|
|
74
79
|
|
|
75
|
-
const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group']);
|
|
80
|
+
const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group', 'plan']);
|
|
76
81
|
|
|
77
82
|
export function isChatCommand(command) {
|
|
78
83
|
return typeof command === 'string' && command.startsWith('chat:');
|
|
@@ -106,6 +111,11 @@ const REFUSALS = {
|
|
|
106
111
|
wb_dm_fixed: () => '只有私聊需要请主人选工作空间;群在建的时候就绑好了工作空间,chat read 里能看到路径。',
|
|
107
112
|
wb_workspace_missing: () => '这个群绑定的工作空间文件夹已经被删了,请告诉主人在群设置里换一个。',
|
|
108
113
|
wb_ask_closed: () => '这道选择题已经答过了。',
|
|
114
|
+
// v0.38.x: the workbench plan card (PRD 26 plan card design); the first two never make the Agent retry
|
|
115
|
+
wb_plan_steps: () => '计划要 3 到 8 步。',
|
|
116
|
+
wb_plan_text: () => '每一步都要有内容,而且不超过 60 字。',
|
|
117
|
+
wb_plan_missing: () => '这一轮还没发计划,先把 3 到 8 步发一份。',
|
|
118
|
+
wb_plan_closed: () => '这一段工作已经结束了,计划不用再更新。',
|
|
109
119
|
// v0.35.0: neutral on purpose, the platform gives no reason (PRD 09/06 BR-闸.15)
|
|
110
120
|
agent_gate_file_not_sent: () => '文件没有发出去,这条消息也没有发出。',
|
|
111
121
|
// v0.37 PA-10: recall (Agent only, own message, 2 minutes)
|
|
@@ -155,6 +165,11 @@ function patch(c, pathStr, body) {
|
|
|
155
165
|
return authedPatchWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
|
|
156
166
|
}
|
|
157
167
|
|
|
168
|
+
|
|
169
|
+
// PUT has no idempotency header (contract 4.0): `client_key` in the body is what makes a retry harmless.
|
|
170
|
+
function put(c, pathStr, body) {
|
|
171
|
+
return authedPutWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
|
|
172
|
+
}
|
|
158
173
|
function post(c, pathStr, body) {
|
|
159
174
|
return authedPostWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl });
|
|
160
175
|
}
|
|
@@ -487,7 +502,7 @@ async function runResult(c, sid) {
|
|
|
487
502
|
if (!listed.length && !files.length) lines.push('这次没有改动空间里的文件,成果消息里没有附件。');
|
|
488
503
|
if (data.segment && data.segment.ended) lines.push('这一段工作已结束;主人不满意的话可以在网页上一键退回这次改动。');
|
|
489
504
|
// Print only (never reported for you): a hired Agent's time counts only when usage is reported.
|
|
490
|
-
if (hireId) lines.push(
|
|
505
|
+
if (hireId) lines.push(`用量由平台自动读取,不用报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:${hireId},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:${hireId}。干着活隔一会儿补一次。叫醒里会写今日剩余额度(百分比);剩余额度不足时先告诉主人,再接大活。`);
|
|
491
506
|
c.log(lines.join('\n'));
|
|
492
507
|
return 0;
|
|
493
508
|
}
|
|
@@ -546,9 +561,90 @@ async function runNeedWorkspace(c, sid, positional) {
|
|
|
546
561
|
}
|
|
547
562
|
|
|
548
563
|
/**
|
|
549
|
-
* anytowork chat <list|read|send|result|ask|progress|need-workspace>
|
|
564
|
+
* anytowork chat <list|read|send|result|ask|progress|plan|need-workspace>
|
|
550
565
|
* @param {object} p { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, deps? }
|
|
551
566
|
*/
|
|
567
|
+
// ---------------------------------------------------------------- chat plan (v0.38.x, PRD 26 plan card design)
|
|
568
|
+
|
|
569
|
+
/** "1,2,3" -> [1,2,3]; null when anything is not a positive whole number. */
|
|
570
|
+
function ordList(raw) {
|
|
571
|
+
if (raw == null) return null;
|
|
572
|
+
const out = [];
|
|
573
|
+
for (const piece of String(raw).split(',')) {
|
|
574
|
+
const t = piece.trim();
|
|
575
|
+
if (!/^\d+$/.test(t) || Number(t) < 1) return null;
|
|
576
|
+
out.push(Number(t));
|
|
577
|
+
}
|
|
578
|
+
return out;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const PLAN_STATE_WORD = { done: '完成', doing: '在做' };
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* `chat plan <session> "<one|two|three>" [--done 1,2] [--doing 3]`
|
|
585
|
+
* One command, two uses: give a whole plan (3 to 8 steps, split by |) or only move steps to a new state.
|
|
586
|
+
* The platform decides the rest; this only checks the arguments and turns refusals into plain words.
|
|
587
|
+
*/
|
|
588
|
+
async function runPlan(c, sid, positional) {
|
|
589
|
+
const steps = (positional == null ? '' : String(positional)).split('|').map((x) => x.trim()).filter(Boolean);
|
|
590
|
+
const done = ordList(c.flags.done);
|
|
591
|
+
const doing = ordList(c.flags.doing);
|
|
592
|
+
if (c.flags.done != null && !done) return usage(c, '--done 要写第几步(数字,多个用逗号隔开,如 --done 1,2)。');
|
|
593
|
+
if (c.flags.doing != null && !doing) return usage(c, '--doing 要写第几步(数字,多个用逗号隔开,如 --doing 3)。');
|
|
594
|
+
if ((doing || []).some((n) => (done || []).includes(n))) return usage(c, '同一个步骤不能既 --done 又 --doing。');
|
|
595
|
+
const set = [];
|
|
596
|
+
for (const ord of done || []) set.push({ ord, state: 'done' });
|
|
597
|
+
for (const ord of doing || []) set.push({ ord, state: 'doing' });
|
|
598
|
+
if (!steps.length && !set.length) {
|
|
599
|
+
return usage(c, '用法:anytowork chat plan <会话> "第一步|第二步|第三步"(3 到 8 步),或者 --done 1 --doing 2 只改状态。');
|
|
600
|
+
}
|
|
601
|
+
if (steps.length) {
|
|
602
|
+
// 3 to 8: fewer makes no card (chat progress is enough), more is an error, never a silent trim
|
|
603
|
+
if (steps.length < 3 || steps.length > 8) return usage(c, '计划要 3 到 8 步。');
|
|
604
|
+
const tooLong = steps.find((x) => x.length > 60);
|
|
605
|
+
if (tooLong) return usage(c, `每一步不超过 60 字:「${tooLong.slice(0, 12)}…」太长了。`);
|
|
606
|
+
}
|
|
607
|
+
const body = { client_key: c.flags.idempotencyKey || randomUUID() };
|
|
608
|
+
if (steps.length) body.steps = steps.map((text) => ({ text }));
|
|
609
|
+
if (set.length) body.set = set;
|
|
610
|
+
let data;
|
|
611
|
+
try {
|
|
612
|
+
data = await put(c, `/sessions/${enc(sid)}/plan`, body);
|
|
613
|
+
} catch (e) {
|
|
614
|
+
const r = refusalOf(e);
|
|
615
|
+
// An older platform has no /plan route: a bare 404, not one of our coded refusals. Stay quiet, keep working.
|
|
616
|
+
if (!r && e && e.status === 404) {
|
|
617
|
+
const text = '平台还不支持计划,这一轮照常用 chat progress。';
|
|
618
|
+
if (c.json) c.log(JSON.stringify({ ok: false, error: 'plan_unsupported', message: text }));
|
|
619
|
+
else c.log(text);
|
|
620
|
+
return 0;
|
|
621
|
+
}
|
|
622
|
+
// Nothing broke: one line, exit 0, no retry.
|
|
623
|
+
if (r && (r.code === 'wb_plan_missing' || r.code === 'wb_plan_closed')) {
|
|
624
|
+
const text = REFUSALS[r.code]();
|
|
625
|
+
if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text, ...r.vars }));
|
|
626
|
+
else c.log(text);
|
|
627
|
+
return 0;
|
|
628
|
+
}
|
|
629
|
+
throw e;
|
|
630
|
+
}
|
|
631
|
+
touchCurrentSession(c.credOpts, c.nowMs());
|
|
632
|
+
if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
|
|
633
|
+
const plan = data.plan || {};
|
|
634
|
+
const lines = [];
|
|
635
|
+
if (steps.length) {
|
|
636
|
+
lines.push(Number(plan.version) > 1
|
|
637
|
+
? '计划已换掉,从头开始勾。'
|
|
638
|
+
: `计划已发给主人(${steps.length} 步)。每做完一步用 --done 勾掉。`);
|
|
639
|
+
}
|
|
640
|
+
if (set.length) {
|
|
641
|
+
const words = set.map((x) => `第 ${x.ord} 步${PLAN_STATE_WORD[x.state] || ''}`).join(',');
|
|
642
|
+
lines.push(steps.length ? `${words}。` : `计划已更新:${words}。`);
|
|
643
|
+
}
|
|
644
|
+
c.log([...lines, newsLine(data)].filter(Boolean).join('\n'));
|
|
645
|
+
return 0;
|
|
646
|
+
}
|
|
647
|
+
|
|
552
648
|
export async function runChat(p) {
|
|
553
649
|
const { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err } = p;
|
|
554
650
|
const deps = p.deps || {};
|
|
@@ -573,6 +669,7 @@ export async function runChat(p) {
|
|
|
573
669
|
if (sub === 'result') return await runResult(c, sid);
|
|
574
670
|
if (sub === 'ask') return await runAsk(c, sid);
|
|
575
671
|
if (sub === 'progress') return await runProgress(c, sid, rest);
|
|
672
|
+
if (sub === 'plan') return await runPlan(c, sid, rest);
|
|
576
673
|
if (sub === 'recall') return await runRecall(c, sid);
|
|
577
674
|
return await runNeedWorkspace(c, sid, rest);
|
|
578
675
|
} catch (e) {
|
package/src/cli-parse.js
CHANGED
|
@@ -298,6 +298,8 @@ export function parseArgs(argv) {
|
|
|
298
298
|
options: [], // chat ask --option "<choice>" (repeatable; "label::note")
|
|
299
299
|
recommend: null, // chat ask --recommend <n> (1-based)
|
|
300
300
|
before: null, // chat read --before <message id>
|
|
301
|
+
done: null, // chat plan --done 1,2: steps that are finished (comma list)
|
|
302
|
+
doing: null, // chat plan --doing 3: steps in progress, parallel allowed (comma list)
|
|
301
303
|
how: null, // v0.37 setup ack --how exec|own|cron
|
|
302
304
|
test: null, // v0.37 setup ack --test <test id> (normally remembered from the wake-up event)
|
|
303
305
|
ignoreNew: false, // v0.37 chat send --ignore-new: send even though others wrote since you last read (PA-03)
|
|
@@ -634,6 +636,10 @@ export function parseArgs(argv) {
|
|
|
634
636
|
if (v != null && v !== '') flags.mentions.push(v);
|
|
635
637
|
} else if (a === '--wip') {
|
|
636
638
|
flags.wip = true;
|
|
639
|
+
} else if (a === '--done') {
|
|
640
|
+
flags.done = args.shift() ?? null;
|
|
641
|
+
} else if (a === '--doing') {
|
|
642
|
+
flags.doing = args.shift() ?? null;
|
|
637
643
|
} else if (a === '--option') {
|
|
638
644
|
const v = args.shift();
|
|
639
645
|
if (v != null) flags.options.push(v);
|
|
@@ -738,7 +744,7 @@ export function parseArgs(argv) {
|
|
|
738
744
|
} else if (c0 === 'chat') {
|
|
739
745
|
// v0.32: anytowork chat list|read|send|ask|progress|need-workspace (none = show the help); v0.33 adds result
|
|
740
746
|
command = c1 === undefined ? 'chat:help'
|
|
741
|
-
: (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group'].includes(c1) ? `chat:${c1}` : 'unknown');
|
|
747
|
+
: (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group', 'plan'].includes(c1) ? `chat:${c1}` : 'unknown');
|
|
742
748
|
} else if (c0 === 'setup') {
|
|
743
749
|
// v0.37: settings after connecting: setup [check] | test-wake | ack <code> | checkin <minutes>
|
|
744
750
|
command = c1 === undefined ? 'setup:check'
|
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)})` : ''}:退出相关的群,按协议处理雇主的资料,不要把资料带到别处`,
|
package/src/index.js
CHANGED
|
@@ -551,6 +551,7 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
|
|
|
551
551
|
chat send <会话> "<内容>" [--wip] 回复;默认表示这一轮做完,干到一半先说一声加 --wip
|
|
552
552
|
chat result <会话> [--file <空间路径>]... 交成果:整件事做完了说一声(主人不满意可以一键退回这次改动)
|
|
553
553
|
chat ask / progress / need-workspace 选择题 / 报进度(不进聊天)/ 请主人给私聊选工作空间
|
|
554
|
+
chat plan <会话> "第一步|第二步|第三步" [--done 1,2] 三步以上的活开工前先说计划(3 到 8 步);做完一步用 --done 勾掉
|
|
554
555
|
chat recall <消息编号> 撤回你自己发的一条消息(2 分钟内);chat send 可加 --ignore-new;chat group rename|describe|add-agent 管你主人的群
|
|
555
556
|
Talk in the owner's workbench. 详细 / Details: anytowork chat --help
|
|
556
557
|
|
package/src/listener/run.js
CHANGED
|
@@ -637,6 +637,10 @@ export class Listener {
|
|
|
637
637
|
}
|
|
638
638
|
// v0.36: while nothing is running, send new model call records every 10 minutes (no model, nothing spent)
|
|
639
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
|
+
}
|
|
640
644
|
const started = this.nowMs();
|
|
641
645
|
let data;
|
|
642
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
|
@@ -5,12 +5,16 @@
|
|
|
5
5
|
// (agent-setup); the platform's copy (app/wb/rules_text.py, WB_RULES_REV) is the reference.
|
|
6
6
|
import { pickLang } from "./model-pledge.js";
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
// rev history: 9 -> 10 (2026-11-28): the full text states what the chat renders (bold, headings, ordered / bullet
|
|
9
|
+
// lists, inline code, code blocks; a table shows row by row) and that very long content goes as a file;
|
|
10
|
+
// 9 -> 10 (2026-11-29): step 3 also asks for a plan first (anytowork chat plan, 3 to 8 steps); the progress line
|
|
11
|
+
// stays. The platform copy (app/wb/rules_text.py) is the reference; 7 and 9 had drifted apart from it, both are 10 now.
|
|
12
|
+
export const WB_RULES_REV = 10;
|
|
9
13
|
|
|
10
14
|
export const WB_RULES_TEXT = {
|
|
11
15
|
"wb.rules.full": {
|
|
12
|
-
zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句收到和打算:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3.
|
|
13
|
-
en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message: anytowork chat read {sid}\n2. Reply at once with what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. Now and then say a line of progress: anytowork chat progress {sid} \"...\". (without it, your owner thinks you never got it).\n4. When done, hand in the result: anytowork chat result {sid}\nOnce you read a message, act: reply, --wip or progress. If you only read, the platform will call you again. Every round must end with a formal reply or a result (without --wip); a round answered only with --wip counts as no answer. When your owner asks you something, answer with a reply in the chat (chat send); your owner cannot see progress, so it does not count as an answer.\nIf a command says there are N new messages, your owner has said more: you must run chat read first, then decide whether to carry on or change course. Do not wait until your current step is done. The same goes for a supplement or a progress question on an order.",
|
|
16
|
+
zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句收到和打算:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3. 三步以上的活,开工前先把计划说给主人看:anytowork chat plan {sid} \"第一步|第二步|第三步\"(3 到 8 步);做完一步用 --done,同时做几步就把那几步都标 --doing。计划变了就重发一份,不用另开。做的过程中隔一会儿说进展:anytowork chat progress {sid} \"……\"(不说,主人以为你没收到)。\n4. 做完交成果:anytowork chat result {sid}\n读了消息就要有动作:回复、--wip 或 progress 三选一,只读不动平台会再叫你。每一轮必须以一条正式回复或成果(不带 --wip)收尾,只发 --wip 算没有回应。主人问你的问题,必须用聊天里的回复(chat send)回答;progress 主人看不到,不算回答。\n命令返回提示「另有 N 条新消息」,是主人又说话了:必须先 chat read 读完,再决定继续还是改方向,不要等手头这步做完。订单的补充需求或追问进度同理。聊天支持加粗、标题、有序/无序列表、行内代码和代码块,表格在气泡里按行显示;内容很长就先落成文件再发。",
|
|
17
|
+
en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message: anytowork chat read {sid}\n2. Reply at once with what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. For a job with three or more steps, show your plan first: anytowork chat plan {sid} \"one|two|three\" (3 to 8 steps); tick a step with --done, and mark steps you run in parallel with --doing. If the plan changes, send it again. Now and then say a line of progress: anytowork chat progress {sid} \"...\". (without it, your owner thinks you never got it).\n4. When done, hand in the result: anytowork chat result {sid}\nOnce you read a message, act: reply, --wip or progress. If you only read, the platform will call you again. Every round must end with a formal reply or a result (without --wip); a round answered only with --wip counts as no answer. When your owner asks you something, answer with a reply in the chat (chat send); your owner cannot see progress, so it does not count as an answer.\nIf a command says there are N new messages, your owner has said more: you must run chat read first, then decide whether to carry on or change course. Do not wait until your current step is done. The same goes for a supplement or a progress question on an order. The chat renders bold, headings, ordered / bullet lists, inline code and code blocks; a table shows row by row in the bubble; send very long content as a file.",
|
|
14
18
|
},
|
|
15
19
|
"wb.rules.short": {
|
|
16
20
|
zh: "主人在等你:先读消息,先回一句收到,边做边说一两句,做完交成果。",
|
|
@@ -23,8 +27,8 @@ export const WB_RULES_TEXT = {
|
|
|
23
27
|
},
|
|
24
28
|
// Extra paragraph for a hired Agent: full once per session, short afterwards.
|
|
25
29
|
"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
|
|
30
|
+
zh: "你是被聘来的:用量由平台自动读取,不用另外报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:{hire_id},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:{hire_id}。干着活隔一会儿补一次。叫醒里会写今日剩余额度(百分比);剩余额度不足时先告诉主人,再接大活。",
|
|
31
|
+
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
32
|
},
|
|
29
33
|
"wb.rules.hire.short": {
|
|
30
34
|
zh: "用量平台自动读。",
|