@anytowork/cli 0.12.36 → 0.12.38
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 +1 -1
- package/package.json +1 -1
- package/src/api.js +24 -0
- package/src/chat-commands.js +17 -4
- package/src/cli-parse.js +2 -1
- package/src/index.js +8 -3
- package/src/listener/commands.js +16 -2
- package/src/listener/prompt.js +6 -4
- package/src/listener/run.js +125 -4
- package/src/mt/collect.js +6 -1
- package/src/mt/inrun.js +277 -0
- package/src/mt/readers.js +160 -2
- package/src/profile.js +30 -8
- package/src/setup-commands.js +111 -3
- package/src/space-commands.js +7 -0
- package/src/space-sync.js +3 -0
- package/src/wb-rules-text.js +4 -4
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ anytowork profiles
|
|
|
51
51
|
```
|
|
52
52
|
|
|
53
53
|
存储位置:默认 profile 仍在 `~/.anytowork/`;具名 profile 在 `~/.anytowork/profiles/<名字>/`。
|
|
54
|
-
`--profile` 也可与 `ANYTOWORK_CONFIG_DIR`
|
|
54
|
+
`--profile` 也可与 `ANYTOWORK_CONFIG_DIR` 组合(根目录换成你指定的位置)。环境目录本身已是 `…/profiles/<名字>` 时,同名 `--profile` 直接用这个目录,不会叠成两份。
|
|
55
55
|
|
|
56
56
|
> 每个 Agent 都向主人要一个**新的**接入码、各自用自己的 `--profile` 接入;
|
|
57
57
|
> 主人在网页确认时,可以选择是新建一个 Agent,还是把它绑回一个已有的 Agent(登录失效后重新接入时用)。
|
package/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -1206,6 +1206,15 @@ export async function reportListener(baseUrl, credOpts = {}, body = {}, opts = {
|
|
|
1206
1206
|
return authedPostWithRefresh(baseUrl, '/api/v1/agent/listener/report', credOpts, body, null, opts);
|
|
1207
1207
|
}
|
|
1208
1208
|
|
|
1209
|
+
/**
|
|
1210
|
+
* POST /api/v1/agent/chat/sessions/{sid}/beat — v0.37.7: the always-on listener tells the platform the Agent's start
|
|
1211
|
+
* command for this session is still running (only with the listener header; an older platform answers 404).
|
|
1212
|
+
*/
|
|
1213
|
+
export async function postListenerBeat(baseUrl, credOpts = {}, sid, opts = {}) {
|
|
1214
|
+
return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/beat`, credOpts, { source: 'listener' }, null,
|
|
1215
|
+
{ ...opts, headers: { ...LISTENER_HEADER, ...(opts.headers || {}) } });
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1209
1218
|
/** GET /api/v1/agent/wb/sessions/{sid}/read-state — {last_read_msg_id}; used to skip a wake that was already read. */
|
|
1210
1219
|
export async function getWbReadState(baseUrl, credOpts = {}, sid, opts = {}) {
|
|
1211
1220
|
return authedGetWithRefresh(baseUrl, `/api/v1/agent/wb/sessions/${encodeURIComponent(sid)}/read-state`, credOpts, opts);
|
|
@@ -1236,6 +1245,21 @@ export async function postCheckin(baseUrl, credOpts = {}, everyMinutes, opts = {
|
|
|
1236
1245
|
return authedPostWithRefresh(baseUrl, '/api/v1/agent/checkin', credOpts, { every_minutes: everyMinutes }, null, opts);
|
|
1237
1246
|
}
|
|
1238
1247
|
|
|
1248
|
+
/** v0.37.7 (C9) PUT /agent/wake-hook {url, auth_token?} -> { hook, signing_secret, test: {state, test_id, deadline_at} }. Never the url or token. */
|
|
1249
|
+
export async function putWakeHook(baseUrl, credOpts = {}, body, opts = {}) {
|
|
1250
|
+
return authedPutWithRefresh(baseUrl, '/api/v1/agent/wake-hook', credOpts, body, opts);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/** v0.37.7 (C9) GET /agent/wake-hook -> { hook: {host, secret_last4, has_auth_token, status, push: {state, error}, ...} | null }. */
|
|
1254
|
+
export async function getWakeHook(baseUrl, credOpts = {}, opts = {}) {
|
|
1255
|
+
return authedGetWithRefresh(baseUrl, '/api/v1/agent/wake-hook', credOpts, opts);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/** v0.37.7 (C9) DELETE /agent/wake-hook -> { ok, removed }. */
|
|
1259
|
+
export async function deleteWakeHook(baseUrl, credOpts = {}, opts = {}) {
|
|
1260
|
+
return authedDeleteWithRefresh(baseUrl, '/api/v1/agent/wake-hook', credOpts, opts);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1239
1263
|
/** AW-06 GET /agent/setup -> { done, items: [{key, state, ...}], doc_url }. */
|
|
1240
1264
|
export async function getAgentSetup(baseUrl, credOpts = {}, opts = {}) {
|
|
1241
1265
|
return authedGetWithRefresh(baseUrl, '/api/v1/agent/setup', credOpts, opts);
|
package/src/chat-commands.js
CHANGED
|
@@ -62,6 +62,10 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
|
|
|
62
62
|
A reply ends your round by default; use --wip for "still working", chat progress for progress notes, and chat result when it is all done.
|
|
63
63
|
读、报进度、--wip 都算你在干活;隔几分钟没有动作,主人那边会显示「还没回」。
|
|
64
64
|
Reading, progress notes and --wip all count as working; after a few quiet minutes the owner sees "Not replied yet".
|
|
65
|
+
读了消息就要有动作:回复、--wip 或 progress,三选一。只读不动,平台会再叫你一次。
|
|
66
|
+
Once you read a message, act on it: reply, --wip or progress, pick one. If you only read, the platform will call you once more.
|
|
67
|
+
命令返回里如果提示「另有 N 条新消息」,等手头这一步做完再 chat read 一次;不要专门为了查消息多跑命令。
|
|
68
|
+
If an answer says there are N new messages, run chat read once after the step in hand; do not run extra commands just to check.
|
|
65
69
|
做事时用到的空间文件,anytowork space pull / push 会自动记到「当前会话」里;要指定别的会话加 --session <会话>,
|
|
66
70
|
不想记进任何会话加 --session none。
|
|
67
71
|
Space pulls / pushes are recorded under the current session; use --session <session> or --session none.
|
|
@@ -254,7 +258,8 @@ export function formatRead(data, sid, env = process.env) {
|
|
|
254
258
|
const members = (data.members || []).map((x) => {
|
|
255
259
|
const role = x.is_me ? '你' : (x.type === 'user' ? '主人' : (x.role === 'leader' ? '群主' : ''));
|
|
256
260
|
// v0.37 PA-02: a member who may only see the message much later is marked (only "away"; no minutes are given)
|
|
257
|
-
|
|
261
|
+
// v0.37.7: "unset" (never set up any way of being woken) is just as unreachable for now
|
|
262
|
+
const away = (x.reach_kind === 'away' || x.reach_kind === 'unset') && !x.is_me ? '(暂时联系不上)' : '';
|
|
258
263
|
return (role && !x.is_me ? `${x.name}(${role})` : (x.is_me ? `${x.name}(你)` : x.name)) + away;
|
|
259
264
|
});
|
|
260
265
|
const ro = (data.group && data.group.archived) || (data.session && data.session.archived) ? '(已归档,只能读不能发)' : '';
|
|
@@ -318,6 +323,12 @@ async function runList(c) {
|
|
|
318
323
|
return 0;
|
|
319
324
|
}
|
|
320
325
|
|
|
326
|
+
/** v0.37.7 (B7): the platform may add `news` ("N new messages elsewhere / since") to an answer; print its one line. */
|
|
327
|
+
export function newsLine(data) {
|
|
328
|
+
const n = data && data.news;
|
|
329
|
+
return n && typeof n.hint === 'string' && n.hint.trim() ? n.hint.trim() : '';
|
|
330
|
+
}
|
|
331
|
+
|
|
321
332
|
async function runRead(c, sid) {
|
|
322
333
|
const before = c.flags.before;
|
|
323
334
|
if (before != null && !/^\d+$/.test(String(before))) return usage(c, '--before 要写消息编号(数字)。');
|
|
@@ -325,7 +336,7 @@ async function runRead(c, sid) {
|
|
|
325
336
|
// Reading new messages makes this the current session; looking back (--before) only keeps the clock alive.
|
|
326
337
|
if (before == null) setCurrentSession(data.current_session || sid, c.credOpts, c.nowMs(), data.hire_id || null);
|
|
327
338
|
else touchCurrentSession(c.credOpts, c.nowMs());
|
|
328
|
-
c.log(c.json ? JSON.stringify(data, null, 2) : formatRead(data, sid, c.env));
|
|
339
|
+
c.log(c.json ? JSON.stringify(data, null, 2) : [formatRead(data, sid, c.env), newsLine(data)].filter(Boolean).join('\n'));
|
|
329
340
|
return 0;
|
|
330
341
|
}
|
|
331
342
|
|
|
@@ -375,6 +386,7 @@ async function runSend(c, sid, positional) {
|
|
|
375
386
|
}
|
|
376
387
|
if (c.flags.wip) lines.push('这一轮还在进行中;做完后再回复一次(不带 --wip)。');
|
|
377
388
|
else if (data.subtask && data.subtask.status === 'done') lines.push(`这一轮已结束。整件事做完了,请用 anytowork chat result ${sid} 交成果。`);
|
|
389
|
+
if (newsLine(data)) lines.push(newsLine(data));
|
|
378
390
|
c.log(lines.join('\n'));
|
|
379
391
|
return 0;
|
|
380
392
|
}
|
|
@@ -502,7 +514,7 @@ async function runAsk(c, sid) {
|
|
|
502
514
|
});
|
|
503
515
|
touchCurrentSession(c.credOpts, c.nowMs());
|
|
504
516
|
c.log(c.json ? JSON.stringify(data, null, 2)
|
|
505
|
-
: `选择题已发出(消息 #${data.message && data.message.id}
|
|
517
|
+
: [`选择题已发出(消息 #${data.message && data.message.id})。主人回答后你会被叫醒。`, newsLine(data)].filter(Boolean).join('\n'));
|
|
506
518
|
return 0;
|
|
507
519
|
}
|
|
508
520
|
|
|
@@ -511,7 +523,8 @@ async function runProgress(c, sid, positional) {
|
|
|
511
523
|
if (!text || !String(text).trim()) return usage(c, '用法:anytowork chat progress <会话> "<一句话>"');
|
|
512
524
|
const data = await post(c, `/sessions/${enc(sid)}/progress`, { text: String(text) });
|
|
513
525
|
touchCurrentSession(c.credOpts, c.nowMs());
|
|
514
|
-
c.log(c.json ? JSON.stringify(data, null, 2)
|
|
526
|
+
c.log(c.json ? JSON.stringify(data, null, 2)
|
|
527
|
+
: ['已记进工作轨迹(主人在 Agent 地图里看得到,不进聊天),这一轮仍在进行中。', newsLine(data)].filter(Boolean).join('\n'));
|
|
515
528
|
return 0;
|
|
516
529
|
}
|
|
517
530
|
|
package/src/cli-parse.js
CHANGED
|
@@ -744,8 +744,9 @@ export function parseArgs(argv) {
|
|
|
744
744
|
: (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group'].includes(c1) ? `chat:${c1}` : 'unknown');
|
|
745
745
|
} else if (c0 === 'setup') {
|
|
746
746
|
// v0.37: settings after connecting: setup [check] | test-wake | ack <code> | checkin <minutes>
|
|
747
|
+
// v0.37.7 (C9): setup wake-url set [<url>] | show | remove (auth token only from stdin or ANYTOWORK_WAKE_TOKEN)
|
|
747
748
|
command = c1 === undefined ? 'setup:check'
|
|
748
|
-
: (['check', 'test-wake', 'ack', 'checkin'].includes(c1) ? `setup:${c1}` : 'unknown');
|
|
749
|
+
: (['check', 'test-wake', 'ack', 'checkin', 'wake-url'].includes(c1) ? `setup:${c1}` : 'unknown');
|
|
749
750
|
|
|
750
751
|
} else if (c0 === 'ping') {
|
|
751
752
|
command = 'ping';
|
package/src/index.js
CHANGED
|
@@ -12,7 +12,7 @@ import { parseArgs } from './cli-parse.js';
|
|
|
12
12
|
import { buildAskQuestions, buildAnswers } from './collab-input.js';
|
|
13
13
|
import { RETIRED_COMMANDS } from './retired-commands.js';
|
|
14
14
|
import { resolveBaseUrl } from './config.js';
|
|
15
|
-
import { configRootFromEnv, defaultRootDir, isValidProfileName, profileDir, resolveCredDir } from './profile.js';
|
|
15
|
+
import { configRootFromEnv, defaultRootDir, isValidProfileName, profileRootFromEnv, profileDir, resolveCredDir } from './profile.js';
|
|
16
16
|
import { loadCredentials } from './credentials.js';
|
|
17
17
|
import { runAuthLogin } from './oauth.js';
|
|
18
18
|
import { runConnect } from './connect.js';
|
|
@@ -564,6 +564,9 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
|
|
|
564
564
|
setup test-wake 给自己发一次叫醒测试并等结果,打印用时 / start a wake-up test and wait for it
|
|
565
565
|
setup ack <随机码> 回应叫醒测试(随机码在叫醒事件的 🎯 行里)/ answer a wake-up test
|
|
566
566
|
setup checkin <分钟> 如实报告你多久检查一次(5–1440);poll 的实际间隔平台也会自动记下
|
|
567
|
+
setup wake-url set <地址> [--stdin] 把触发地址交给平台保存(有新消息时平台 POST 它叫醒你);地址也可走标准输入或 ANYTOWORK_WAKE_URL,
|
|
568
|
+
对方要求鉴权令牌时用 --stdin 或 ANYTOWORK_WAKE_TOKEN 给;保存成功显示一次签名密钥
|
|
569
|
+
setup wake-url show | remove 看保存的地址(主机名、签名密钥末 4 位、最近推送结果)/ 撤销
|
|
567
570
|
/ report how often you really check in (5-1440)
|
|
568
571
|
详细 / Details: anytowork setup --help
|
|
569
572
|
|
|
@@ -808,7 +811,8 @@ export async function run(argv, deps = {}) {
|
|
|
808
811
|
);
|
|
809
812
|
return 2;
|
|
810
813
|
}
|
|
811
|
-
|
|
814
|
+
// 环境目录可能已经是 <根>/profiles/<名>(监听拉起时就是这样):先还原成根目录,不再叠一层
|
|
815
|
+
profileDirPath = profileDir(flags.profile, { rootDir: profileRootFromEnv(env) });
|
|
812
816
|
}
|
|
813
817
|
|
|
814
818
|
if (command === 'auth:login') {
|
|
@@ -973,7 +977,8 @@ export async function run(argv, deps = {}) {
|
|
|
973
977
|
}
|
|
974
978
|
// v0.37: report how often I check in
|
|
975
979
|
if (isSetupCommand(command)) {
|
|
976
|
-
return await runSetup({ command, positionals, flags, baseUrl, credOpts, fetchImpl,
|
|
980
|
+
return await runSetup({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, env, argv,
|
|
981
|
+
deps: { ...deps, readStdin: deps.readStdin || readAllStdin } });
|
|
977
982
|
}
|
|
978
983
|
// v0.34: being hired (job policy, apply with an amount, sign, usage reports)
|
|
979
984
|
if (isHireCommand(command)) {
|
package/src/listener/commands.js
CHANGED
|
@@ -86,13 +86,16 @@ export async function runListenTest(p) {
|
|
|
86
86
|
return 1;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
const LISTENER_SEEN_FRESH_MS = 2 * 60 * 1000;
|
|
90
|
+
|
|
89
91
|
export async function runListenStatus(p) {
|
|
90
92
|
const { flags, credOpts, log, deps = {} } = p;
|
|
91
93
|
const env = deps.env || process.env;
|
|
92
94
|
const cfg = readConfig(credOpts);
|
|
93
95
|
const st = readState(credOpts);
|
|
94
96
|
const now = (deps.nowMs || Date.now)();
|
|
95
|
-
|
|
97
|
+
// v0.37.7 (B5): seenAt is saved about every 30-60 s while it runs, so 2 minutes is enough; a stopped listener also writes 0 (below)
|
|
98
|
+
const running = !!cfg && st.seenAt > 0 && now - st.seenAt < LISTENER_SEEN_FRESH_MS;
|
|
96
99
|
const used = runsToday(st, now);
|
|
97
100
|
const nodeStale = !!(cfg && cfg.nodePath && !fs.existsSync(cfg.nodePath));
|
|
98
101
|
if (flags.json) {
|
|
@@ -132,7 +135,18 @@ export async function runListenForever(p) {
|
|
|
132
135
|
if (adhoc) err(lt('exec.sh.notice', {}, env));
|
|
133
136
|
log(lt('run.started', {}, env));
|
|
134
137
|
const l = new Listener({ cfg, baseUrl, credOpts, fetchImpl, log, err, deps, classify });
|
|
135
|
-
|
|
138
|
+
// v0.37.7 (P2 B5 + P5): a stop request (launchctl bootout, systemctl stop, Ctrl+C, hang-up) clears the local
|
|
139
|
+
// "last seen" mark and tells the platform "stopped" (waits at most 3 seconds) before the process ends, so
|
|
140
|
+
// `listen status`, the owner's page and the wake-up routing do not keep saying "running" for minutes.
|
|
141
|
+
const proc = deps.proc || process;
|
|
142
|
+
const onStop = () => { l.announceStop().finally(() => proc.exit(0)); };
|
|
143
|
+
const sigs = deps.noSignalHandlers ? [] : ['SIGTERM', 'SIGINT', 'SIGHUP'];
|
|
144
|
+
for (const s of sigs) proc.once(s, onStop);
|
|
145
|
+
try {
|
|
146
|
+
return await l.loop();
|
|
147
|
+
} finally {
|
|
148
|
+
for (const s of sigs) { try { proc.removeListener(s, onStop); } catch { /* gone */ } }
|
|
149
|
+
}
|
|
136
150
|
}
|
|
137
151
|
|
|
138
152
|
export { labelOf, unitNameOf, writeState };
|
package/src/listener/prompt.js
CHANGED
|
@@ -70,11 +70,13 @@ export function buildPrompt(payload, env = process.env, identity = null, job = n
|
|
|
70
70
|
}
|
|
71
71
|
if (identity && (identity.profile || identity.dir)) {
|
|
72
72
|
const pf = identity.profile;
|
|
73
|
+
// v0.12.38: the wake-up already points anytowork at this login through the environment,
|
|
74
|
+
// so `--profile <name>` and a plain command reach the same credentials. Never ask the Agent to unset the env var.
|
|
73
75
|
lines.push(lang === 'en'
|
|
74
|
-
? (pf ? `Your identity on this computer is "${pf}"
|
|
75
|
-
: `Your identity on this computer lives in ${identity.dir}
|
|
76
|
-
: (pf ? `你在这台电脑上的身份是「${pf}
|
|
77
|
-
: `你在这台电脑上的身份放在 ${identity.dir}
|
|
76
|
+
? (pf ? `Your identity on this computer is "${pf}". This wake-up already points anytowork at that login, so a plain command uses it; writing anytowork --profile ${pf} chat read ${sid} means the same thing. Both spellings work.`
|
|
77
|
+
: `Your identity on this computer lives in ${identity.dir} (this wake-up already sets ANYTOWORK_CONFIG_DIR=${identity.dir}). Run anytowork commands as they are; no --profile is needed.`)
|
|
78
|
+
: (pf ? `你在这台电脑上的身份是「${pf}」。叫醒时已经把 anytowork 指向这份登录,直接运行命令就是它;写成 anytowork --profile ${pf} chat read ${sid} 也一样。两种写法等价,都能读到同一份登录。`
|
|
79
|
+
: `你在这台电脑上的身份放在 ${identity.dir}(叫醒时已经设好 ANYTOWORK_CONFIG_DIR=${identity.dir}),命令直接运行即可,不用再加 --profile。`));
|
|
78
80
|
}
|
|
79
81
|
return lines.join('\n');
|
|
80
82
|
}
|
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, LISTENER_HEADER } from '../api.js';
|
|
15
|
+
import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, 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';
|
|
@@ -22,6 +22,7 @@ import { lt } from './text.js';
|
|
|
22
22
|
import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
|
|
23
23
|
import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
|
|
24
24
|
import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
|
|
25
|
+
import { RunUsageTracker, inrunSettings } from '../mt/inrun.js'; // v0.37.7 C2: usage while the Agent runs
|
|
25
26
|
import {
|
|
26
27
|
LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight, effectiveDailyMax, effectiveFailPause,
|
|
27
28
|
readListenerCursor, writeListenerCursor, appendLog, promptsDir,
|
|
@@ -34,6 +35,11 @@ const BUSY_SPAN_MS = 10_000;
|
|
|
34
35
|
const QUICK_REPLY_MS = 2000;
|
|
35
36
|
const QUICK_PAUSE_MS = 3000;
|
|
36
37
|
const PAUSED_TICK_MS = 15_000;
|
|
38
|
+
const BEAT_EVERY_MS = 60_000; // v0.37.7 C1: the alive beat while the start command runs
|
|
39
|
+
const VERSION_CHECK_MS = 10 * 60 * 1000; // v0.37.7 C7: look for a newer installed version this often
|
|
40
|
+
const FINAL_UPLOAD_WAIT_MS = 20_000; // the last usage upload at the end of a run may take this long at most
|
|
41
|
+
/** Exit code of "I was upgraded, start me again": non-zero on purpose (launchd KeepAlive / systemd Restart=on-failure). */
|
|
42
|
+
export const EXIT_UPGRADED = 75;
|
|
37
43
|
|
|
38
44
|
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;
|
|
39
45
|
const UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
|
@@ -45,6 +51,23 @@ export function isSafeId(x) {
|
|
|
45
51
|
|
|
46
52
|
function defaultSleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
|
|
47
53
|
|
|
54
|
+
/** The version of the package files on disk now (an upgrade replaces them while this process keeps the old code). */
|
|
55
|
+
function installedVersionOnDisk() {
|
|
56
|
+
try { return JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version || null; } catch { return null; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** `promise`, but never longer than `ms` (the timer is cleared either way). Never rejects. */
|
|
60
|
+
async function within(promise, ms) {
|
|
61
|
+
let t;
|
|
62
|
+
try {
|
|
63
|
+
return await Promise.race([promise, new Promise((r) => { t = setTimeout(r, ms); })]);
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
} finally {
|
|
67
|
+
clearTimeout(t);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
48
71
|
/** Quote a path for the system shell (it comes from our own credentials directory, never from a message). */
|
|
49
72
|
export function shellQuote(s, platform = process.platform) {
|
|
50
73
|
if (platform === 'win32') return `"${String(s).replace(/"/g, '')}"`;
|
|
@@ -137,6 +160,14 @@ export class Listener {
|
|
|
137
160
|
this.shouldStop = d.listenShouldStop || (() => false);
|
|
138
161
|
this.autoCollect = d.autoCollect || autoCollect;
|
|
139
162
|
this.env = d.env || process.env;
|
|
163
|
+
this.beatOff = false; // v0.37.7 C1: the platform has no beat route (older version): stop trying
|
|
164
|
+
this.installedVersion = d.installedVersion || installedVersionOnDisk;
|
|
165
|
+
this.versionCheckMs = Number(d.versionCheckMs || p.cfg && p.cfg.versionCheckMs) || VERSION_CHECK_MS;
|
|
166
|
+
this.lastVersionCheck = 0;
|
|
167
|
+
this.usage = d.usageTracker || new RunUsageTracker({
|
|
168
|
+
baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl, env: d.env || process.env, home: d.home, sqlite: d.sqlite,
|
|
169
|
+
nowMs: d.nowMs || Date.now,
|
|
170
|
+
});
|
|
140
171
|
this.queue = new WakeQueue({ config: { ...LISTENER_DEFAULTS, ...this.cfg }, nowMs: this.nowMs });
|
|
141
172
|
this.state = readState(this.credOpts);
|
|
142
173
|
this.active = new Set();
|
|
@@ -181,6 +212,73 @@ export class Listener {
|
|
|
181
212
|
} catch { /* an older platform has no report route; never stop for it */ }
|
|
182
213
|
}
|
|
183
214
|
|
|
215
|
+
/**
|
|
216
|
+
* Round 4 (B5): tell the platform at once that this listener is going away, and forget the local "seen" time so
|
|
217
|
+
* `listen status` stops saying it is running. Quiet, at most a few seconds, once.
|
|
218
|
+
*/
|
|
219
|
+
async announceStop(waitMs = 3000) {
|
|
220
|
+
if (this.stoppedAnnounced) return;
|
|
221
|
+
this.stoppedAnnounced = true;
|
|
222
|
+
this.state.seenAt = 0;
|
|
223
|
+
try { this.save(); } catch { /* the state file is only a hint */ }
|
|
224
|
+
this.logLine('stopped');
|
|
225
|
+
await within(this.report({ state: 'stopped', runs_today: runsToday(this.state, this.nowMs()) }), waitMs);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** v0.37.7 C1: every minute while the start command runs, say so to the platform (no model, nothing spent). */
|
|
229
|
+
startBeat(sid) {
|
|
230
|
+
const every = this.cfg.beatEveryMs != null ? Number(this.cfg.beatEveryMs) : BEAT_EVERY_MS;
|
|
231
|
+
if (!(every > 0) || this.beatOff) return null;
|
|
232
|
+
const t = setInterval(async () => {
|
|
233
|
+
if (this.beatOff) return;
|
|
234
|
+
try {
|
|
235
|
+
await postListenerBeat(this.baseUrl, this.credOpts, sid, { fetchImpl: this.fetchImpl });
|
|
236
|
+
} catch (e) {
|
|
237
|
+
// 404: an older platform without the route. 403: the platform did not take it for a listener call. Both: stop for good.
|
|
238
|
+
if (e && (e.status === 404 || e.status === 403)) { this.beatOff = true; this.logLine(`beat off status=${e.status}`); }
|
|
239
|
+
}
|
|
240
|
+
}, every);
|
|
241
|
+
if (t.unref) t.unref();
|
|
242
|
+
return t;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** v0.37.7 C2: note a run that belongs to a hire / task; its usage is read from the local logs while it runs. */
|
|
246
|
+
beginUsage(job, command, jobInfo) {
|
|
247
|
+
try {
|
|
248
|
+
const set = inrunSettings(this.cfg, this.state, this.env);
|
|
249
|
+
if (!set.enabled) return null;
|
|
250
|
+
const p = job.payload || {};
|
|
251
|
+
const taskId = isSafeId(String(p.task_id || '')) ? String(p.task_id) : '';
|
|
252
|
+
if (!job.hireId && !taskId) return null;
|
|
253
|
+
const dirs = [this.cfg.cwd || process.cwd()];
|
|
254
|
+
if (jobInfo && jobInfo.path) dirs.push(jobInfo.path);
|
|
255
|
+
return this.usage.begin({ sid: job.sid, wakeId: job.wakeId, hireId: job.hireId, taskId, command, dirs, startMs: this.nowMs() });
|
|
256
|
+
} catch {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
startUsageTimer(urun) {
|
|
262
|
+
if (!urun) return null;
|
|
263
|
+
const ms = inrunSettings(this.cfg, this.state, this.env).intervalMs;
|
|
264
|
+
if (!ms) return null;
|
|
265
|
+
const t = setInterval(() => { this.usage.upload(urun); }, ms);
|
|
266
|
+
if (t.unref) t.unref();
|
|
267
|
+
return t;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** v0.37.7 C7: an upgrade replaced the files on disk; only a start-at-login listener ends itself (something starts it again). */
|
|
271
|
+
upgradeDue() {
|
|
272
|
+
const kind = this.cfg.autostartKind;
|
|
273
|
+
if (kind !== 'launchd' && kind !== 'systemd') return false;
|
|
274
|
+
const now = this.nowMs();
|
|
275
|
+
if (this.active.size || now - this.lastVersionCheck < this.versionCheckMs) return false;
|
|
276
|
+
this.lastVersionCheck = now;
|
|
277
|
+
let v = null;
|
|
278
|
+
try { v = this.installedVersion(); } catch { /* unreadable: stay */ }
|
|
279
|
+
return !!v && v !== CLI_VERSION;
|
|
280
|
+
}
|
|
281
|
+
|
|
184
282
|
pause(reason, detail) {
|
|
185
283
|
const now = this.nowMs();
|
|
186
284
|
this.state.paused = { reason, at: now, detail: detail || null };
|
|
@@ -309,6 +407,8 @@ export class Listener {
|
|
|
309
407
|
async runJob(job) {
|
|
310
408
|
const now0 = this.nowMs();
|
|
311
409
|
let ranFile = null;
|
|
410
|
+
let urun = null;
|
|
411
|
+
let timers = [];
|
|
312
412
|
try {
|
|
313
413
|
// A wake that waited in the queue: if the Agent has read the conversation meanwhile, skip it.
|
|
314
414
|
if (job.waited && job.msgId != null) {
|
|
@@ -322,7 +422,8 @@ export class Listener {
|
|
|
322
422
|
} catch { /* cannot tell: run it */ }
|
|
323
423
|
}
|
|
324
424
|
const promptFile = path.join(promptsDir(this.credOpts), `${job.wakeId || job.sid.slice(0, 8)}-${now0}.txt`);
|
|
325
|
-
const
|
|
425
|
+
const jobInfo = this.jobOf(job.payload);
|
|
426
|
+
const prompt = buildPrompt(job.payload, this.env, this.identity(), jobInfo);
|
|
326
427
|
try {
|
|
327
428
|
fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
|
|
328
429
|
fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
|
|
@@ -334,7 +435,15 @@ export class Listener {
|
|
|
334
435
|
};
|
|
335
436
|
const command = expandCommand(this.cfg.exec, vals);
|
|
336
437
|
const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
|
|
337
|
-
|
|
438
|
+
urun = this.beginUsage(job, command, jobInfo);
|
|
439
|
+
timers = [this.startBeat(job.sid), this.startUsageTimer(urun)];
|
|
440
|
+
let res;
|
|
441
|
+
try {
|
|
442
|
+
res = await this.execCommand({ command, input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
|
|
443
|
+
} finally {
|
|
444
|
+
for (const t of timers) if (t) clearInterval(t);
|
|
445
|
+
}
|
|
446
|
+
if (urun) await within(this.usage.finish(urun), FINAL_UPLOAD_WAIT_MS);
|
|
338
447
|
const ok = res && res.code === 0 && !res.timedOut && !res.error;
|
|
339
448
|
const ms = this.nowMs() - now0;
|
|
340
449
|
const why = !res ? 'spawn' : (res.timedOut ? 'timeout' : (res.error ? 'spawn' : `exit_${res.code}`));
|
|
@@ -385,7 +494,14 @@ export class Listener {
|
|
|
385
494
|
let reconnectMs = RECONNECT_FIRST_MS;
|
|
386
495
|
let broken = false;
|
|
387
496
|
let cursor = readListenerCursor(this.credOpts, readCursor);
|
|
497
|
+
this.lastVersionCheck = this.nowMs();
|
|
388
498
|
while (!this.shouldStop()) {
|
|
499
|
+
// v0.37.7 C7: the package on disk is newer than this running code: say so and end; launchd / systemd start the new one
|
|
500
|
+
if (this.upgradeDue()) {
|
|
501
|
+
this.logLine(`upgrade running=${CLI_VERSION}`);
|
|
502
|
+
await this.announceStop();
|
|
503
|
+
return EXIT_UPGRADED;
|
|
504
|
+
}
|
|
389
505
|
if (this.isPaused()) {
|
|
390
506
|
try { await this.pausedStep(); } catch (e) {
|
|
391
507
|
if (this.classify && this.classify(e) === 'upgrade') throw e;
|
|
@@ -425,7 +541,11 @@ export class Listener {
|
|
|
425
541
|
// v0.37 PA-06: the platform's own numbers (daily limit, failures before a pause) replace the local defaults
|
|
426
542
|
if (lis && lis.limits && typeof lis.limits === 'object') {
|
|
427
543
|
const was = JSON.stringify(this.state.limits || null);
|
|
428
|
-
this.state.limits = {
|
|
544
|
+
this.state.limits = {
|
|
545
|
+
daily_max: Number(lis.limits.daily_max) || null, fail_pause_after: Number(lis.limits.fail_pause_after) || null,
|
|
546
|
+
// v0.37.7: seconds between usage uploads while an Agent runs; 0 = off; absent = the built-in default
|
|
547
|
+
...(lis.limits.inrun_upload_sec != null && Number.isFinite(Number(lis.limits.inrun_upload_sec)) ? { inrun_upload_sec: Number(lis.limits.inrun_upload_sec) } : {}),
|
|
548
|
+
};
|
|
429
549
|
if (JSON.stringify(this.state.limits) !== was) this.save();
|
|
430
550
|
}
|
|
431
551
|
if (lis && lis.allowed === false) {
|
|
@@ -438,6 +558,7 @@ export class Listener {
|
|
|
438
558
|
if (!(data && data.events && data.events.length) && this.nowMs() - started < QUICK_REPLY_MS) await this.sleep(QUICK_PAUSE_MS);
|
|
439
559
|
}
|
|
440
560
|
await Promise.allSettled([...this.active]);
|
|
561
|
+
await this.announceStop();
|
|
441
562
|
return 0;
|
|
442
563
|
}
|
|
443
564
|
}
|
package/src/mt/collect.js
CHANGED
|
@@ -131,6 +131,11 @@ export function isZero(r) {
|
|
|
131
131
|
|
|
132
132
|
/** Local key of a record (call: call_key hash; summary: report id). */
|
|
133
133
|
export function localKey(r) {
|
|
134
|
+
// v0.37.7: a cumulative row (per session x model) is a new fact every time its totals change, so the totals
|
|
135
|
+
// are part of the key (the batch idempotency key must differ, otherwise the platform would take it for a replay).
|
|
136
|
+
if (r.kind === 'cumulative') {
|
|
137
|
+
return `c:${r.source_session_key}:${r.model}:${r.input_tokens}:${r.output_tokens}:${r.cache_write_tokens}:${r.cache_read_tokens}:${r.reasoning_tokens || 0}`;
|
|
138
|
+
}
|
|
134
139
|
return r.granularity === 'summary' ? `s:${r.report_id}` : sha256(callKey(r.provider, r.call_id));
|
|
135
140
|
}
|
|
136
141
|
|
|
@@ -205,7 +210,7 @@ export async function sendRows({ baseUrl, credOpts, fetchImpl, rows, state, nowM
|
|
|
205
210
|
batch.forEach((r, i) => {
|
|
206
211
|
const res = results.find((x) => x && x.i === i) || results[i] || null;
|
|
207
212
|
if (!res) return;
|
|
208
|
-
state.sent[localKey(r)] = nowMs;
|
|
213
|
+
if (r.kind !== 'cumulative') state.sent[localKey(r)] = nowMs; // totals are resent when they change: nothing to remember
|
|
209
214
|
tot.total += 1;
|
|
210
215
|
const st = res.status;
|
|
211
216
|
if (st in tot && typeof tot[st] === 'number') tot[st] += 1;
|
package/src/mt/inrun.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// v0.37.7 (segment 4, C2 to C4): usage of the runs the always-on listener starts, read from this computer's own logs
|
|
2
|
+
// WHILE the Agent runs and once more when it ends. The listener notes, for every run it starts: the session, the wake-up,
|
|
3
|
+
// the hire / task, the start and end time and the folders. From that this module picks the calls that belong to the run
|
|
4
|
+
// and sends them with a `task_ref`; nothing is asked of the Agent and no model is called.
|
|
5
|
+
//
|
|
6
|
+
// Rows (`anytowork.usage.v2`, contract section 3.1 of the segment-4 plan):
|
|
7
|
+
// - Claude Code / Codex logs: one row per call (granularity call), only calls of the run's folders in the run's time window;
|
|
8
|
+
// - session database: one CUMULATIVE row per session x model (kind cumulative): the platform keeps the biggest value it saw and
|
|
9
|
+
// adds only the difference, so sending the same totals again, or from another computer, never counts twice;
|
|
10
|
+
// - run-log database: one row per run (granularity call), only runs of the session key named in the start command.
|
|
11
|
+
// `attribution` is `run` (this run's time window + folders / session) or `window` (another run was going on at the same
|
|
12
|
+
// time, so the owner of the call is not certain: shown on the platform, not priced).
|
|
13
|
+
// Nothing here reads or sends prompts, answers or file contents; only numbers, model names, times and ids.
|
|
14
|
+
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { readMsgLog, readRollout, readSessionModelUsage, readRunLog, guessProvider } from './readers.js';
|
|
18
|
+
import { readState, writeState, sendRows, sha256, isZero, localKey } from './collect.js';
|
|
19
|
+
import { readRegistry, workdirForPath } from './workdirs.js';
|
|
20
|
+
|
|
21
|
+
export const SCHEMA_V2 = 'anytowork.usage.v2';
|
|
22
|
+
export const INRUN_DEFAULT_SEC = 180; // MT_INRUN_UPLOAD_SEC default (the platform sends `inrun_upload_sec` in listener.limits)
|
|
23
|
+
const START_SLACK_MS = 5000; // a session / log line may be stamped a little before the start we noted
|
|
24
|
+
const FINISH_GRACE_MS = 15_000; // and a little after the end
|
|
25
|
+
const SETTLE_MS = 60_000; // a call seen less than this long ago may still be streaming into the log
|
|
26
|
+
const KEEP_FINISHED_MS = 10 * 60 * 1000; // finished runs stay known this long (to tell who owns what in a crowd)
|
|
27
|
+
|
|
28
|
+
/** The task a run belongs to: the session, the wake-up and the hire or task (ids the platform sent and the listener checked). */
|
|
29
|
+
export function buildTaskRef({ sid, wakeId, hireId, taskId }) {
|
|
30
|
+
const ref = { session_id: sid, wake_id: wakeId || '' };
|
|
31
|
+
if (hireId) ref.hire_id = hireId; else if (taskId) ref.task_id = taskId;
|
|
32
|
+
return ref;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* How the in-run upload runs for this listener: `{enabled, intervalMs}`.
|
|
37
|
+
* The platform's `inrun_upload_sec` (listener.limits) wins; 0 switches the whole in-run upload off and the idle upload
|
|
38
|
+
* (every 10 minutes while nothing runs) takes over. `ANYTOWORK_INRUN_UPLOAD_SEC` on this computer can set the interval
|
|
39
|
+
* (0 = off). Not less than 30 seconds, except `cfg.inrunUploadMs` (tests; 0 = only the upload at the end of a run).
|
|
40
|
+
*/
|
|
41
|
+
export function inrunSettings(cfg, state, env = process.env) {
|
|
42
|
+
const platRaw = state && state.limits ? state.limits.inrun_upload_sec : undefined;
|
|
43
|
+
const plat = platRaw != null && Number.isFinite(Number(platRaw)) ? Number(platRaw) : null;
|
|
44
|
+
const envRaw = env && env.ANYTOWORK_INRUN_UPLOAD_SEC;
|
|
45
|
+
const envSec = envRaw != null && envRaw !== '' && Number.isFinite(Number(envRaw)) ? Number(envRaw) : null;
|
|
46
|
+
if (plat === 0 || envSec === 0) return { enabled: false, intervalMs: null };
|
|
47
|
+
if (cfg && cfg.inrunUploadMs != null) return { enabled: true, intervalMs: Number(cfg.inrunUploadMs) > 0 ? Number(cfg.inrunUploadMs) : null };
|
|
48
|
+
const sec = envSec != null ? envSec : (plat != null ? plat : INRUN_DEFAULT_SEC);
|
|
49
|
+
return { enabled: true, intervalMs: Math.max(30, sec) * 1000 };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function norm(p) { try { return path.resolve(String(p)); } catch { return null; } }
|
|
53
|
+
|
|
54
|
+
/** A log folder belongs to a run when it is one of the run's folders or inside one (never inside the root or home folder). */
|
|
55
|
+
function dirMatches(cwd, dirs, home, exactOnly = false) {
|
|
56
|
+
const c = norm(cwd);
|
|
57
|
+
if (!c) return false;
|
|
58
|
+
for (const d of dirs) {
|
|
59
|
+
if (c === d) return true;
|
|
60
|
+
if (exactOnly || d === path.parse(d).root || d === home) continue;
|
|
61
|
+
if (c.startsWith(d + path.sep)) return true;
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function shareDir(a, b) { return a.dirs.some((d) => b.dirs.includes(d)); }
|
|
67
|
+
function timeOverlap(a, b, now) {
|
|
68
|
+
const aEnd = a.endMs == null ? now : a.endMs + FINISH_GRACE_MS;
|
|
69
|
+
const bEnd = b.endMs == null ? now : b.endMs + FINISH_GRACE_MS;
|
|
70
|
+
return a.startMs - START_SLACK_MS <= bEnd && b.startMs - START_SLACK_MS <= aEnd;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function callRow(c, ctx) {
|
|
74
|
+
const row = {
|
|
75
|
+
schema: SCHEMA_V2,
|
|
76
|
+
granularity: 'call',
|
|
77
|
+
call_id: String(c.call_id).trim().slice(0, 200),
|
|
78
|
+
conversation_id: String(c.conversation_id).slice(0, 200),
|
|
79
|
+
provider: String(c.provider || 'unknown').toLowerCase().slice(0, 60),
|
|
80
|
+
model: String(c.model).slice(0, 120),
|
|
81
|
+
started_at: c.started_at,
|
|
82
|
+
input_tokens: c.input_tokens,
|
|
83
|
+
output_tokens: c.output_tokens,
|
|
84
|
+
cache_write_tokens: c.cache_write_tokens || 0,
|
|
85
|
+
cache_read_tokens: c.cache_read_tokens || 0,
|
|
86
|
+
program: ctx.program,
|
|
87
|
+
reader: ctx.reader,
|
|
88
|
+
attribution: ctx.attribution,
|
|
89
|
+
task_ref: ctx.taskRef,
|
|
90
|
+
source: 'local-log',
|
|
91
|
+
};
|
|
92
|
+
if (c.reasoning_tokens != null) row.reasoning_tokens = c.reasoning_tokens;
|
|
93
|
+
if (c.unreadable_fields && c.unreadable_fields.length) row.unreadable_fields = c.unreadable_fields;
|
|
94
|
+
if (c.message_id) row.message_id = String(c.message_id).slice(0, 200);
|
|
95
|
+
if (c.request_model) row.request_model = String(c.request_model).slice(0, 120);
|
|
96
|
+
if (c.ended_at && c.ended_at !== c.started_at) row.ended_at = c.ended_at;
|
|
97
|
+
if (c.cwd) row.project_dir_hash = sha256(norm(c.cwd) || c.cwd);
|
|
98
|
+
if (ctx.workdirId) row.workdir_id = ctx.workdirId;
|
|
99
|
+
return row;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isoSec(ms) { return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'); }
|
|
103
|
+
|
|
104
|
+
export class RunUsageTracker {
|
|
105
|
+
/** @param {object} p { baseUrl, credOpts, fetchImpl, env, home, sqlite, nowMs, log } */
|
|
106
|
+
constructor(p) {
|
|
107
|
+
this.baseUrl = p.baseUrl;
|
|
108
|
+
this.credOpts = p.credOpts;
|
|
109
|
+
this.fetchImpl = p.fetchImpl;
|
|
110
|
+
this.env = p.env || process.env;
|
|
111
|
+
this.home = p.home || os.homedir();
|
|
112
|
+
this.sqlite = p.sqlite; // undefined: load the built-in module when needed; null: none
|
|
113
|
+
this.nowMs = p.nowMs || Date.now;
|
|
114
|
+
this.log = p.log || (() => {});
|
|
115
|
+
this.runs = [];
|
|
116
|
+
this.seq = 0;
|
|
117
|
+
this.off = false; // the platform said the feature is off: stop trying in this process
|
|
118
|
+
this.chain = Promise.resolve(); // uploads one after another: they share one local state file
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A run starts. `dirs`: the folders the Agent works in (the listener's cwd, the hire work folder). */
|
|
122
|
+
begin({ sid, wakeId, hireId, taskId, command, dirs, startMs }) {
|
|
123
|
+
const now = this.nowMs();
|
|
124
|
+
this.runs = this.runs.filter((x) => x.endMs == null || now - x.endMs < KEEP_FINISHED_MS);
|
|
125
|
+
const r = {
|
|
126
|
+
seq: (this.seq += 1), sid, startMs: startMs != null ? startMs : now, endMs: null,
|
|
127
|
+
taskRef: buildTaskRef({ sid, wakeId, hireId, taskId }),
|
|
128
|
+
dirs: [...new Set((dirs || []).map(norm).filter(Boolean))],
|
|
129
|
+
tokens: String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter((t) => t.length >= 4 && !t.startsWith('-') && /[:_-]/.test(t)),
|
|
130
|
+
cum: new Map(), // `session|model` -> totals already sent
|
|
131
|
+
sentAny: false,
|
|
132
|
+
};
|
|
133
|
+
this.runs.push(r);
|
|
134
|
+
return r;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Queue one upload of what the run has so far (`final`: the run ended, no settle time, a short grace after the end). */
|
|
138
|
+
upload(r, { final = false } = {}) {
|
|
139
|
+
const next = this.chain.then(() => this.#upload(r, final)).catch(() => null);
|
|
140
|
+
this.chain = next;
|
|
141
|
+
return next;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The run ended: remember when, then send the last batch. */
|
|
145
|
+
finish(r) {
|
|
146
|
+
r.endMs = this.nowMs();
|
|
147
|
+
return this.upload(r, { final: true });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
peers(r, now) {
|
|
151
|
+
return this.runs.filter((x) => x !== r && shareDir(x, r) && timeOverlap(x, r, now));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Which run owns a session of the session database. The only run whose time fits owns it (sure). When several runs of one folder go on
|
|
156
|
+
* at the same time, the sessions of that folder are handed out in the order the runs started (not sure: `window`).
|
|
157
|
+
* `ordered`: the sessions of the folders of this crowd, by start time.
|
|
158
|
+
*/
|
|
159
|
+
#hermesOwner(s, r, now, ordered) {
|
|
160
|
+
const group = [r, ...this.peers(r, now)].sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
|
|
161
|
+
const fits = group.filter((x) => s.startedMs >= x.startMs - START_SLACK_MS && (x.endMs == null || s.startedMs <= x.endMs + FINISH_GRACE_MS));
|
|
162
|
+
if (!fits.length) return { owner: null, sure: false };
|
|
163
|
+
if (fits.length === 1) return { owner: fits[0], sure: true };
|
|
164
|
+
const rank = Math.max(0, ordered.findIndex((x) => x.id === s.id));
|
|
165
|
+
return { owner: fits[Math.min(rank, fits.length - 1)], sure: false };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async #upload(r, final) {
|
|
169
|
+
if (this.off) return null;
|
|
170
|
+
const now = this.nowMs();
|
|
171
|
+
const since = r.startMs - START_SLACK_MS;
|
|
172
|
+
const until = final ? (r.endMs != null ? r.endMs : now) + FINISH_GRACE_MS : now;
|
|
173
|
+
const settleMs = final ? 0 : SETTLE_MS;
|
|
174
|
+
const env = this.env;
|
|
175
|
+
const home = this.home;
|
|
176
|
+
const state = readState(this.credOpts);
|
|
177
|
+
const registry = (() => { try { return readRegistry(this.credOpts); } catch { return {}; } })();
|
|
178
|
+
const wdCache = new Map();
|
|
179
|
+
const workdirOf = (cwd) => { try { const w = workdirForPath(cwd, registry, wdCache); return w ? w.workdir_id : null; } catch { return null; } };
|
|
180
|
+
const crowd = this.peers(r, now).length > 0;
|
|
181
|
+
const rows = [];
|
|
182
|
+
const pendingCum = [];
|
|
183
|
+
const heldSessions = [];
|
|
184
|
+
|
|
185
|
+
// session database: totals per session x model
|
|
186
|
+
try {
|
|
187
|
+
const hs = await readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite });
|
|
188
|
+
const crowdDirs = [...new Set([r, ...this.peers(r, now)].flatMap((x) => x.dirs))];
|
|
189
|
+
const crowdStart = Math.min(r.startMs, ...this.peers(r, now).map((x) => x.startMs)) - START_SLACK_MS;
|
|
190
|
+
const ordered = hs.sessions
|
|
191
|
+
.filter((s) => s.source !== 'cron' && s.cwd && dirMatches(s.cwd, crowdDirs, home, true) && s.startedMs >= crowdStart)
|
|
192
|
+
.sort((a, b) => a.startedMs - b.startedMs);
|
|
193
|
+
for (const s of ordered) {
|
|
194
|
+
if (s.startedMs < since || s.startedMs > until) continue;
|
|
195
|
+
const { owner, sure } = this.#hermesOwner(s, r, now, ordered);
|
|
196
|
+
if (owner !== r) continue;
|
|
197
|
+
heldSessions.push(s.id);
|
|
198
|
+
for (const m of s.models) {
|
|
199
|
+
const sig = `${s.id}|${m.model}`;
|
|
200
|
+
const totals = `${m.input_tokens}|${m.output_tokens}|${m.cache_write_tokens}|${m.cache_read_tokens}|${m.reasoning_tokens}`;
|
|
201
|
+
if (r.cum.get(sig) === totals) continue;
|
|
202
|
+
const row = {
|
|
203
|
+
schema: SCHEMA_V2, kind: 'cumulative', granularity: 'cumulative',
|
|
204
|
+
source_session_key: s.id, conversation_id: s.id,
|
|
205
|
+
provider: guessProvider(m.model), model: m.model.slice(0, 120),
|
|
206
|
+
started_at: isoSec(s.startedMs), ended_at: isoSec(s.lastSeenMs || s.startedMs),
|
|
207
|
+
input_tokens: m.input_tokens, output_tokens: m.output_tokens, cache_write_tokens: m.cache_write_tokens, cache_read_tokens: m.cache_read_tokens,
|
|
208
|
+
reasoning_tokens: m.reasoning_tokens,
|
|
209
|
+
program: 'hermes', reader: 'cli:session_model_usage', attribution: sure ? 'run' : 'window',
|
|
210
|
+
task_ref: r.taskRef, source: 'local-log',
|
|
211
|
+
};
|
|
212
|
+
if (isZero(row)) continue;
|
|
213
|
+
rows.push(row);
|
|
214
|
+
pendingCum.push([sig, totals]);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
} catch { /* unreadable: the next round tries again */ }
|
|
218
|
+
|
|
219
|
+
// Claude Code / Codex: calls of the run's folders in the run's time window
|
|
220
|
+
const attributionOfCalls = crowd ? 'window' : 'run';
|
|
221
|
+
const fromJsonl = [
|
|
222
|
+
{ program: 'claude_code', reader: 'cli:msg_log', read: () => readMsgLog({ home, env, sinceMs: since }) },
|
|
223
|
+
{ program: 'codex', reader: 'cli:rollout', read: () => readRollout({ home, env, sinceMs: since }) },
|
|
224
|
+
];
|
|
225
|
+
for (const src of fromJsonl) {
|
|
226
|
+
try {
|
|
227
|
+
for (const c of src.read().calls) {
|
|
228
|
+
if (c.seenMs < since || c.seenMs > until || c.seenMs > now - settleMs) continue;
|
|
229
|
+
if (!c.cwd || !dirMatches(c.cwd, r.dirs, home)) continue;
|
|
230
|
+
rows.push(callRow(c, { program: src.program, reader: src.reader, attribution: attributionOfCalls, taskRef: r.taskRef, workdirId: workdirOf(c.cwd) }));
|
|
231
|
+
}
|
|
232
|
+
} catch { /* one unreadable log never blocks the others */ }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// run-log database: runs of the session key the start command names
|
|
236
|
+
if (r.tokens.length) {
|
|
237
|
+
try {
|
|
238
|
+
const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite });
|
|
239
|
+
for (const c of oc.calls) {
|
|
240
|
+
if (c.seenMs < since || c.seenMs > until) continue;
|
|
241
|
+
const key = c.session_key || '';
|
|
242
|
+
const hit = r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
|
|
243
|
+
if (!hit) continue;
|
|
244
|
+
rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution: attributionOfCalls, taskRef: r.taskRef }));
|
|
245
|
+
}
|
|
246
|
+
} catch { /* same */ }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// what was already sent is not sent again (calls: the local list shared with the idle upload)
|
|
250
|
+
const seen = new Set();
|
|
251
|
+
const fresh = [];
|
|
252
|
+
for (const row of rows) {
|
|
253
|
+
if (row.kind === 'cumulative') { fresh.push(row); continue; }
|
|
254
|
+
if (isZero(row)) continue;
|
|
255
|
+
const k = localKey(row);
|
|
256
|
+
if (seen.has(k) || state.sent[k]) continue;
|
|
257
|
+
seen.add(k);
|
|
258
|
+
fresh.push(row);
|
|
259
|
+
}
|
|
260
|
+
if (final) markSummariesSent(state, heldSessions);
|
|
261
|
+
if (!fresh.length) { if (final) writeState(this.credOpts, state, now); return { sent: 0 }; }
|
|
262
|
+
const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
|
|
263
|
+
if (tot.featureOff) this.off = true;
|
|
264
|
+
if (!tot.error && !tot.featureOff) {
|
|
265
|
+
for (const [sig, totals] of pendingCum) r.cum.set(sig, totals);
|
|
266
|
+
r.sentAny = true;
|
|
267
|
+
}
|
|
268
|
+
writeState(this.credOpts, state, now);
|
|
269
|
+
return { sent: fresh.length, tot };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The idle upload sends a finished session of the session database as one summary row; a session already sent live must not go twice. */
|
|
274
|
+
function markSummariesSent(state, sessionIds) {
|
|
275
|
+
for (const id of sessionIds) state.sent[`s:s-${sha256(String(id)).slice(0, 32)}`] = Date.now();
|
|
276
|
+
}
|
|
277
|
+
|
package/src/mt/readers.js
CHANGED
|
@@ -100,6 +100,23 @@ function msgLogRoots(home, env) {
|
|
|
100
100
|
return [...new Set(roots)];
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* v0.37.7 (C5): one reply is written as several lines (streaming). The same message.id + requestId is one call: the
|
|
105
|
+
* LAST line wins (it holds the final counts), the earliest time is kept, and lines of a synthetic model (the program's
|
|
106
|
+
* own placeholder, not a model call) are left out.
|
|
107
|
+
*/
|
|
108
|
+
function lastWinsInto(map, key, row) {
|
|
109
|
+
const old = map.get(key);
|
|
110
|
+
if (old) {
|
|
111
|
+
// the time span of the reply is the first to the last line; the counts are the last line's
|
|
112
|
+
const times = [old.started_at, old.ended_at, row.started_at].filter(Boolean).sort();
|
|
113
|
+
row.started_at = times[0];
|
|
114
|
+
row.ended_at = times[times.length - 1] > times[0] ? times[times.length - 1] : null;
|
|
115
|
+
row.seenMs = Math.max(old.seenMs, row.seenMs);
|
|
116
|
+
}
|
|
117
|
+
map.set(key, row);
|
|
118
|
+
}
|
|
119
|
+
|
|
103
120
|
export function readMsgLog({ home, env, sinceMs }) {
|
|
104
121
|
const calls = new Map();
|
|
105
122
|
let files = 0;
|
|
@@ -110,13 +127,13 @@ export function readMsgLog({ home, env, sinceMs }) {
|
|
|
110
127
|
if (o.type !== 'assistant' || !o.message || typeof o.message !== 'object') return;
|
|
111
128
|
const m = o.message;
|
|
112
129
|
const u = m.usage;
|
|
113
|
-
if (!u || typeof u !== 'object' || !m.model || m.model
|
|
130
|
+
if (!u || typeof u !== 'object' || !m.model || /^<?synthetic>?$/i.test(String(m.model))) return;
|
|
114
131
|
const callId = m.id || o.requestId || o.uuid;
|
|
115
132
|
const at = iso(o.timestamp);
|
|
116
133
|
if (!callId || !at || !o.sessionId) return;
|
|
117
134
|
const seenMs = Date.parse(at);
|
|
118
135
|
if (seenMs < sinceMs) return;
|
|
119
|
-
|
|
136
|
+
lastWinsInto(calls, `${m.id || ''}|${o.requestId || ''}|${m.id || o.requestId ? '' : o.uuid}`, {
|
|
120
137
|
call_id: String(callId),
|
|
121
138
|
conversation_id: String(o.sessionId),
|
|
122
139
|
message_id: o.requestId && o.requestId !== callId ? String(o.requestId) : undefined,
|
|
@@ -262,6 +279,147 @@ export async function readSessionDb({ home, env, sinceMs, sqlite }) {
|
|
|
262
279
|
return { calls: [], summaries, files: files.length };
|
|
263
280
|
}
|
|
264
281
|
|
|
282
|
+
// ---------------------------------------------------------------- session database, live (v0.37.7 C3)
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* The session database table of usage per session x model (`session_model_usage`, updated while the session runs, so an
|
|
286
|
+
* unfinished session is read too). Rows that differ only in billing route / task (for example the title model call)
|
|
287
|
+
* are added up into one entry per session x model. No filtering here: the caller picks the sessions of a run.
|
|
288
|
+
* @returns {Promise<{sessions: object[], files: number, unreadable?: number}>}
|
|
289
|
+
*/
|
|
290
|
+
export async function readSessionModelUsage({ home, env, sinceMs, sqlite }) {
|
|
291
|
+
const files = sessionDbFiles(home, env);
|
|
292
|
+
if (!files.length) return { sessions: [], files: 0 };
|
|
293
|
+
const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
|
|
294
|
+
if (!DatabaseSync) return { sessions: [], files: 0, unreadable: files.length };
|
|
295
|
+
const sessions = new Map();
|
|
296
|
+
for (const f of files) {
|
|
297
|
+
let db;
|
|
298
|
+
try {
|
|
299
|
+
db = new DatabaseSync(f, { readOnly: true });
|
|
300
|
+
const rows = db.prepare(
|
|
301
|
+
'SELECT s.id AS id, s.source AS source, s.cwd AS cwd, s.started_at AS started_at, s.ended_at AS ended_at, '
|
|
302
|
+
+ 'm.model AS model, m.input_tokens AS i, m.output_tokens AS o, m.cache_read_tokens AS cr, m.cache_write_tokens AS cw, '
|
|
303
|
+
+ 'm.reasoning_tokens AS r, m.last_seen AS last_seen '
|
|
304
|
+
+ 'FROM session_model_usage m JOIN sessions s ON s.id = m.session_id '
|
|
305
|
+
+ 'WHERE COALESCE(m.last_seen, s.started_at) >= ?',
|
|
306
|
+
).all(sinceMs / 1000);
|
|
307
|
+
for (const r of rows) {
|
|
308
|
+
if (!r.model) continue;
|
|
309
|
+
const key = `${f}\u0000${r.id}`;
|
|
310
|
+
let s = sessions.get(key);
|
|
311
|
+
if (!s) {
|
|
312
|
+
s = { id: String(r.id), source: String(r.source || ''), cwd: typeof r.cwd === 'string' ? r.cwd : null, startedMs: Math.round(Number(r.started_at) * 1000),
|
|
313
|
+
endedMs: r.ended_at == null ? null : Math.round(Number(r.ended_at) * 1000), lastSeenMs: 0, models: [] };
|
|
314
|
+
sessions.set(key, s);
|
|
315
|
+
}
|
|
316
|
+
s.lastSeenMs = Math.max(s.lastSeenMs, Math.round(Number(r.last_seen || r.started_at) * 1000));
|
|
317
|
+
let m = s.models.find((x) => x.model === String(r.model));
|
|
318
|
+
if (!m) { m = { model: String(r.model), input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0 }; s.models.push(m); }
|
|
319
|
+
m.input_tokens += int(r.i);
|
|
320
|
+
m.output_tokens += int(r.o);
|
|
321
|
+
m.cache_read_tokens += int(r.cr);
|
|
322
|
+
m.cache_write_tokens += int(r.cw);
|
|
323
|
+
m.reasoning_tokens += int(r.r);
|
|
324
|
+
}
|
|
325
|
+
} catch { /* a locked or different file: skip it */ } finally {
|
|
326
|
+
try { if (db) db.close(); } catch { /* ignore */ }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return { sessions: [...sessions.values()], files: files.length };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---------------------------------------------------------------- run-log database (v0.37.7 C4)
|
|
333
|
+
|
|
334
|
+
function openClawDbFiles(home, env) {
|
|
335
|
+
const roots = [];
|
|
336
|
+
if (env.OPENCLAW_HOME) roots.push(String(env.OPENCLAW_HOME));
|
|
337
|
+
roots.push(path.join(home, '.openclaw'));
|
|
338
|
+
const out = [];
|
|
339
|
+
for (const root of [...new Set(roots)]) {
|
|
340
|
+
let names;
|
|
341
|
+
try { names = fs.readdirSync(path.join(root, 'agents')); } catch { continue; }
|
|
342
|
+
for (const n of names) {
|
|
343
|
+
const dir = path.join(root, 'agents', n, 'agent');
|
|
344
|
+
let files;
|
|
345
|
+
try { files = fs.readdirSync(dir); } catch { continue; }
|
|
346
|
+
// main database only, not the side files named <db>.sqlite.<something>.sqlite
|
|
347
|
+
for (const f of files) if (f.endsWith('.sqlite') && !f.slice(0, -7).includes('.sqlite')) out.push(path.join(dir, f));
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const OPENCLAW_SQL = `SELECT session_id AS sid, run_id AS rid, seq, created_at AS c,
|
|
354
|
+
json_extract(event_json, '$.ts') AS ts,
|
|
355
|
+
json_extract(event_json, '$.sessionKey') AS skey,
|
|
356
|
+
json_extract(event_json, '$.provider') AS provider,
|
|
357
|
+
COALESCE(json_extract(event_json, '$.modelId'), json_extract(event_json, '$.model')) AS model,
|
|
358
|
+
json_type(event_json, '$.data.usage') AS ut,
|
|
359
|
+
json_extract(event_json, '$.data.usage.input') AS i,
|
|
360
|
+
json_extract(event_json, '$.data.usage.output') AS o,
|
|
361
|
+
json_extract(event_json, '$.data.usage.cacheWrite') AS cw,
|
|
362
|
+
json_extract(event_json, '$.data.usage.cacheRead') AS cr,
|
|
363
|
+
json_extract(event_json, '$.data.usage.reasoningTokens') AS r,
|
|
364
|
+
json_extract(event_json, '$.data.usage.total') AS total
|
|
365
|
+
FROM trajectory_runtime_events
|
|
366
|
+
WHERE created_at >= ? AND json_extract(event_json, '$.type') = 'model.completed'
|
|
367
|
+
ORDER BY created_at, seq`;
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The run-log database: one `model.completed` event is one RUN (not a running total). The same run + model written twice
|
|
371
|
+
* counts once (the bigger one is kept: under-reporting is the safe side). A missing reasoning count is 0; a missing
|
|
372
|
+
* cache count is 0 and listed in `unreadable_fields`. The session key is returned so the caller can pick the runs of
|
|
373
|
+
* one wake-up (several sessions run on one computer at the same time).
|
|
374
|
+
*/
|
|
375
|
+
export async function readRunLog({ home, env, sinceMs, sqlite }) {
|
|
376
|
+
const files = openClawDbFiles(home, env);
|
|
377
|
+
if (!files.length) return { calls: [], files: 0 };
|
|
378
|
+
const DatabaseSync = sqlite === undefined ? await loadSqlite() : sqlite;
|
|
379
|
+
if (!DatabaseSync) return { calls: [], files: 0, unreadable: files.length };
|
|
380
|
+
const runs = new Map();
|
|
381
|
+
for (const f of files) {
|
|
382
|
+
let db;
|
|
383
|
+
try {
|
|
384
|
+
db = new DatabaseSync(f, { readOnly: true });
|
|
385
|
+
const tbl = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_runtime_events'").all();
|
|
386
|
+
if (!tbl.length) continue;
|
|
387
|
+
for (const r of db.prepare(OPENCLAW_SQL).all(sinceMs)) {
|
|
388
|
+
if (r.ut !== 'object' || !r.model) continue;
|
|
389
|
+
const at = iso(r.ts) || iso(r.c);
|
|
390
|
+
if (!at) continue;
|
|
391
|
+
const unreadable = [];
|
|
392
|
+
if (r.cr == null) unreadable.push('cache_read_tokens');
|
|
393
|
+
if (r.cw == null) unreadable.push('cache_write_tokens');
|
|
394
|
+
const row = {
|
|
395
|
+
call_id: `${r.rid || `s:${r.sid}:${r.seq}`}:${r.model}`,
|
|
396
|
+
run_id: r.rid ? String(r.rid) : null,
|
|
397
|
+
session_id: String(r.sid),
|
|
398
|
+
session_key: typeof r.skey === 'string' ? r.skey : null,
|
|
399
|
+
conversation_id: String(r.sid),
|
|
400
|
+
provider: String(r.provider || guessProvider(r.model)).toLowerCase(),
|
|
401
|
+
model: String(r.model),
|
|
402
|
+
started_at: at,
|
|
403
|
+
ended_at: null,
|
|
404
|
+
seenMs: Date.parse(at),
|
|
405
|
+
input_tokens: int(r.i),
|
|
406
|
+
output_tokens: int(r.o),
|
|
407
|
+
cache_write_tokens: int(r.cw),
|
|
408
|
+
cache_read_tokens: int(r.cr),
|
|
409
|
+
reasoning_tokens: int(r.r),
|
|
410
|
+
unreadable_fields: unreadable,
|
|
411
|
+
total: int(r.total),
|
|
412
|
+
};
|
|
413
|
+
const old = runs.get(row.call_id);
|
|
414
|
+
if (!old || row.total > old.total || (row.total === old.total && row.seenMs > old.seenMs)) runs.set(row.call_id, row);
|
|
415
|
+
}
|
|
416
|
+
} catch { /* a locked or different file: skip it */ } finally {
|
|
417
|
+
try { if (db) db.close(); } catch { /* ignore */ }
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return { calls: [...runs.values()], files: files.length };
|
|
421
|
+
}
|
|
422
|
+
|
|
265
423
|
/**
|
|
266
424
|
* Read every known log on this computer. `settleMs`: calls seen less than this long ago are left for the next run
|
|
267
425
|
* (a reply may still be streaming into the log).
|
package/src/profile.js
CHANGED
|
@@ -63,16 +63,38 @@ export function profileDir(name, opts = {}) {
|
|
|
63
63
|
* 目录优先级(越靠前越优先):
|
|
64
64
|
* 1. opts.dir 单测注入 / 调用方显式指定
|
|
65
65
|
* 2. flags.profile(--profile) 同机多 Agent 隔离(推荐)
|
|
66
|
-
* 3. ANYTOWORK_CONFIG_DIR
|
|
67
|
-
* 4. ~/.anytowork
|
|
68
|
-
* 注:--profile 优先级高于 ANYTOWORK_CONFIG_DIR
|
|
69
|
-
*
|
|
66
|
+
* 3. ANYTOWORK_CONFIG_DIR 旧版隔离手段(继续支持)
|
|
67
|
+
* 4. ~/.anytowork 默认
|
|
68
|
+
* 注:--profile 优先级高于 ANYTOWORK_CONFIG_DIR——显式开关应当压过环境变量。
|
|
69
|
+
* 两者不叠加:环境目录如果本身已经是 <根>/profiles/<名>,同名 profile 就直接用它
|
|
70
|
+
*(监听拉起时环境变量已指向这份登录,叫醒提示又建议加 --profile,叠一层就读不到凭证)。
|
|
70
71
|
*/
|
|
71
72
|
export function resolveCredDir({ dir, profile, env = process.env } = {}) {
|
|
72
73
|
if (dir) return dir;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
const fromEnv = configRootFromEnv(env);
|
|
75
|
+
if (profile == null || profile === '') return fromEnv;
|
|
76
|
+
const split = splitProfileEnvDir(fromEnv);
|
|
77
|
+
if (split.profile === profile) return fromEnv;
|
|
78
|
+
return profileDir(profile, { rootDir: split.root });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 拆开环境里给的目录:<根>/profiles/<名> → 根 + 名;<根>/profiles → 根;其他原样当根。
|
|
83
|
+
* 监听拉起的 Agent 同时拿到 ANYTOWORK_CONFIG_DIR=<根>/profiles/<名> 和叫醒提示里的
|
|
84
|
+
* --profile <名>,不拆开的话 --profile 会再拼一层 profiles/<名>。
|
|
85
|
+
*/
|
|
86
|
+
function splitProfileEnvDir(dirName) {
|
|
87
|
+
const name = path.basename(dirName);
|
|
88
|
+
const parent = path.dirname(dirName);
|
|
89
|
+
if (!name || parent === dirName) return { root: dirName, profile: null };
|
|
90
|
+
if (name === "profiles") return { root: parent, profile: null };
|
|
91
|
+
if (path.basename(parent) === "profiles" && isValidProfileName(name)) {
|
|
92
|
+
return { root: path.dirname(parent), profile: name };
|
|
76
93
|
}
|
|
77
|
-
return
|
|
94
|
+
return { root: dirName, profile: null };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 环境变量指向的根目录(若它已是一个 profile 目录,还原成根目录)。 */
|
|
98
|
+
export function profileRootFromEnv(env = process.env) {
|
|
99
|
+
return splitProfileEnvDir(configRootFromEnv(env)).root;
|
|
78
100
|
}
|
package/src/setup-commands.js
CHANGED
|
@@ -4,12 +4,18 @@
|
|
|
4
4
|
// setup test-wake start a wake-up test for myself and wait for the result (up to its time limit)
|
|
5
5
|
// setup ack <code> answer a wake-up test (the code is in the 🎯 line of the wake-up event)
|
|
6
6
|
// setup checkin <minutes> tell the platform how often I really check in (5-1440)
|
|
7
|
+
// setup wake-url set [<url>] [--stdin] v0.37.7 (C9): hand the platform my trigger address ("POST here and I run
|
|
8
|
+
// once"). The address from the argument, ANYTOWORK_WAKE_URL or stdin; the
|
|
9
|
+
// optional auth token (only if the receiving side asks for one) from stdin or
|
|
10
|
+
// ANYTOWORK_WAKE_TOKEN, never from the command line. The platform makes the
|
|
11
|
+
// signing secret (whsec_...) and the answer shows it once.
|
|
12
|
+
// setup wake-url show | remove what is kept (host name + the signing secret's last 4 only) / take it off
|
|
7
13
|
//
|
|
8
14
|
// Exit codes: 0 for everything that worked, including "something is still missing" (a reminder is not a failure);
|
|
9
15
|
// 1 when the platform refused; 2 for a bad argument or a lost login (decided by the shared handler).
|
|
10
16
|
// The platform decides every state; this file only asks and prints.
|
|
11
17
|
|
|
12
|
-
import { getAgentSetup, startWakeTest, ackWakeTest, postCheckin } from './api.js';
|
|
18
|
+
import { getAgentSetup, startWakeTest, ackWakeTest, postCheckin, putWakeHook, getWakeHook, deleteWakeHook } from './api.js';
|
|
13
19
|
import { pickLang } from './model-pledge.js';
|
|
14
20
|
import { SETUP_DOC_URL, readWakeTest } from './setup-hints.js';
|
|
15
21
|
import { noteReported, CHECKIN_MIN, CHECKIN_MAX } from './checkin.js';
|
|
@@ -23,6 +29,15 @@ export const SETUP_HELP = `anytowork setup — 接好后的设置 / settings aft
|
|
|
23
29
|
[--how exec|own|cron] 你是怎么被叫醒的(可不写)/ how you were woken (optional)
|
|
24
30
|
[--test <编号>] 测试编号(一般不用写,命令行会记住)/ test id (normally remembered)
|
|
25
31
|
setup checkin <分钟> 如实报告你多久检查一次(5–1440)/ report how often you check in (5-1440)
|
|
32
|
+
setup wake-url set <地址> 把触发地址交给平台:有新消息时平台 POST 它叫醒你 / hand the platform your trigger address
|
|
33
|
+
[--stdin] 从标准输入读:https 开头的一行是地址,另一行是鉴权令牌(对方要求时才给);
|
|
34
|
+
也可用环境变量 ANYTOWORK_WAKE_URL / ANYTOWORK_WAKE_TOKEN。令牌不要写在命令行里
|
|
35
|
+
/ stdin: the https line is the address, another line the auth token (only if the
|
|
36
|
+
receiving side asks); or ANYTOWORK_WAKE_URL / ANYTOWORK_WAKE_TOKEN; never on the command line
|
|
37
|
+
保存成功会显示一次签名密钥(whsec_ 开头),用来核对推送确实来自平台
|
|
38
|
+
/ a successful save shows the signing secret (whsec_...) once, to verify pushes
|
|
39
|
+
setup wake-url show 看保存的地址(主机名、签名密钥末 4 位、最近推送结果)/ show it (host, secret's last 4, last push)
|
|
40
|
+
setup wake-url remove 撤销 / take it off
|
|
26
41
|
所有命令支持 --json。 All commands accept --json.`;
|
|
27
42
|
|
|
28
43
|
const TEXT = {
|
|
@@ -52,6 +67,26 @@ const TEXT = {
|
|
|
52
67
|
ackLate: { zh: '这次测试已经超时或结束了。需要的话运行 anytowork setup test-wake 再测一次。', en: 'That test has timed out or ended. Run anytowork setup test-wake to test again if needed.' },
|
|
53
68
|
checkinUsage: { zh: '用法:anytowork setup checkin <分钟>({min}–{max} 之间的整数)', en: 'Usage: anytowork setup checkin <minutes> (a whole number from {min} to {max})' },
|
|
54
69
|
checkinOk: { zh: '已报告:你每 {n} 分钟检查一次。', en: 'Reported: you check in every {n} minutes.' },
|
|
70
|
+
hookUsage: { zh: '用法:anytowork setup wake-url set [<地址>] [--stdin] | show | remove', en: 'Usage: anytowork setup wake-url set [<address>] [--stdin] | show | remove' },
|
|
71
|
+
hookArg: { zh: '令牌、密钥不能写在命令行里(会留在命令历史和进程列表里)。鉴权令牌用 --stdin 从标准输入给,或设环境变量 ANYTOWORK_WAKE_TOKEN;签名密钥由平台生成,不用给。这次没有提交。', en: 'Tokens and secrets must not be on the command line (they stay in the shell history and the process list). Pipe the auth token with --stdin or set ANYTOWORK_WAKE_TOKEN; the signing secret is made by the platform. Nothing was sent.' },
|
|
72
|
+
hookSaved: { zh: '已保存触发地址:{host}。', en: 'Trigger address saved: {host}.' },
|
|
73
|
+
hookSecret: { zh: '签名密钥(只显示这一次,请存好;用它核对推送头里的 webhook-signature,确认请求来自平台):', en: 'Signing secret (shown only this once; keep it and use it to verify the webhook-signature header of each push):' },
|
|
74
|
+
hookPending: { zh: '测试推送已在后台发出。稍后运行 anytowork setup wake-url show 看结果;被叫醒后运行 anytowork poll,按 🎯 那一行回应。', en: 'The test push is on its way. Run anytowork setup wake-url show later for the result; once woken, run anytowork poll and answer as its 🎯 line says.' },
|
|
75
|
+
hookPushOffNow: { zh: '平台暂时没有发推送,地址已保存。', en: 'Pushes are paused on the platform for now; the address is saved.' },
|
|
76
|
+
hookBadUrl: { zh: '地址不能用:只收能从公网访问的 https 地址(443 端口,不带用户名密码)。', en: 'That address cannot be used: only public https addresses (port 443, no user name or password).' },
|
|
77
|
+
hookBadHost: { zh: '这个地址的域名解析不到公网地址。核对拼写,或换一个能从公网访问的地址。', en: 'The host name of that address does not resolve to a public address. Check the spelling or use one reachable from the internet.' },
|
|
78
|
+
hookBadToken: { zh: '鉴权令牌不对:要 12–512 个字符,不能有空格或换行。', en: 'That auth token cannot be used: 12-512 characters, no spaces or line breaks.' },
|
|
79
|
+
hookLater: { zh: '保存得太频繁了,请 {n} 秒后再试。', en: 'Saved too often; try again in {n} s.' },
|
|
80
|
+
hookNone: { zh: '没有保存触发地址。', en: 'No trigger address is kept.' },
|
|
81
|
+
hookShow: { zh: '触发地址:{host}{key}{auth},状态:{state},最近推送:{push}', en: 'Trigger address: {host}{key}{auth}, state: {state}, last push: {push}' },
|
|
82
|
+
hookKey: { zh: '(签名密钥末 4 位 {k})', en: ' (signing secret ending {k})' },
|
|
83
|
+
hookAuth: { zh: ',带鉴权令牌', en: ', with auth token' },
|
|
84
|
+
hookOn: { zh: '在用', en: 'on' },
|
|
85
|
+
hookOff: { zh: '已停用(连续叫不醒),重新运行 set 即可恢复', en: 'switched off (failed in a row); run set again to turn it back on' },
|
|
86
|
+
hookPush_pending: { zh: '等待结果', en: 'waiting for the result' },
|
|
87
|
+
hookPush_ok: { zh: '已送达', en: 'accepted' },
|
|
88
|
+
hookPush_failed: { zh: '没送达({e})', en: 'not accepted ({e})' },
|
|
89
|
+
hookRemoved: { zh: '已撤销触发地址。', en: 'Trigger address taken off.' },
|
|
55
90
|
checkinRange: { zh: '间隔要在 {min}–{max} 分钟之间。每 1–4 分钟运行一次 poll 的不用报告,那种做法直接可以被测试叫醒。', en: 'The interval must be {min}-{max} minutes. Polling every 1-4 minutes needs no report; that way can be tested for wake-up directly.' },
|
|
56
91
|
};
|
|
57
92
|
|
|
@@ -200,19 +235,92 @@ async function runCheckin(c, raw) {
|
|
|
200
235
|
return 0;
|
|
201
236
|
}
|
|
202
237
|
|
|
238
|
+
// Review 7: a token or secret typed as a flag (--key x, --key=x, --token=x ...) is refused with exit 2 before anything is
|
|
239
|
+
// sent and its value is never printed. The parser drops unknown flags silently, so the raw argv is checked here.
|
|
240
|
+
const SECRET_FLAG = /^--?(key|secret|token|auth[-_]?token|signing[-_]?secret|password)(=|$)/i;
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* C9 inputs: the address (argument, ANYTOWORK_WAKE_URL, or the https line of stdin) and the optional auth token
|
|
244
|
+
* (another stdin line, or ANYTOWORK_WAKE_TOKEN). Stdin is read only with --stdin.
|
|
245
|
+
*/
|
|
246
|
+
async function readInputs(c, positionals) {
|
|
247
|
+
const env = c.env || {};
|
|
248
|
+
let url = positionals[3] || String(env.ANYTOWORK_WAKE_URL || '').trim();
|
|
249
|
+
let fromStdin = '';
|
|
250
|
+
if (c.flags.stdin) {
|
|
251
|
+
const raw = c.deps.readStdin ? await c.deps.readStdin() : '';
|
|
252
|
+
for (const line of String(raw || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean)) {
|
|
253
|
+
if (/^https?:\/\//i.test(line)) { if (!url) url = line; } else if (!fromStdin) fromStdin = line;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { url, token: fromStdin || String(env.ANYTOWORK_WAKE_TOKEN || '').trim() };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function hookLine(h, env) {
|
|
260
|
+
const key = h.secret_last4 ? t('hookKey', { k: h.secret_last4 }, env) : '';
|
|
261
|
+
return { host: h.host || '?', key };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function runWakeUrl(c, positionals) {
|
|
265
|
+
const action = positionals[2];
|
|
266
|
+
if ((c.argv || []).some((a) => SECRET_FLAG.test(String(a)))) { c.err(t('hookArg', {}, c.env)); return 2; }
|
|
267
|
+
if (action === 'show') {
|
|
268
|
+
const data = await getWakeHook(c.baseUrl, c.credOpts, { fetchImpl: c.fetchImpl });
|
|
269
|
+
const h = data && data.hook;
|
|
270
|
+
if (c.flags.json) { c.log(JSON.stringify(data || { hook: null })); return 0; }
|
|
271
|
+
if (!h) { c.log(t('hookNone', {}, c.env)); return 0; }
|
|
272
|
+
const { host, key } = hookLine(h, c.env);
|
|
273
|
+
const p = h.push || {};
|
|
274
|
+
const push = t('hookPush_' + (['ok', 'failed'].includes(p.state) ? p.state : 'pending'), { e: p.error || h.last_error || '?' }, c.env);
|
|
275
|
+
const auth = h.has_auth_token ? t('hookAuth', {}, c.env) : '';
|
|
276
|
+
c.log(t('hookShow', { host, key, auth, state: t(h.status === 'active' ? 'hookOn' : 'hookOff', {}, c.env), push }, c.env));
|
|
277
|
+
return 0;
|
|
278
|
+
}
|
|
279
|
+
if (action === 'remove') {
|
|
280
|
+
const data = await deleteWakeHook(c.baseUrl, c.credOpts, { fetchImpl: c.fetchImpl });
|
|
281
|
+
c.log(c.flags.json ? JSON.stringify(data || { ok: true }) : t('hookRemoved', {}, c.env));
|
|
282
|
+
return 0;
|
|
283
|
+
}
|
|
284
|
+
if (action !== 'set') { c.err(t('hookUsage', {}, c.env)); return 2; }
|
|
285
|
+
// Anything after the address is refused too: a value typed after an unknown flag would land here.
|
|
286
|
+
if (positionals.length > 4) { c.err(t('hookArg', {}, c.env)); return 2; }
|
|
287
|
+
const { url, token } = await readInputs(c, positionals);
|
|
288
|
+
if (!url) { c.err(t('hookUsage', {}, c.env)); return 2; }
|
|
289
|
+
let data;
|
|
290
|
+
try {
|
|
291
|
+
data = await putWakeHook(c.baseUrl, c.credOpts, token ? { url, auth_token: token } : { url }, { fetchImpl: c.fetchImpl });
|
|
292
|
+
} catch (e) {
|
|
293
|
+
const b = bodyOf(e);
|
|
294
|
+
const code = b && typeof b.error === 'string' ? b.error : '';
|
|
295
|
+
if (code === 'wake_hook_bad_url') { c.err(t('hookBadUrl', {}, c.env)); return 1; }
|
|
296
|
+
if (code === 'wake_hook_bad_host') { c.err(t('hookBadHost', {}, c.env)); return 1; }
|
|
297
|
+
if (code === 'wake_hook_bad_token') { c.err(t('hookBadToken', {}, c.env)); return 1; }
|
|
298
|
+
if (e && e.status === 429) { c.err(t('hookLater', { n: (b && b.retry_after_sec) || e.retryAfter || 60 }, c.env)); return 1; }
|
|
299
|
+
throw e;
|
|
300
|
+
}
|
|
301
|
+
if (c.flags.json) { c.log(JSON.stringify(data)); return 0; }
|
|
302
|
+
const h = (data && data.hook) || {};
|
|
303
|
+
c.log(t('hookSaved', { host: h.host || '?' }, c.env));
|
|
304
|
+
if (data && data.signing_secret) { c.log(t('hookSecret', {}, c.env)); c.log(String(data.signing_secret)); }
|
|
305
|
+
const test = (data && data.test) || {};
|
|
306
|
+
c.log(t(test.state === 'off' ? 'hookPushOffNow' : 'hookPending', {}, c.env));
|
|
307
|
+
return 0;
|
|
308
|
+
}
|
|
309
|
+
|
|
203
310
|
/**
|
|
204
|
-
* anytowork setup check | test-wake | ack | checkin
|
|
311
|
+
* anytowork setup check | test-wake | ack | checkin | wake-url
|
|
205
312
|
* @param {object} p { command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err, env }
|
|
206
313
|
*/
|
|
207
314
|
export async function runSetup(p) {
|
|
208
315
|
const c = {
|
|
209
316
|
flags: p.flags, baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl,
|
|
210
|
-
deps: p.deps || {}, log: p.log, err: p.err, env: p.env || process.env,
|
|
317
|
+
deps: p.deps || {}, log: p.log, err: p.err, env: p.env || process.env, argv: p.argv || [],
|
|
211
318
|
};
|
|
212
319
|
const sub = p.command.slice('setup:'.length);
|
|
213
320
|
const arg = p.positionals[2];
|
|
214
321
|
if (sub === 'check') return runCheck(c);
|
|
215
322
|
if (sub === 'test-wake') return runTestWake(c);
|
|
216
323
|
if (sub === 'ack') return runAck(c, arg);
|
|
324
|
+
if (sub === 'wake-url') return runWakeUrl(c, p.positionals);
|
|
217
325
|
return runCheckin(c, arg);
|
|
218
326
|
}
|
package/src/space-commands.js
CHANGED
|
@@ -13,6 +13,7 @@ import path from 'node:path';
|
|
|
13
13
|
import { apiGet, spaceTarget, taskTarget, pull, push, normalizeRemotePath, readState, SyncError, describeApiError } from './space-sync.js';
|
|
14
14
|
import { humanSize } from './media-upload.js';
|
|
15
15
|
import { readCurrentSession } from './chat-state.js';
|
|
16
|
+
import { newsLine } from './chat-commands.js';
|
|
16
17
|
import { runSpaceRead } from './space-read.js';
|
|
17
18
|
|
|
18
19
|
// ---------------------------------------------------------------- help (Chinese and English side by side)
|
|
@@ -46,6 +47,9 @@ export const SPACE_HELP = `anytowork space — 读写主人的空间 / read and
|
|
|
46
47
|
--delete 把本地删掉的文件也在空间里删除(默认不删)。 / Also delete in the space what you deleted locally (off by default).
|
|
47
48
|
--tidy 按主人的要求整理文件时加上,版本会显示为「整理」。 / Add it when tidying up for the owner; the version shows as "tidy".
|
|
48
49
|
|
|
50
|
+
writable 表示你能不能往这里写;editable 只表示能不能在线改文本,文件夹恒为 false,不代表没有权限。
|
|
51
|
+
writable says whether you may write there; editable only says whether it is text that can be edited online (always false for a folder).
|
|
52
|
+
|
|
49
53
|
以上命令都可加 --session <会话> 或 --session none(见下面「工作台」)。
|
|
50
54
|
All of them accept --session <session> or --session none (see "Workbench" below).
|
|
51
55
|
|
|
@@ -236,6 +240,7 @@ async function runLs(c) {
|
|
|
236
240
|
} else {
|
|
237
241
|
c.log(` ${n.name} ${humanSize(n.size_bytes || 0)} ${dayOf(n.updated_at)}`);
|
|
238
242
|
}
|
|
243
|
+
if (n.writable === false) c.log(' 只读'); // only a no-write node is marked; editable is not shown (it is not the permission)
|
|
239
244
|
}
|
|
240
245
|
return 0;
|
|
241
246
|
}
|
|
@@ -280,6 +285,7 @@ function reportPush(c, target, s) {
|
|
|
280
285
|
unchanged: s.unchanged, sent: s.sent, uploaded: s.uploaded.length, reused: s.reused.length, skipped: s.skipped.length,
|
|
281
286
|
bytes: s.bytes, deletes_sent: s.deletesSent, local_deleted_not_synced: s.localDeleted,
|
|
282
287
|
changes: s.changes, conflicts: s.conflicts, kept: s.kept, skipped_local: s.skippedLocal,
|
|
288
|
+
...(s.news ? { news: s.news } : {}),
|
|
283
289
|
}, null, 2));
|
|
284
290
|
return 0;
|
|
285
291
|
}
|
|
@@ -301,6 +307,7 @@ function reportPush(c, target, s) {
|
|
|
301
307
|
c.log(`本地已删除 ${s.localDeleted.length} 个文件,这次没有同步删除:${listed(s.localDeleted)}。需要同步删除时加 --delete。`);
|
|
302
308
|
}
|
|
303
309
|
if (s.skippedLocal.length) c.log(`跳过了 ${s.skippedLocal.length} 个符号链接或特殊文件:${listed(s.skippedLocal.map((x) => x.path))}`);
|
|
310
|
+
if (newsLine(s)) c.log(newsLine(s)); // v0.37.7 (B7): new messages while you were pushing
|
|
304
311
|
return 0;
|
|
305
312
|
}
|
|
306
313
|
|
package/src/space-sync.js
CHANGED
|
@@ -124,6 +124,8 @@ export function describeApiError(e) {
|
|
|
124
124
|
const vars = body.vars && typeof body.vars === 'object' ? { ...body, ...body.vars } : body;
|
|
125
125
|
const lines = [`${body.message || code}【${code}】`];
|
|
126
126
|
if (HINTS[code]) for (const h of HINTS[code](vars)) lines.push(` ${h}`);
|
|
127
|
+
// v0.37.7 (Echo 448): the platform may say WHY and what to do (e.g. the folders a hired Agent may write); print it as is
|
|
128
|
+
if (typeof body.hint === 'string' && body.hint.trim()) lines.push(` ${body.hint.trim()}`);
|
|
127
129
|
return { code, message: body.message || '', lines, body };
|
|
128
130
|
}
|
|
129
131
|
|
|
@@ -593,6 +595,7 @@ export async function push(ctx, target, dir, { note = null, tidy = false, del =
|
|
|
593
595
|
summary.changes = (done && done.changes) || [];
|
|
594
596
|
summary.conflicts = (done && done.conflicts) || [];
|
|
595
597
|
summary.kept = (done && done.kept) || [];
|
|
598
|
+
if (done && done.news) summary.news = done.news; // v0.37.7 (B7): "N new messages", printed by the command
|
|
596
599
|
|
|
597
600
|
// remember the new starting point: sent files are now what the platform has; deleted files are gone
|
|
598
601
|
const next = { ...base };
|
package/src/wb-rules-text.js
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
// Since v0.35.3 the platform sends the finished words in `rules.text` (already in the owner's language, with the
|
|
3
3
|
// extra paragraphs attached); this file only holds the same words as a fallback for an old server that sends just
|
|
4
4
|
// {key, params:{sid}}. Wording must stay identical to PRD 26 section 7.3, connect.json, llms.txt and the docs site
|
|
5
|
-
// (agent-setup); the platform's copy (WB_RULES_REV =
|
|
5
|
+
// (agent-setup); the platform's copy (WB_RULES_REV = 3) is the reference.
|
|
6
6
|
import { pickLang } from "./model-pledge.js";
|
|
7
7
|
|
|
8
|
-
export const WB_RULES_REV =
|
|
8
|
+
export const WB_RULES_REV = 3;
|
|
9
9
|
|
|
10
10
|
export const WB_RULES_TEXT = {
|
|
11
11
|
"wb.rules.full": {
|
|
12
|
-
zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句,说你收到了、打算怎么做:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3. 做的过程中隔一会儿说一两句进展:anytowork chat progress {sid} \"……\"。主人看不到动静,就分不清你是在忙还是没收到。\n4. 做完交成果:anytowork chat result {sid}",
|
|
13
|
-
en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message first: anytowork chat read {sid}\n2. Reply right away to say you got it and what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. While you work, say a line or two now and then: anytowork chat progress {sid} \"...\". If they hear nothing, they cannot tell whether you are busy or never got it.\n4. When it is done, hand in the result: anytowork chat result {sid}",
|
|
12
|
+
zh: "主人在工作台等你的回话,照这几步做:\n1. 先读消息:anytowork chat read {sid}\n2. 马上回一句,说你收到了、打算怎么做:anytowork chat send {sid} \"……\" --wip(还要接着做就带 --wip)\n3. 做的过程中隔一会儿说一两句进展:anytowork chat progress {sid} \"……\"。主人看不到动静,就分不清你是在忙还是没收到。\n4. 做完交成果:anytowork chat result {sid}\n读了消息就要有动作:回复、--wip 或 progress,三选一。只读不动,平台会再叫你一次。\n命令返回里如果提示「另有 N 条新消息」,等手头这一步做完再 chat read 一次;不要专门为了查消息多跑命令。",
|
|
13
|
+
en: "Your owner is waiting for your reply in the workbench. Do this:\n1. Read the message first: anytowork chat read {sid}\n2. Reply right away to say you got it and what you plan to do: anytowork chat send {sid} \"...\" --wip (keep --wip while you are still working)\n3. While you work, say a line or two now and then: anytowork chat progress {sid} \"...\". If they hear nothing, they cannot tell whether you are busy or never got it.\n4. When it is done, hand in the result: anytowork chat result {sid}\nOnce you read a message, act on it: reply, --wip or progress, pick one. If you only read and do nothing, the platform will call you once more.\nIf the answer of a command says there are N new messages, run chat read once after you finish the step in hand; do not run extra commands just to check for messages.",
|
|
14
14
|
},
|
|
15
15
|
"wb.rules.short": {
|
|
16
16
|
zh: "主人在等你:先读消息,先回一句收到,边做边说一两句,做完交成果。",
|