@anytowork/cli 0.12.72 → 0.12.74
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 +15 -79
- package/package.json +1 -1
- package/src/api.js +17 -50
- package/src/apply-backoff.js +5 -2
- package/src/cli-parse.js +12 -131
- package/src/config.js +34 -5
- package/src/connect.js +22 -3
- package/src/error-map.js +56 -0
- package/src/exit-reasons.js +0 -9
- package/src/format.js +77 -144
- package/src/index.js +62 -112
- package/src/model-pledge.js +6 -6
- package/src/mt/collect.js +2 -26
- package/src/mt/commands.js +3 -84
- package/src/mt/format-check.js +2 -2
- package/src/mt/readers.js +1 -1
- package/src/mt/text.js +20 -89
- package/src/mt/wake-attribution.js +2 -2
- package/src/mt/workdirs.js +1 -18
- package/src/setup-commands.js +6 -6
- package/src/setup-hints.js +3 -19
- package/src/space-commands.js +2 -41
- package/src/space-sync.js +2 -2
- package/src/chat-commands.js +0 -685
- package/src/chat-state.js +0 -77
- package/src/hire-commands.js +0 -706
- package/src/listen-command.js +0 -79
- package/src/listener/commands.js +0 -183
- package/src/listener/config.js +0 -216
- package/src/listener/hire-wake.js +0 -60
- package/src/listener/install.js +0 -233
- package/src/listener/nudge.js +0 -88
- package/src/listener/prompt.js +0 -111
- package/src/listener/queue.js +0 -112
- package/src/listener/run-error.js +0 -81
- package/src/listener/run.js +0 -723
- package/src/listener/text.js +0 -103
- package/src/mt/inrun.js +0 -351
- package/src/mt/recipes.js +0 -478
- package/src/mt/sample.js +0 -708
- package/src/reply-hint.js +0 -21
- package/src/wb-rules-text.js +0 -169
package/src/listener/text.js
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
// Always-on listener: words printed by `anytowork listen install|run|test|status|uninstall` (zh and en).
|
|
2
|
-
// They talk to the Agent that runs the command (and through it to the owner): plain words, no product names.
|
|
3
|
-
|
|
4
|
-
import { pickLang } from '../model-pledge.js';
|
|
5
|
-
|
|
6
|
-
const TEXT = {
|
|
7
|
-
// 2026-11-24: two wake-up plans only (Quick Connect): A always-on listener, B a poll every minute.
|
|
8
|
-
// v0.12.58: waking is not watching - a poll every minute is what makes the platform show it as watching.
|
|
9
|
-
'exec.missing': {
|
|
10
|
-
zh: 'ℹ 没有能启动你自己的命令时,用方案 B:每 1 分钟运行一次 anytowork poll,有新事件才启动模型。叫醒只有两种方案:方案 A 常驻监听(anytowork listen install --exec "<启动你自己的一条命令>")首选,A 不可用时用 B。poll 定时任务同时是接单和求职的盯单,用方案 A 也要保留。做法:https://anytowork.com/docs/en/guide/connect#wake',
|
|
11
|
-
en: 'ℹ No command that starts you: use Plan B, anytowork poll every minute, starting the model only when there are new events. Wake-up has two plans: Plan A, the always-on listener (anytowork listen install --exec "<the one command that starts you>"), is preferred; Plan B is for when A is unavailable. The poll job also watches for tasks and jobs, so keep it with Plan A too. Steps: https://anytowork.com/docs/en/guide/connect#wake',
|
|
12
|
-
},
|
|
13
|
-
'exec.notinstalled': {
|
|
14
|
-
zh: '这个身份还没有装常驻监听。先运行:anytowork listen install --exec "<启动你自己的一条命令>"',
|
|
15
|
-
en: 'No always-on listener is set up for this identity yet. Run first: anytowork listen install --exec "<the one command that starts you>"',
|
|
16
|
-
},
|
|
17
|
-
'install.trial': {
|
|
18
|
-
zh: '安装前先试启动一次你的命令……',
|
|
19
|
-
en: 'Starting your command once before installing...',
|
|
20
|
-
},
|
|
21
|
-
'install.trialfail': {
|
|
22
|
-
zh: '启动命令没跑通:{why}。常驻监听没有安装。请修好命令后重新运行 anytowork listen install --exec "<启动你自己的一条命令>";改了两次仍不行,或确实没有这样的命令,改用方案 B:每 1 分钟运行一次 anytowork poll。做法:https://anytowork.com/docs/en/guide/connect#plan-b',
|
|
23
|
-
en: 'The start command did not work: {why}. The always-on listener was not installed. Fix the command and run anytowork listen install --exec "<the one command that starts you>" again; if it still fails after two fixes, or you have no such command, use Plan B: anytowork poll every minute. Steps: https://anytowork.com/docs/en/guide/connect#plan-b',
|
|
24
|
-
},
|
|
25
|
-
'install.done': {
|
|
26
|
-
zh: '常驻监听已装好并开始运行。收到消息会立刻叫醒你。它只负责叫醒,不算盯单。接下来运行 anytowork listen test 试一次,把结果告诉主人。',
|
|
27
|
-
en: 'The always-on listener is set up and running. You will be woken as soon as a message arrives. It only wakes you up; it does not count as watching for tasks. Next run anytowork listen test once and tell your owner the result.',
|
|
28
|
-
},
|
|
29
|
-
'install.noautostart': {
|
|
30
|
-
zh: '配置已保存,没有设开机自启。需要时运行 anytowork listen run(保持它一直开着)。',
|
|
31
|
-
en: 'Settings saved, no start at login. Run anytowork listen run when needed (keep it running).',
|
|
32
|
-
},
|
|
33
|
-
'install.nosupervisor': {
|
|
34
|
-
zh: 'ℹ 这台机器上开机自启装不上(系统服务和开机定时项都不可用),方案 A 不可用。先运行 anytowork listen uninstall,再改用方案 B:每 1 分钟运行一次 anytowork poll,有新事件才启动模型。做法:https://anytowork.com/docs/en/guide/connect#plan-b',
|
|
35
|
-
en: 'ℹ Start at login cannot be installed on this machine (neither the service manager nor a boot-time schedule entry is available), so Plan A is unavailable. Run anytowork listen uninstall, then use Plan B: anytowork poll every minute, starting the model only when there are new events. Steps: https://anytowork.com/docs/en/guide/connect#plan-b',
|
|
36
|
-
},
|
|
37
|
-
// v0.12.61: HOME here is not the system home, so the start-at-login entry is given the login folder.
|
|
38
|
-
'install.homefallback': {
|
|
39
|
-
zh: 'ℹ 当前 HOME 与系统用户主目录不同:已把登录目录 {dir} 写进启动项,监听用它找登录,不会去读默认目录。',
|
|
40
|
-
en: 'ℹ HOME here is not the system home: the login folder {dir} is written into the start-at-login entry, so the listener finds your login there, not in the default folder.',
|
|
41
|
-
},
|
|
42
|
-
'install.linger': {
|
|
43
|
-
zh: '想让它在电脑开机后、没人登录时也运行:loginctl enable-linger',
|
|
44
|
-
en: 'To keep it running at boot even when nobody is logged in: loginctl enable-linger',
|
|
45
|
-
},
|
|
46
|
-
'install.failed': {
|
|
47
|
-
zh: '装自启失败:{err}。配置已保存,可以先用 anytowork listen run 前台运行。',
|
|
48
|
-
en: 'Setting up start at login failed: {err}. Settings are saved; you can run anytowork listen run in the foreground for now.',
|
|
49
|
-
},
|
|
50
|
-
'uninstall.done': {
|
|
51
|
-
zh: '常驻监听已停用,开机自启和配置都删了。',
|
|
52
|
-
en: 'The always-on listener is removed, with its start at login and settings.',
|
|
53
|
-
},
|
|
54
|
-
'test.start': {
|
|
55
|
-
zh: '正在用一条测试提示词试着启动你的命令……',
|
|
56
|
-
en: 'Trying your start command with a test prompt...',
|
|
57
|
-
},
|
|
58
|
-
'test.ok': {
|
|
59
|
-
zh: '启动成功(退出码 0)。常驻监听可以用了。',
|
|
60
|
-
en: 'Started fine (exit code 0). The always-on listener is ready.',
|
|
61
|
-
},
|
|
62
|
-
'test.fail': {
|
|
63
|
-
zh: '启动命令没跑通:{why}。请修好命令后重新运行 anytowork listen install,再 listen test。',
|
|
64
|
-
en: 'The start command did not work: {why}. Fix the command, run anytowork listen install again, then listen test.',
|
|
65
|
-
},
|
|
66
|
-
'why.exit': { zh: '退出码 {code}', en: 'exit code {code}' },
|
|
67
|
-
'why.timeout': { zh: '超时没结束', en: 'did not finish in time' },
|
|
68
|
-
'why.spawn': { zh: '启动不了', en: 'could not start' },
|
|
69
|
-
'run.started': {
|
|
70
|
-
zh: '常驻监听已启动,等待叫醒。',
|
|
71
|
-
en: 'The always-on listener is running and waiting for calls.',
|
|
72
|
-
},
|
|
73
|
-
'run.auth': {
|
|
74
|
-
zh: '登录状态已失效,平台不再认这个 Agent,常驻监听已停止(退出码 2)。请告诉主人:到「我的团队」里给这个 Agent 重新接入。不要自己运行 auth login(那样会变成一个新的 Agent)。',
|
|
75
|
-
en: 'The login is no longer valid, so the always-on listener stopped (exit code 2). Tell your owner to reconnect this Agent in My Team. Do not run auth login yourself (that would create a new Agent).',
|
|
76
|
-
},
|
|
77
|
-
'status.title': { zh: '常驻监听状态', en: 'Always-on listener' },
|
|
78
|
-
'status.installed.yes': { zh: '已装:是({kind})', en: 'Set up: yes ({kind})' },
|
|
79
|
-
'status.installed.noauto': { zh: '已装:是(没有设开机自启,需要保持 anytowork listen run 开着)', en: 'Set up: yes (no start at login; keep anytowork listen run open)' },
|
|
80
|
-
'status.installed.no': { zh: '已装:否', en: 'Set up: no' },
|
|
81
|
-
'status.running.yes': { zh: '在跑:是', en: 'Running: yes' },
|
|
82
|
-
'status.running.no': { zh: '在跑:否', en: 'Running: no' },
|
|
83
|
-
'status.today': { zh: '今天叫醒:{n} 次(每天最多 {max} 次)', en: 'Woken today: {n} (at most {max} a day)' },
|
|
84
|
-
'status.last.ok': { zh: '最近一次:成功({time},用时 {sec} 秒)', en: 'Latest run: ok ({time}, {sec} s)' },
|
|
85
|
-
'status.last.fail': { zh: '最近一次:失败({time},{why})', en: 'Latest run: failed ({time}, {why})' },
|
|
86
|
-
'status.last.none': { zh: '最近一次:还没有', en: 'Latest run: none yet' },
|
|
87
|
-
'status.paused': { zh: '已暂停:{why}', en: 'Paused: {why}' },
|
|
88
|
-
'status.paused.fail': { zh: '连续 {n} 次启动失败,修好命令后运行 anytowork listen test 即可恢复,24 小时后也会自动再试', en: '{n} start failures in a row; fix the command and run anytowork listen test to resume, or it tries again by itself after 24 hours' },
|
|
89
|
-
'status.paused.cap': { zh: '今天的叫醒次数到上限了,明天 0 点自动恢复', en: 'Today\'s limit is reached; it resumes at midnight' },
|
|
90
|
-
'status.paused.platform_cap': { zh: '今天的自动叫醒次数用完了,明天自动恢复;消息照常在,你自己 poll 或 chat read 都能看到', en: 'Today\'s automatic wake-ups are used up and resume tomorrow; messages are still there, poll or chat read shows them' },
|
|
91
|
-
'status.paused.platform': { zh: '平台暂时不叫醒({why}),会自动再看,恢复后继续', en: 'The platform is not waking for now ({why}); it checks again by itself and resumes' },
|
|
92
|
-
'status.node.stale': { zh: '提醒:装的时候用的 node 路径已经不在了({path}),请重新运行 anytowork listen install。', en: 'Note: the node path used at install no longer exists ({path}). Run anytowork listen install again.' },
|
|
93
|
-
'exec.sh.notice': { zh: '前台运行中(没有设开机自启),关掉这个窗口就停止。', en: 'Running in the foreground (no start at login); closing this window stops it.' },
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
export function lt(key, vars = {}, env = process.env) {
|
|
97
|
-
const e = TEXT[key];
|
|
98
|
-
let s = e ? e[pickLang(env)] : key;
|
|
99
|
-
for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
|
100
|
-
return s;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
export const LISTEN_SUBS = new Set(['install', 'run', 'test', 'status', 'uninstall']);
|
package/src/mt/inrun.js
DELETED
|
@@ -1,351 +0,0 @@
|
|
|
1
|
-
// v0.37.7 (segment 4, C2 to C4), rebuilt in v0.38.39: usage of the runs the always-on listener starts, read from this computer's own
|
|
2
|
-
// logs WHILE the Agent runs and once more when it ends.
|
|
3
|
-
//
|
|
4
|
-
// Which calls belong to which wake-up is decided by the wake-up number the prompt carries (one fixed line at its end), never by
|
|
5
|
-
// folder or time window: every reader returns the same list of events and `attributeEvents` (wake-attribution.js) is the only place
|
|
6
|
-
// that cuts it into turns. This module only takes the calls of the wake-ups its runs answer and sends them.
|
|
7
|
-
//
|
|
8
|
-
// Rows (`anytowork.usage.v2`):
|
|
9
|
-
// - logs and transcripts that keep every call: one row per call (granularity call);
|
|
10
|
-
// - session database: one CUMULATIVE row per session x model (the platform keeps the biggest value it saw);
|
|
11
|
-
// - run-log database totals: one row per run, always `window` (shown, not priced: the log has no outside messages to read a number from).
|
|
12
|
-
// `attribution`: `run` (turn of one number: priced) or `window` (could not be told apart: shown, not priced).
|
|
13
|
-
// Each row carries `task_ref {wake_id, session_id, basis: 'wake_label', segment}`; the platform finds the hire from the wake-up itself.
|
|
14
|
-
// Nothing here sends prompts, answers or file contents; only numbers, model names, times and ids.
|
|
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.
|
|
21
|
-
|
|
22
|
-
import os from 'node:os';
|
|
23
|
-
import path from 'node:path';
|
|
24
|
-
import { readMsgLog, readRollout, readDshLog, readSessionModelUsage, readRunLog, readTranscriptUsage, guessProvider } from './readers.js';
|
|
25
|
-
import { readState, writeState, sendRows, sha256, isZero, localKey } from './collect.js';
|
|
26
|
-
import { readRegistry, workdirForPath } from './workdirs.js';
|
|
27
|
-
import { attributeEvents } from './wake-attribution.js';
|
|
28
|
-
import { liveRecipes, readRecipeEvents, recipeProgramOf } from './recipes.js';
|
|
29
|
-
|
|
30
|
-
export const SCHEMA_V2 = 'anytowork.usage.v2';
|
|
31
|
-
export const INRUN_DEFAULT_SEC = 60; // MT_INRUN_UPLOAD_SEC default (the platform sends `inrun_upload_sec` in listener.limits)
|
|
32
|
-
const START_SLACK_MS = 5000; // a session / log line may be stamped a little before the start we noted
|
|
33
|
-
const SETTLE_MS = 60_000; // a call seen less than this long ago may still be streaming into the log
|
|
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)
|
|
38
|
-
|
|
39
|
-
/** The reference a row carries: the wake-up number found in the prompt (the platform derives the hire / task from it). */
|
|
40
|
-
export function buildTaskRef({ sid, wakeId, segment, basis, wakeIds }) {
|
|
41
|
-
const ref = { session_id: sid, wake_id: wakeId || '' };
|
|
42
|
-
if (basis) ref.basis = basis;
|
|
43
|
-
if (segment) ref.segment = segment;
|
|
44
|
-
const ids = [...new Set((wakeIds || []).map(String).filter((x) => /^[0-9a-f-]{36}$/i.test(x)))].slice(-10);
|
|
45
|
-
if (ids.length > 1) ref.wake_ids = ids;
|
|
46
|
-
return ref;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* How the in-run upload runs for this listener: `{enabled, intervalMs}`.
|
|
51
|
-
* The platform's `inrun_upload_sec` (listener.limits) wins; 0 switches the whole in-run upload off and the idle upload
|
|
52
|
-
* (every 10 minutes while nothing runs) takes over. `ANYTOWORK_INRUN_UPLOAD_SEC` on this computer can set the interval
|
|
53
|
-
* (0 = off). Not less than 30 seconds, except `cfg.inrunUploadMs` (tests; 0 = only the upload at the end of a run).
|
|
54
|
-
*/
|
|
55
|
-
export function inrunSettings(cfg, state, env = process.env) {
|
|
56
|
-
const platRaw = state && state.limits ? state.limits.inrun_upload_sec : undefined;
|
|
57
|
-
const plat = platRaw != null && Number.isFinite(Number(platRaw)) ? Number(platRaw) : null;
|
|
58
|
-
const envRaw = env && env.ANYTOWORK_INRUN_UPLOAD_SEC;
|
|
59
|
-
const envSec = envRaw != null && envRaw !== '' && Number.isFinite(Number(envRaw)) ? Number(envRaw) : null;
|
|
60
|
-
if (plat === 0 || envSec === 0) return { enabled: false, intervalMs: null };
|
|
61
|
-
if (cfg && cfg.inrunUploadMs != null) return { enabled: true, intervalMs: Number(cfg.inrunUploadMs) > 0 ? Number(cfg.inrunUploadMs) : null };
|
|
62
|
-
const sec = envSec != null ? envSec : (plat != null ? plat : INRUN_DEFAULT_SEC);
|
|
63
|
-
return { enabled: true, intervalMs: Math.max(30, sec) * 1000 };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function norm(p) { try { return path.resolve(String(p)); } catch { return null; } }
|
|
67
|
-
|
|
68
|
-
/** The program a start command names (first word of a path or `exec`), or null when it is a wrapper we cannot tell. */
|
|
69
|
-
export function programOfCommand(command) {
|
|
70
|
-
const words = String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
|
|
71
|
-
for (const w of words.slice(0, 6)) {
|
|
72
|
-
const b = path.basename(w).toLowerCase().replace(/\.(?:exe|cmd|sh|js|mjs)$/, '');
|
|
73
|
-
if (b === 'hermes') return 'hermes';
|
|
74
|
-
if (b === 'openclaw') return 'openclaw';
|
|
75
|
-
if (b === 'claude') return 'claude_code';
|
|
76
|
-
if (b === 'codex') return 'codex';
|
|
77
|
-
if (b === 'dsh') return 'dsh';
|
|
78
|
-
const viaRecipe = recipeProgramOf(b);
|
|
79
|
-
if (viaRecipe) return viaRecipe;
|
|
80
|
-
}
|
|
81
|
-
return null;
|
|
82
|
-
}
|
|
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
|
-
|
|
89
|
-
function callRow(c, ctx) {
|
|
90
|
-
const row = {
|
|
91
|
-
schema: SCHEMA_V2,
|
|
92
|
-
granularity: 'call',
|
|
93
|
-
call_id: String(c.call_id).trim().slice(0, 200),
|
|
94
|
-
conversation_id: String(c.conversation_id).slice(0, 200),
|
|
95
|
-
provider: String(c.provider || 'unknown').toLowerCase().slice(0, 60),
|
|
96
|
-
model: String(c.model).slice(0, 120),
|
|
97
|
-
started_at: c.started_at,
|
|
98
|
-
input_tokens: c.input_tokens,
|
|
99
|
-
output_tokens: c.output_tokens,
|
|
100
|
-
cache_write_tokens: c.cache_write_tokens || 0,
|
|
101
|
-
cache_read_tokens: c.cache_read_tokens || 0,
|
|
102
|
-
program: ctx.program,
|
|
103
|
-
reader: ctx.reader,
|
|
104
|
-
attribution: ctx.attribution,
|
|
105
|
-
task_ref: ctx.taskRef,
|
|
106
|
-
source: 'local-log',
|
|
107
|
-
};
|
|
108
|
-
if (c.reasoning_tokens != null) row.reasoning_tokens = c.reasoning_tokens;
|
|
109
|
-
if (c.unreadable_fields && c.unreadable_fields.length) row.unreadable_fields = c.unreadable_fields;
|
|
110
|
-
if (c.message_id) row.message_id = String(c.message_id).slice(0, 200);
|
|
111
|
-
if (c.request_model) row.request_model = String(c.request_model).slice(0, 120);
|
|
112
|
-
if (c.ended_at && c.ended_at !== c.started_at) row.ended_at = c.ended_at;
|
|
113
|
-
if (c.cwd) row.project_dir_hash = sha256(norm(c.cwd) || c.cwd);
|
|
114
|
-
if (ctx.workdirId) row.workdir_id = ctx.workdirId;
|
|
115
|
-
return row;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function isoSec(ms) { return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'); }
|
|
119
|
-
|
|
120
|
-
export class RunUsageTracker {
|
|
121
|
-
/** @param {object} p { baseUrl, credOpts, fetchImpl, env, home, sqlite, nowMs, log } */
|
|
122
|
-
constructor(p) {
|
|
123
|
-
this.baseUrl = p.baseUrl;
|
|
124
|
-
this.credOpts = p.credOpts;
|
|
125
|
-
this.fetchImpl = p.fetchImpl;
|
|
126
|
-
this.env = p.env || process.env;
|
|
127
|
-
this.home = p.home || os.homedir();
|
|
128
|
-
this.sqlite = p.sqlite; // undefined: load the built-in module when needed; null: none
|
|
129
|
-
this.nowMs = p.nowMs || Date.now;
|
|
130
|
-
this.log = p.log || (() => {});
|
|
131
|
-
this.runs = [];
|
|
132
|
-
this.seq = 0;
|
|
133
|
-
this.off = false; // the platform said the feature is off: stop trying in this process
|
|
134
|
-
this.chain = Promise.resolve(); // uploads one after another: they share one local state file
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/** A run starts. `wakeIds`: every wake-up this run answers (a merged job has several). Folders are no longer used to tell runs apart. */
|
|
138
|
-
begin({ sid, wakeId, command, startMs, wakeIds }) {
|
|
139
|
-
const now = this.nowMs();
|
|
140
|
-
this.runs = this.runs.filter((x) => x.endMs == null || now - x.endMs < KEEP_FINISHED_MS);
|
|
141
|
-
const ids = new Set([...(wakeIds || []), wakeId].filter(Boolean).map((x) => String(x).toLowerCase()));
|
|
142
|
-
const r = {
|
|
143
|
-
seq: (this.seq += 1), sid, startMs: startMs != null ? startMs : now, endMs: null,
|
|
144
|
-
wakeIds: ids,
|
|
145
|
-
tokens: String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter((t) => t.length >= 4 && !t.startsWith('-') && /[:_-]/.test(t)),
|
|
146
|
-
prog: programOfCommand(command),
|
|
147
|
-
cum: new Map(), // `session|model` -> totals already sent
|
|
148
|
-
sentAny: false,
|
|
149
|
-
};
|
|
150
|
-
r.key = runKey(sid, ids);
|
|
151
|
-
this.runs.push(r);
|
|
152
|
-
if (ids.size) this.#queue(() => this.#remember(r));
|
|
153
|
-
return r;
|
|
154
|
-
}
|
|
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
|
-
|
|
213
|
-
/** Queue one upload of what the run has so far (`final`: the run ended, no settle time). */
|
|
214
|
-
upload(r, { final = false } = {}) {
|
|
215
|
-
const next = this.chain.then(() => this.#upload(r, final)).catch(() => null);
|
|
216
|
-
this.chain = next;
|
|
217
|
-
return next;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/** The run ended: remember when, then send the last batch. */
|
|
221
|
-
finish(r) {
|
|
222
|
-
r.endMs = this.nowMs();
|
|
223
|
-
return this.upload(r, { final: true });
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
async #upload(r, final) {
|
|
227
|
-
if (this.off || !r.wakeIds.size) return null;
|
|
228
|
-
const now = this.nowMs();
|
|
229
|
-
const since = r.startMs - START_SLACK_MS;
|
|
230
|
-
const settleMs = final ? 0 : SETTLE_MS;
|
|
231
|
-
const { home, env } = this;
|
|
232
|
-
const state = readState(this.credOpts);
|
|
233
|
-
const registry = (() => { try { return readRegistry(this.credOpts); } catch { return {}; } })();
|
|
234
|
-
const wdCache = new Map();
|
|
235
|
-
const workdirOf = (cwd) => { try { const w = workdirForPath(cwd, registry, wdCache); return w ? w.workdir_id : null; } catch { return null; } };
|
|
236
|
-
const rows = [];
|
|
237
|
-
const pendingCum = [];
|
|
238
|
-
const heldSessions = [];
|
|
239
|
-
|
|
240
|
-
// 1. every reader gives the same event list; one shared function cuts it into turns
|
|
241
|
-
const events = [];
|
|
242
|
-
const tag = (read, program, reader) => {
|
|
243
|
-
try {
|
|
244
|
-
const out = read();
|
|
245
|
-
return Promise.resolve(out).then((o) => { for (const c of o.calls || []) c.__src = { program, reader }; for (const s of o.sessions || []) s.__src = { program: 'hermes', reader: 'cli:session_model_usage' }; events.push(...(o.events || [])); return o; }).catch(() => null);
|
|
246
|
-
} catch { return Promise.resolve(null); }
|
|
247
|
-
};
|
|
248
|
-
await Promise.all([
|
|
249
|
-
tag(() => readMsgLog({ home, env, sinceMs: since, log: this.log }), 'claude_code', 'cli:msg_log'),
|
|
250
|
-
tag(() => readRollout({ home, env, sinceMs: since, log: this.log }), 'codex', 'cli:rollout'),
|
|
251
|
-
tag(() => readDshLog({ home, env, sinceMs: since, log: this.log }), 'dsh', 'cli:dsh_log'),
|
|
252
|
-
tag(() => readSessionModelUsage({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log }), 'hermes', 'cli:session_model_usage'),
|
|
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}`)),
|
|
256
|
-
]);
|
|
257
|
-
const { rows: owned, dropped } = attributeEvents(events);
|
|
258
|
-
for (const o of owned) {
|
|
259
|
-
if (!r.wakeIds.has(o.wakeId)) continue;
|
|
260
|
-
const c = o.call;
|
|
261
|
-
const src = c.__src || {};
|
|
262
|
-
const taskRef = buildTaskRef({ sid: r.sid, wakeId: o.wakeId, segment: o.segment, basis: 'wake_label', wakeIds: [...r.wakeIds] });
|
|
263
|
-
if (c.models) {
|
|
264
|
-
// session database: one total per session x model, taken whole
|
|
265
|
-
if (c.startedMs < since) continue;
|
|
266
|
-
heldSessions.push(c.id);
|
|
267
|
-
for (const m of c.models) {
|
|
268
|
-
const sig = `${c.id}|${m.model}`;
|
|
269
|
-
const totals = `${m.input_tokens}|${m.output_tokens}|${m.cache_write_tokens}|${m.cache_read_tokens}|${m.reasoning_tokens}`;
|
|
270
|
-
if (r.cum.get(sig) === totals) continue;
|
|
271
|
-
const row = {
|
|
272
|
-
schema: SCHEMA_V2, kind: 'cumulative', granularity: 'cumulative',
|
|
273
|
-
source_session_key: c.id, conversation_id: c.id,
|
|
274
|
-
provider: guessProvider(m.model), model: m.model.slice(0, 120),
|
|
275
|
-
started_at: isoSec(c.startedMs), ended_at: isoSec(c.lastSeenMs || c.startedMs),
|
|
276
|
-
input_tokens: m.input_tokens, output_tokens: m.output_tokens, cache_write_tokens: m.cache_write_tokens, cache_read_tokens: m.cache_read_tokens,
|
|
277
|
-
reasoning_tokens: m.reasoning_tokens,
|
|
278
|
-
program: 'hermes', reader: 'cli:session_model_usage', attribution: o.attribution,
|
|
279
|
-
task_ref: taskRef, source: 'local-log',
|
|
280
|
-
};
|
|
281
|
-
if (isZero(row)) continue;
|
|
282
|
-
rows.push(row);
|
|
283
|
-
pendingCum.push([sig, totals]);
|
|
284
|
-
}
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
if (c.seenMs < since || c.seenMs > now - settleMs) continue;
|
|
288
|
-
rows.push(callRow(c, { program: src.program, reader: src.reader, attribution: o.attribution, taskRef, workdirId: workdirOf(c.cwd) }));
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// 2. run-log database totals of the session key the start command names: no outside messages in it, so shown only
|
|
292
|
-
if (r.tokens.length && (!r.prog || r.prog === 'openclaw')) {
|
|
293
|
-
const mine = (c) => {
|
|
294
|
-
const key = c.session_key || '';
|
|
295
|
-
return r.tokens.some((t) => t === key || t === c.session_id || (key && key.endsWith(`:${t}`)));
|
|
296
|
-
};
|
|
297
|
-
const live = new Set(owned.filter((o) => o.call.__src && o.call.__src.reader === 'cli:transcript_db').map((o) => o.call.session_id));
|
|
298
|
-
try {
|
|
299
|
-
const oc = await readRunLog({ home, env, sinceMs: since, sqlite: this.sqlite, log: this.log, verdictKnown: true });
|
|
300
|
-
for (const c of oc.calls) {
|
|
301
|
-
if (c.seenMs < since || c.seenMs > now - settleMs || !mine(c)) continue;
|
|
302
|
-
if (live.has(c.session_id) || (state.perCallReported || {})[c.session_id]) continue; // the session already has its calls one by one
|
|
303
|
-
rows.push(callRow(c, { program: 'openclaw', reader: 'cli:run_db', attribution: 'window', taskRef: buildTaskRef({ sid: r.sid, wakeId: [...r.wakeIds][0], basis: 'session_key' }) }));
|
|
304
|
-
}
|
|
305
|
-
} catch { /* same */ }
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
const nDropped = Object.values(dropped).reduce((x, y) => x + y, 0);
|
|
309
|
-
if (nDropped) {
|
|
310
|
-
this.lastDropped = dropped;
|
|
311
|
-
this.log(`usage: ${nDropped} calls not taken (${Object.entries(dropped).map(([k, v]) => `${k} x${v}`).join(', ')})`);
|
|
312
|
-
state.lastDropped = { at: new Date(now).toISOString(), reasons: dropped };
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
// what was already sent is not sent again (calls: the local list shared with the idle upload)
|
|
316
|
-
const seen = new Set();
|
|
317
|
-
const fresh = [];
|
|
318
|
-
for (const row of rows) {
|
|
319
|
-
if (row.kind === 'cumulative') { fresh.push(row); continue; }
|
|
320
|
-
if (isZero(row)) continue;
|
|
321
|
-
const k = localKey(row);
|
|
322
|
-
if (seen.has(k) || state.sent[k]) continue;
|
|
323
|
-
seen.add(k);
|
|
324
|
-
fresh.push(row);
|
|
325
|
-
}
|
|
326
|
-
if (final) markSummariesSent(state, heldSessions);
|
|
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 }; }
|
|
329
|
-
const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
|
|
330
|
-
if (tot.featureOff) { this.off = true; settled(); }
|
|
331
|
-
if (!tot.error && !tot.featureOff) {
|
|
332
|
-
settled();
|
|
333
|
-
if (fresh.some((x) => x.reader === 'cli:transcript_db')) {
|
|
334
|
-
// remembered across rounds (and restarts): a later round that cannot read the transcript must not add the run total
|
|
335
|
-
state.perCallReported = state.perCallReported || {};
|
|
336
|
-
for (const x of fresh) if (x.reader === 'cli:transcript_db') state.perCallReported[x.conversation_id] = now;
|
|
337
|
-
}
|
|
338
|
-
for (const [sig, totals] of pendingCum) r.cum.set(sig, totals);
|
|
339
|
-
r.sentAny = true;
|
|
340
|
-
// one line per successful upload: how many rows and which wake-up(s); no content, no tokens
|
|
341
|
-
this.log(`usage: uploaded ${fresh.length} rows wake=${[...r.wakeIds].join(",") || "-"}`);
|
|
342
|
-
}
|
|
343
|
-
writeState(this.credOpts, state, now);
|
|
344
|
-
return { sent: fresh.length, tot, dropped, ok: !tot.error && !tot.featureOff };
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/** The idle upload sends a finished session of the session database as one summary row; a session already sent live must not go twice. */
|
|
349
|
-
function markSummariesSent(state, sessionIds) {
|
|
350
|
-
for (const id of sessionIds) state.sent[`s:s-${sha256(String(id)).slice(0, 32)}`] = Date.now();
|
|
351
|
-
}
|