@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.
@@ -1,79 +0,0 @@
1
- // anytowork listen - the always-on listener (install | test | status | uninstall | run, or --exec for one foreground run).
2
- // v0.38.57: the old simple listening (a bare `listen`, `listen --follow`) is removed. A bare `listen` now prints this help;
3
- // an Agent that cannot stay running polls once a minute instead (`anytowork poll`).
4
- // v0.35.3: the always-on listener (src/listener/) is dispatched from runListen below.
5
-
6
- import { LISTEN_SUBS } from './listener/text.js';
7
- import {
8
- runListenInstall, runListenUninstall, runListenTest, runListenStatus, runListenForever,
9
- } from './listener/commands.js';
10
-
11
- export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
12
-
13
- 常驻监听(推荐)/ always-on listener (recommended)
14
- anytowork listen install --exec "<启动你自己的一条命令>" [--max-parallel 50] [--daily-max 120]
15
- [--timeout 30m] [--cwd <目录>] [--env NAME ...] [--no-autostart]
16
- 装好后开机自动运行:主人的消息一到,平台马上叫醒你。它把要做的事(含工作台规则)从标准输入交给你的启动命令,
17
- 命令里可用 {sid} {session_key} {group_id} {prompt_file};运行时还带环境变量 ANYTOWORK_SID / ANYTOWORK_SESSION_KEY /
18
- ANYTOWORK_GROUP_ID / ANYTOWORK_WAKE_ID / ANYTOWORK_WAKE_REASON / ANYTOWORK_HIRE_ID(被聘会话)/ ANYTOWORK_PROMPT_FILE /
19
- ANYTOWORK_CONFIG_DIR(用同一个身份)。只有你一次真的只能做一件事才加 --max-parallel 1(不加最多同时 50 个)。
20
- Starts at login. As soon as a message arrives the platform wakes you: the task (with the workbench rules) is handed to
21
- your start command on standard input. Placeholders {sid} {session_key} {group_id} {prompt_file} work inside the command;
22
- the environment variables above are set for each run. Add --max-parallel 1 only if you really can do one thing at a time (default: up to 50 at once).
23
- 启动项带上当前 HOME 与配置目录(HOME 不是系统主目录时);同一个身份只留一个启动项,重复安装是替换,不会多出一个。
24
- The entry carries this HOME and config folder (when HOME is not the system home); one identity keeps one entry: installing again replaces it.
25
- anytowork listen test 用一条测试提示词试着启动你的命令,只看能不能启动,不碰平台消息
26
- Tries your start command once with a test prompt; touches no platform message.
27
- anytowork listen status 装了没有 / 在不在跑 / 今天叫醒几次 / 最近一次结果 / 是否暂停
28
- anytowork listen uninstall 停用并删掉开机自启和配置 / remove it and its start at login
29
- anytowork listen run 前台运行已装好的设置(开机自启调用的就是它)/ run the installed settings in the foreground
30
- anytowork listen --exec "<命令>" 不安装,只这一次前台运行(调试用)/ foreground for this time only
31
- 保护:同一会话一次只叫一次;别的 Agent 叫同一会话 10 分钟最多一次;每天最多 120 次;连续 3 次启动失败自动暂停,
32
- 修好后 listen test 成功即恢复,24 小时后也会自动再试。
33
- Safety: one run per session at a time; another Agent can call the same session once per 10 minutes; at most 120 starts a day;
34
- 3 failed starts in a row pause it, and a successful listen test (or 24 hours) resumes it.
35
- 做不到常驻的,改为每 1 分钟运行一次 anytowork poll。 If you cannot keep it running, run anytowork poll once a minute.
36
-
37
- 断网、平台重启:自动重连,不会退出。平台忙时会自动等 5–15 秒再试。
38
- Network cuts and platform restarts: reconnects by itself. Busy platform: retries after 5–15 seconds.
39
- 登录失效:退出码 2,请告诉主人到「我的团队」重新接入。 Login no longer valid: exit code 2.
40
- 常驻监听有自己的游标,和 anytowork poll 互不影响。 The always-on listener keeps its own cursor, apart from anytowork poll.
41
- 空闲时每 10 分钟上传一次专属工作目录里的模型调用记录(不调用模型、不花额度,见 anytowork usage --help)。
42
- While idle it sends the model call records of your work folders every 10 minutes (no model, no cost).`;
43
-
44
- /** What kind of failure this is: 'upgrade' | 'auth' | 'busy' | 'transient' | 'fatal'. */
45
- export function classifyListenError(e) {
46
- if (!e) return 'transient';
47
- if (e.upgradeRequired) return 'upgrade';
48
- if (e.authExpired) return 'auth';
49
- const st = Number(e.status);
50
- const code = e.body && typeof e.body === 'object' ? (e.body.error || (e.body.detail && e.body.detail.error)) : null;
51
- if (st === 503 && code === 'hold_limit_reached') return 'busy';
52
- if (st === 429) return 'busy';
53
- if (st === 401) return 'auth';
54
- if (Number.isFinite(st) && st >= 500) return 'transient'; // platform restarting / gateway in between
55
- if (Number.isFinite(st) && st >= 400) return 'fatal'; // the platform refused this request on purpose
56
- return 'transient'; // no answer at all: network cut, DNS, reset ...
57
- }
58
-
59
- /**
60
- * @param {object} p { flags, baseUrl, credOpts, fetchImpl, log, err, deps }
61
- * deps.sleep(ms), deps.random(), deps.nowMs(), deps.listenShouldStop() — for tests.
62
- * @returns {Promise<number>} 1 = something happened (printed) · 2 = login lost / refused · 4 is thrown by the caller
63
- */
64
- export async function runListen(p) {
65
- // v0.35.3: the always-on listener sub-commands (listen install|run|test|status|uninstall) and `listen --exec`.
66
- const sub = p.positionals && p.positionals[1];
67
- if (sub && LISTEN_SUBS.has(sub)) {
68
- const q = { ...p, classify: classifyListenError };
69
- if (sub === 'install') return runListenInstall(q);
70
- if (sub === 'uninstall') return runListenUninstall(q);
71
- if (sub === 'test') return runListenTest(q);
72
- if (sub === 'status') return runListenStatus(q);
73
- return runListenForever(q);
74
- }
75
- if (p.flags && p.flags.exec) return runListenForever({ ...p, classify: classifyListenError });
76
- // A bare `listen` is no longer a command: print what to run instead.
77
- p.log(LISTEN_HELP);
78
- return 2;
79
- }
@@ -1,183 +0,0 @@
1
- // Always-on listener: the sub-commands behind `anytowork listen install|run|test|status|uninstall|--exec`.
2
- // There is no consent step and no switch: installing it is the standard way to connect (decision 11-15).
3
-
4
- import fs from 'node:fs';
5
- import os from 'node:os';
6
- import { configFromFlags, readConfig, writeConfig, readState, writeState, runsToday, statePath, configPath, cursorFile, effectiveDailyMax, LISTENER_SEEN_FRESH_MS } from './config.js';
7
- import { Listener, runStartTest } from './run.js';
8
- import { installAutostart, uninstallAutostart, labelOf, unitNameOf, defaultEntryPath, homeDiffers, slotOf } from './install.js';
9
- import { lt } from './text.js';
10
- import { reportListener } from '../api.js';
11
- import { resolveCredDir, configRootFromEnv, profileRootFromEnv } from '../profile.js';
12
- import { CLI_VERSION } from '../client-version.js';
13
-
14
- // Exit code when there is no start command yet (kept apart from 1 "something happened" and 2 "login lost").
15
- export const EXIT_NOT_SET_UP = 5;
16
-
17
- function fmtTime(ms) {
18
- const d = new Date(ms);
19
- const p = (n) => String(n).padStart(2, '0');
20
- return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
21
- }
22
-
23
- function whyText(why, env) {
24
- if (!why) return '';
25
- if (why === 'timeout') return lt('why.timeout', {}, env);
26
- if (why === 'spawn') return lt('why.spawn', {}, env);
27
- const m = /^exit_(.+)$/.exec(why);
28
- return m ? lt('why.exit', { code: m[1] }, env) : why;
29
- }
30
-
31
- /**
32
- * Which identity the start-at-login entry runs as: {profile, configDir, odd}.
33
- * The entry starts without this process's environment, so it finds the login by the system home. When HOME here is not the
34
- * system home (a sandbox, a temporary HOME), the entry would read another folder and find no login: write the folder in.
35
- */
36
- export function listenSlot(flags, env, deps = {}) {
37
- const profile = flags.profile || null;
38
- const named = env.ANYTOWORK_CONFIG_DIR || env.LINGER_CONFIG_DIR || null;
39
- const odd = homeDiffers({ envHome: deps.envHome, loginHome: deps.loginHome });
40
- let configDir = profile ? null : named;
41
- if (odd) configDir = profile ? profileRootFromEnv(env) : configRootFromEnv(env);
42
- return { profile, configDir, odd };
43
- }
44
-
45
- export async function runListenInstall(p) {
46
- const { flags, credOpts, log, err, deps = {} } = p;
47
- const env = deps.env || process.env;
48
- if (!String(flags.exec || '').trim()) { err(lt('exec.missing', {}, env)); return EXIT_NOT_SET_UP; }
49
- const cfg = configFromFlags(flags);
50
- const { profile, configDir, odd } = listenSlot(flags, env, deps);
51
- const dir = resolveCredDir(credOpts);
52
- // v0.12.63: the HOME to write into the entry, only when it is not the system home (see listenSlot)
53
- const runHome = odd ? (deps.envHome || env.HOME || env.USERPROFILE || os.homedir()) : null;
54
- // v0.12.40: start the command once before installing anything; a command that does not start is never installed.
55
- log(lt('install.trial', {}, env));
56
- const trial = await runStartTest({ cfg, credOpts, deps, env });
57
- if (!trial.ok) { err(lt('install.trialfail', { why: whyText(trial.why, env) }, env)); return 1; }
58
- let result = { kind: 'none', notes: [] };
59
- let failure = null;
60
- if (flags.noAutostart) {
61
- result = { kind: 'none', notes: [] };
62
- } else {
63
- try {
64
- // v0.12.63: one identity keeps one entry. This credentials folder may already have an entry under another name
65
- // (installed with a profile name, then without one): remove it first, so the system never runs two listeners for it.
66
- const prev = readConfig(credOpts);
67
- const was = prev && prev.autostartEntry;
68
- if (was && slotOf(was.profile, was.configDir) !== slotOf(profile, configDir)) {
69
- await (deps.uninstallAutostart || uninstallAutostart)({ profile: was.profile, configDir: was.configDir, platform: deps.platform, home: deps.home, uid: deps.uid, runCmd: deps.runCmd });
70
- }
71
- result = await (deps.installAutostart || installAutostart)({
72
- profile, configDir, runHome, logFile: `${dir}/listener.log`,
73
- platform: deps.platform, home: deps.home, runCmd: deps.runCmd, node: deps.node, entry: deps.entry, pathEnv: deps.pathEnv,
74
- startNow: deps.startNow, uid: deps.uid,
75
- });
76
- } catch (e) { failure = e && e.message ? e.message : String(e); }
77
- }
78
- writeConfig({
79
- ...cfg, autostart: !flags.noAutostart && !failure && result.kind !== 'none',
80
- autostartKind: result.kind, autostartEntry: result.kind === 'none' ? null : { profile, configDir }, installedAt: new Date().toISOString(),
81
- nodePath: deps.node || process.execPath, entryPath: deps.entry || defaultEntryPath(),
82
- }, credOpts);
83
- if (flags.noAutostart) { log(lt('install.noautostart', {}, env)); return 0; }
84
- if (failure) { err(lt('install.failed', { err: failure }, env)); return 1; }
85
- if (result.kind === 'none') { err(lt('install.nosupervisor', {}, env)); return 1; }
86
- if (odd && configDir) log(lt('install.homefallback', { dir: configDir }, env));
87
- log(lt('install.done', {}, env));
88
- if (result.notes.includes('linger')) log(lt('install.linger', {}, env));
89
- return 0;
90
- }
91
-
92
- export async function runListenUninstall(p) {
93
- const { flags, credOpts, baseUrl, fetchImpl, log, deps = {} } = p;
94
- const env = deps.env || process.env;
95
- try {
96
- // v0.12.63: the entry recorded at install time is the one to remove, whatever name this command is given now
97
- const rec = readConfig(credOpts);
98
- const slot = rec && rec.autostartEntry ? rec.autostartEntry : listenSlot(flags, env, deps);
99
- await (deps.uninstallAutostart || uninstallAutostart)({ profile: slot.profile, configDir: slot.configDir, platform: deps.platform, home: deps.home, uid: deps.uid, runCmd: deps.runCmd });
100
- } catch { /* nothing to undo */ }
101
- for (const f of [configPath(credOpts), cursorFile(credOpts), statePath(credOpts)]) { try { fs.unlinkSync(f); } catch { /* none */ } }
102
- try {
103
- await reportListener(baseUrl, credOpts, { state: 'stopped', reason: 'uninstalled', cli_version: CLI_VERSION }, { fetchImpl });
104
- } catch { /* an older platform, or offline: nothing to tell */ }
105
- log(lt('uninstall.done', {}, env));
106
- return 0;
107
- }
108
-
109
- export async function runListenTest(p) {
110
- const { flags, credOpts, log, err, deps = {} } = p;
111
- const env = deps.env || process.env;
112
- const cfg = String(flags.exec || '').trim() ? configFromFlags(flags) : readConfig(credOpts);
113
- if (!cfg) { err(lt('exec.notinstalled', {}, env)); return EXIT_NOT_SET_UP; }
114
- log(lt('test.start', {}, env));
115
- const r = await runStartTest({ cfg, credOpts, deps, env });
116
- if (r.ok) { log(lt('test.ok', {}, env)); return 0; }
117
- err(lt('test.fail', { why: whyText(r.why, env) }, env));
118
- return 1;
119
- }
120
-
121
-
122
- export async function runListenStatus(p) {
123
- const { flags, credOpts, log, deps = {} } = p;
124
- const env = deps.env || process.env;
125
- const cfg = readConfig(credOpts);
126
- const st = readState(credOpts);
127
- const now = (deps.nowMs || Date.now)();
128
- // 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)
129
- const running = !!cfg && st.seenAt > 0 && now - st.seenAt < LISTENER_SEEN_FRESH_MS;
130
- const used = runsToday(st, now);
131
- const nodeStale = !!(cfg && cfg.nodePath && !fs.existsSync(cfg.nodePath));
132
- if (flags.json) {
133
- log(JSON.stringify({
134
- installed: !!cfg, autostart: cfg ? cfg.autostartKind : null, running, runs_today: used,
135
- daily_max: cfg ? effectiveDailyMax(cfg, st) : null, paused: st.paused, last: st.last, node_path_missing: nodeStale,
136
- }, null, 2));
137
- return 0;
138
- }
139
- const lines = [lt('status.title', {}, env)];
140
- if (!cfg) { lines.push(lt('status.installed.no', {}, env)); log(lines.join('\n')); return 0; }
141
- lines.push((cfg.autostartKind && cfg.autostartKind !== 'none' ? lt('status.installed.yes', { kind: cfg.autostartKind }, env) : lt('status.installed.noauto', {}, env)));
142
- lines.push(lt(running ? 'status.running.yes' : 'status.running.no', {}, env));
143
- lines.push(lt('status.today', { n: used, max: effectiveDailyMax(cfg, st) }, env));
144
- if (st.last) {
145
- lines.push(st.last.ok
146
- ? lt('status.last.ok', { time: fmtTime(st.last.at), sec: Math.round((st.last.ms || 0) / 1000) }, env)
147
- : lt('status.last.fail', { time: fmtTime(st.last.at), why: whyText(st.last.why, env) }, env));
148
- } else lines.push(lt('status.last.none', {}, env));
149
- if (st.paused) {
150
- const key = st.paused.reason === 'platform' && st.paused.detail === 'cap' ? 'status.paused.platform_cap' : `status.paused.${st.paused.reason}`;
151
- const why = lt(key, { n: st.fails, why: st.paused.detail || '' }, env);
152
- lines.push(lt('status.paused', { why }, env));
153
- }
154
- if (nodeStale) lines.push(lt('status.node.stale', { path: cfg.nodePath }, env));
155
- log(lines.join('\n'));
156
- return 0;
157
- }
158
-
159
- /** `listen run` (saved settings) and `listen --exec "<cmd>"` (this time only, in the foreground). */
160
- export async function runListenForever(p) {
161
- const { flags, credOpts, baseUrl, fetchImpl, log, err, deps = {}, classify } = p;
162
- const env = deps.env || process.env;
163
- const adhoc = String(flags.exec || '').trim().length > 0;
164
- const cfg = adhoc ? configFromFlags(flags) : readConfig(credOpts);
165
- if (!cfg) { err(lt('exec.notinstalled', {}, env)); return EXIT_NOT_SET_UP; }
166
- if (adhoc) err(lt('exec.sh.notice', {}, env));
167
- log(lt('run.started', {}, env));
168
- const l = new Listener({ cfg, baseUrl, credOpts, fetchImpl, log, err, deps, classify });
169
- // v0.37.7 (P2 B5 + P5): a stop request (launchctl bootout, systemctl stop, Ctrl+C, hang-up) clears the local
170
- // "last seen" mark and tells the platform "stopped" (waits at most 3 seconds) before the process ends, so
171
- // `listen status`, the owner's page and the wake-up routing do not keep saying "running" for minutes.
172
- const proc = deps.proc || process;
173
- const onStop = () => { l.announceStop().finally(() => proc.exit(0)); };
174
- const sigs = deps.noSignalHandlers ? [] : ['SIGTERM', 'SIGINT', 'SIGHUP'];
175
- for (const s of sigs) proc.once(s, onStop);
176
- try {
177
- return await l.loop();
178
- } finally {
179
- for (const s of sigs) { try { proc.removeListener(s, onStop); } catch { /* gone */ } }
180
- }
181
- }
182
-
183
- export { labelOf, unitNameOf, writeState };
@@ -1,216 +0,0 @@
1
- // Always-on listener: local defaults, files and state (v0.35.3, plan 01 sections 2.1 and 2.3).
2
- //
3
- // These numbers protect the owner's quota on this computer. They are NOT platform risk rules; they are registered
4
- // in the risk list (section 4, "scattered parameters") with this file as their location.
5
- //
6
- // Files (all inside the profile's credentials directory, mode 0600):
7
- // listener.json the start command and limits chosen at install time
8
- // listener-cursor this listener's own place in the event stream
9
- // listener-state.json consecutive failures, runs today, pause reason, last result
10
- // listener.log only ids / times / exit codes / durations (never message content), 1 MB x 3 files
11
- // prompts/ one temporary prompt file per run, deleted when the run ends
12
-
13
- import fs from 'node:fs';
14
- import path from 'node:path';
15
- import { atomicWriteFile } from '../atomic-write.js';
16
- import { resolveCredDir } from '../profile.js';
17
-
18
- export const LISTENER_DEFAULTS = Object.freeze({
19
- maxParallel: 50, // sessions running at the same time (1-50; v0.38.7: 2 -> 50, no per-user limit, users take turns when full)
20
- dailyMax: 120, // starts per local day (v0.37: 100 -> 120, PL-03; the platform sends the same number in `limits`)
21
- timeoutMs: 30 * 60 * 1000, // one run is killed after this long and counts as a failure
22
- agentWakeGapMs: 10 * 60 * 1000, // the same session is woken by another Agent at most once per this long
23
- humanMergeMs: 30 * 1000, // messages from people inside this window are merged into one run
24
- failPauseAfter: 3, // consecutive failed starts before the listener pauses itself
25
- queueMax: 20, // sessions waiting at once; the oldest is dropped beyond this (the platform wakes again)
26
- autoRetryMs: 24 * 3600 * 1000, // a failure pause is tried again by itself after this long
27
- pausedCheckMs: 10 * 60 * 1000, // while paused, ask the platform whether to resume this often
28
- logMaxBytes: 1024 * 1024,
29
- logFiles: 3,
30
- });
31
-
32
- export const MAX_PARALLEL_RANGE = [1, 50];
33
-
34
- function dir(credOpts) { return resolveCredDir(credOpts); }
35
- export const configPath = (credOpts) => path.join(dir(credOpts), 'listener.json');
36
- export const cursorFile = (credOpts) => path.join(dir(credOpts), 'listener-cursor');
37
- export const statePath = (credOpts) => path.join(dir(credOpts), 'listener-state.json');
38
- export const logPath = (credOpts) => path.join(dir(credOpts), 'listener.log');
39
- export const promptsDir = (credOpts) => path.join(dir(credOpts), 'prompts');
40
-
41
- function readJson(file) {
42
- try {
43
- const o = JSON.parse(fs.readFileSync(file, 'utf8'));
44
- return o && typeof o === 'object' ? o : null;
45
- } catch { return null; }
46
- }
47
-
48
- function clampInt(v, lo, hi, fallback) {
49
- const n = parseInt(v, 10);
50
- if (!Number.isFinite(n)) return fallback;
51
- return Math.min(hi, Math.max(lo, n));
52
- }
53
-
54
- /** "30m" / "90s" / "2h" / "1800000" (ms) -> milliseconds; null when it cannot be read. */
55
- export function parseDuration(raw) {
56
- if (raw == null || raw === '') return null;
57
- const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/i.exec(String(raw).trim());
58
- if (!m) return null;
59
- const n = Number(m[1]);
60
- const unit = (m[2] || 'ms').toLowerCase();
61
- const mult = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[unit];
62
- const ms = Math.round(n * mult);
63
- return ms > 0 ? ms : null;
64
- }
65
-
66
- /** Build the config saved by `listen install` / used by `listen --exec` from the command-line flags. */
67
- export function configFromFlags(flags) {
68
- const timeout = parseDuration(flags.timeout);
69
- return {
70
- exec: String(flags.exec || '').trim(),
71
- maxParallel: clampInt(flags.maxParallel, MAX_PARALLEL_RANGE[0], MAX_PARALLEL_RANGE[1], LISTENER_DEFAULTS.maxParallel),
72
- dailyMax: clampInt(flags.dailyMax, 1, 10000, LISTENER_DEFAULTS.dailyMax),
73
- dailyMaxSet: flags.dailyMax != null && flags.dailyMax !== '' && Number.isFinite(parseInt(flags.dailyMax, 10)), // chosen on purpose: may only lower the platform number
74
- timeoutMs: timeout || LISTENER_DEFAULTS.timeoutMs,
75
- cwd: flags.cwd ? String(flags.cwd) : null,
76
- env: (flags.envNames || []).filter((n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n)),
77
- };
78
- }
79
-
80
- /** v0.38.7: installs before this version saved 2 (the old default) or 1 (copied from the docs example); both read as the new 50. */
81
- function migratedMaxParallel(v) {
82
- const n = parseInt(v, 10);
83
- return n === 1 || n === 2 ? LISTENER_DEFAULTS.maxParallel : v;
84
- }
85
-
86
- export function readConfig(credOpts) {
87
- const c = readJson(configPath(credOpts));
88
- if (!c || typeof c.exec !== 'string' || !c.exec.trim()) return null;
89
- return {
90
- ...configFromFlags({ exec: c.exec, maxParallel: migratedMaxParallel(c.maxParallel), dailyMax: c.dailyMaxSet === true ? c.dailyMax : null, cwd: c.cwd, envNames: c.env }),
91
- timeoutMs: Number(c.timeoutMs) > 0 ? Number(c.timeoutMs) : LISTENER_DEFAULTS.timeoutMs,
92
- autostart: c.autostart !== false,
93
- installedAt: c.installedAt || null,
94
- nodePath: c.nodePath || null,
95
- entryPath: c.entryPath || null,
96
- autostartKind: c.autostartKind || null,
97
- autostartEntry: c.autostartEntry && typeof c.autostartEntry === 'object' ? { profile: c.autostartEntry.profile || null, configDir: c.autostartEntry.configDir || null } : null, // v0.12.63: which start-at-login entry belongs to this identity
98
- };
99
- }
100
-
101
- export function writeConfig(cfg, credOpts) {
102
- atomicWriteFile(configPath(credOpts), JSON.stringify(cfg, null, 2), 0o600);
103
- }
104
-
105
- // ---- state -------------------------------------------------------------------------------------------
106
-
107
- export function emptyState() {
108
- return {
109
- fails: 0, // consecutive failed runs
110
- runsDate: null, // local date (YYYY-MM-DD) the counter belongs to
111
- runsToday: 0,
112
- paused: null, // null | { reason: 'fail'|'cap'|'platform', at: ms, detail?: string, until?: ms }
113
- last: null, // { at, ok, code, ms } of the latest run (no content)
114
- seenAt: 0, // last time the running listener touched this file
115
- startedAt: 0,
116
- };
117
- }
118
-
119
- /**
120
- * The daily limit in force (v0.37, PA-06): the number the platform sends in `limits` wins; a number the owner chose
121
- * with --daily-max may only make it smaller. Without a platform number (old platform, nothing heard yet) the saved one.
122
- */
123
- export function effectiveDailyMax(cfg, state) {
124
- const own = Number(cfg && cfg.dailyMax) || LISTENER_DEFAULTS.dailyMax;
125
- const plat = Number(state && state.limits && state.limits.daily_max);
126
- if (!Number.isFinite(plat) || plat <= 0) return own;
127
- return cfg && cfg.dailyMaxSet ? Math.min(own, plat) : plat;
128
- }
129
-
130
- /** Consecutive failed starts before pausing: the platform number when it sent one, else the local default. */
131
- export function effectiveFailPause(cfg, state) {
132
- const plat = Number(state && state.limits && state.limits.fail_pause_after);
133
- const own = Number(cfg && cfg.failPauseAfter) || LISTENER_DEFAULTS.failPauseAfter;
134
- return Number.isFinite(plat) && plat > 0 ? plat : own;
135
- }
136
-
137
- export function readState(credOpts) {
138
- return { ...emptyState(), ...(readJson(statePath(credOpts)) || {}) };
139
- }
140
-
141
- /** The running listener touches its state file every 30-60 s; a stopped one writes 0 on a clean stop. */
142
- export const LISTENER_SEEN_FRESH_MS = 2 * 60 * 1000;
143
-
144
- /** Is a listener installed here and seen recently? Anything unclear counts as "not running". */
145
- export function listenerIsRunning(credOpts, nowMs = Date.now()) {
146
- try {
147
- const cfg = readConfig(credOpts);
148
- const st = readState(credOpts);
149
- return !!cfg && st.seenAt > 0 && nowMs - st.seenAt < LISTENER_SEEN_FRESH_MS;
150
- } catch { return false; }
151
- }
152
-
153
- export function writeState(st, credOpts) {
154
- try { atomicWriteFile(statePath(credOpts), JSON.stringify(st), 0o600); } catch { /* best effort */ }
155
- }
156
-
157
- /** Local calendar date as YYYY-MM-DD. */
158
- export function localDate(ms) {
159
- const d = new Date(ms);
160
- const p = (n) => String(n).padStart(2, '0');
161
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
162
- }
163
-
164
- /** Next local midnight after `ms`. */
165
- export function nextLocalMidnight(ms) {
166
- const d = new Date(ms);
167
- d.setHours(24, 0, 0, 0);
168
- return d.getTime();
169
- }
170
-
171
- /** The "runs today" count, reset when the local date changed. */
172
- export function runsToday(st, nowMs) {
173
- return st.runsDate === localDate(nowMs) ? st.runsToday : 0;
174
- }
175
-
176
- export function countRun(st, nowMs) {
177
- const today = localDate(nowMs);
178
- if (st.runsDate !== today) { st.runsDate = today; st.runsToday = 0; }
179
- st.runsToday += 1;
180
- }
181
-
182
- // ---- cursor ------------------------------------------------------------------------------------------
183
-
184
- /** This listener's own cursor; the first time it starts from the shared poll cursor (history is not replayed). */
185
- export function readListenerCursor(credOpts, readSharedCursor) {
186
- try {
187
- const n = parseInt(fs.readFileSync(cursorFile(credOpts), 'utf8').trim(), 10);
188
- if (Number.isFinite(n)) return n;
189
- } catch { /* first run */ }
190
- const start = Number(readSharedCursor(credOpts)) || 0;
191
- writeListenerCursor(start, credOpts);
192
- return start;
193
- }
194
-
195
- export function writeListenerCursor(n, credOpts) {
196
- atomicWriteFile(cursorFile(credOpts), String(n), 0o600);
197
- }
198
-
199
- // ---- log ---------------------------------------------------------------------------------------------
200
-
201
- /** One line per event; rotates at 1 MB, keeps 3 files (listener.log, .1, .2). Never writes message content. */
202
- export function appendLog(credOpts, line, nowMs = Date.now()) {
203
- const file = logPath(credOpts);
204
- try {
205
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
206
- let size = 0;
207
- try { size = fs.statSync(file).size; } catch { /* new file */ }
208
- if (size >= LISTENER_DEFAULTS.logMaxBytes) {
209
- for (let i = LISTENER_DEFAULTS.logFiles - 1; i >= 1; i--) {
210
- const from = i === 1 ? file : `${file}.${i - 1}`;
211
- try { fs.renameSync(from, `${file}.${i === 1 ? 1 : i}`); } catch { /* missing */ }
212
- }
213
- }
214
- fs.appendFileSync(file, `${new Date(nowMs).toISOString()} ${line}\n`, { mode: 0o600 });
215
- } catch { /* the log is a convenience */ }
216
- }
@@ -1,60 +0,0 @@
1
- // Always-on listener: waking the Agent for a hire event that waits for its answer (v0.38.41).
2
- //
3
- // Before this, the listener woke the Agent only for a workbench message (`wb.wake`). A hire event such as "you were
4
- // picked, sign" or "the employer paid a top-up, accept or refuse" reached only whoever ran `anytowork poll`, so an Agent
5
- // that is connected through the listener never heard of it. These events now start the Agent once, in a session of its
6
- // own (the fixed key `hire-events`: there is no workbench session for them), with a prompt that names what waits and
7
- // the commands to answer it. Informational hire events (start, wrap-up, stop for the day, left) do not wake the Agent. v0.38.57: `shop.opened` (the owner's shop opened) wakes it once so it can tell the owner.
8
-
9
- import { hireEventLines } from '../format.js';
10
- import { pickLang } from '../model-pledge.js';
11
-
12
- /** The hire events that wait for an answer from the Agent and may end in a refund or a lost hire when nobody answers. */
13
- export const WAKE_HIRE_EVENTS = new Set(['hire.to_sign', 'hire.topup', 'hire.reschedule', 'shop.opened']);
14
-
15
- /** The session key every such run uses (placeholders {sid} and {session_key} of the start command). */
16
- export const HIRE_WAKE_KEY = 'hire-events';
17
-
18
- /** Events of one poll answer that should wake the Agent for a hire (an id is needed to tell a repeat from a new one). */
19
- export function hireWakeEvents(events) {
20
- return (events || []).filter((e) => e && WAKE_HIRE_EVENTS.has(e.event_type) && e.id != null);
21
- }
22
-
23
- /** True when the event itself says its time to answer has already gone by (an old event met after a restart). */
24
- export function hireEventExpired(e, nowMs) {
25
- const dl = e && e.payload && e.payload.deadline_at ? Date.parse(e.payload.deadline_at) : NaN;
26
- return Number.isFinite(dl) && dl < nowMs;
27
- }
28
-
29
- const EN_LINE = {
30
- 'shop.opened': () => '- Your owner\'s shop is open: orders and job seeking can be turned on now, tell your owner',
31
- 'hire.to_sign': (p) => `- You were picked for a hire${p.title ? ` "${p.title}"` : ''}${p.deadline_at ? `, sign before ${p.deadline_at}` : ''}: anytowork hire sign ${p.hire_id || '<hire id>'} (or hire decline)`,
32
- 'hire.topup': (p) => `- ${p.reminder ? 'Reminder: ' : ''}the employer paid a top-up for today${p.deadline_at ? `, answer before ${p.deadline_at}` : ''}; no answer in time = a full refund: anytowork hire topup ${p.hire_id || '<hire id>'} --accept | --reject`,
33
- 'hire.reschedule': (p) => `- The employer asks to move the start date to ${p.new_start_date || 'a new date'}: anytowork hire decide ${p.hire_id || '<hire id>'} --request ${p.request_id || '<request id>'} --accept | --reject`,
34
- };
35
-
36
- /** The words handed to the Agent on standard input. */
37
- export function hireWakePrompt(events, env = process.env) {
38
- const lang = pickLang(env);
39
- const list = hireWakeEvents(events);
40
- if (lang === 'en') {
41
- const lines = list.map((e) => EN_LINE[e.event_type]((e.payload) || {}));
42
- return [
43
- '[AnytoWork] There are hire events waiting for you (this is not a chat message).',
44
- ...lines,
45
- 'Run `anytowork poll` to see everything that waits and `anytowork hire mine` for your hires (a top-up shows there as well), then answer; stop when done.',
46
- ].join('\n');
47
- }
48
- const lines = [];
49
- for (const e of list) {
50
- const p = (e && e.payload) || {};
51
- const own = hireEventLines(e).map((x) => `- ${x.trim()}`);
52
- lines.push(...(own.length ? own : [`- ${e.event_type}`]));
53
- if (p.reminder) lines.push(' (这是加量的到期提醒,快到回复截止时间了)');
54
- }
55
- return [
56
- '[AnytoWork] 有招聘事件等你处理(不是聊天消息)。',
57
- ...lines,
58
- '先运行 anytowork poll 看全部待办,再运行 anytowork hire mine 看你的聘用(加量也在里面);加量用 anytowork hire topup <招聘编号> --accept 或 --reject。处理完就结束。',
59
- ].join('\n');
60
- }