@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,723 +0,0 @@
1
- // Always-on listener: the running part (plan 01 sections 2.2 to 2.6, with the 11-15 decision that there is no
2
- // consent step and no on/off switch: installing it IS the default way to connect).
3
- //
4
- // What it does:
5
- // - waits on the platform's event stream with its own cursor (long waits, no model runs while it waits);
6
- // - for every workbench wake-up, starts the Agent's own start command, hands the prompt over on standard input
7
- // (never on the command line) and waits for it to finish;
8
- // - keeps the owner's quota safe: one run per session at a time, a few sessions in parallel, a gap for Agent-to-Agent
9
- // calls, merging of quick messages, a daily limit, and a pause after repeated start failures;
10
- // - never stops for network cuts; stops only when the login is gone (exit code 2).
11
-
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
- import { spawn } from 'node:child_process';
15
- import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, postListenerRunEnd, LISTENER_HEADER } from '../api.js';
16
- import { readCursor } from '../poll-state.js';
17
- import { resolveCredDir } from '../profile.js';
18
- import { CLI_VERSION } from '../client-version.js';
19
- import { WakeQueue } from './queue.js';
20
- import { buildPrompt, testPrompt } from './prompt.js';
21
- import { lt } from './text.js';
22
- import { writeNudge } from './nudge.js';
23
- import { classifyRunEnd, makeTail } from './run-error.js'; // v0.38.76: why a run broke off (category only)
24
- import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
25
- import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
26
- import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
27
- import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
28
- import { RunUsageTracker, inrunSettings, programOfCommand } from '../mt/inrun.js';
29
- import { precheckFormats } from '../mt/readers.js';
30
- import { useAlertStore } from '../mt/format-check.js'; // v0.37.7 C2: usage while the Agent runs
31
- import {
32
- LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight, effectiveDailyMax, effectiveFailPause,
33
- readListenerCursor, writeListenerCursor, appendLog, promptsDir,
34
- } from './config.js';
35
-
36
- const RECONNECT_FIRST_MS = 1000;
37
- const RECONNECT_MAX_MS = 60_000;
38
- const BUSY_MIN_MS = 5000;
39
- const BUSY_SPAN_MS = 10_000;
40
- const QUICK_REPLY_MS = 2000;
41
- const QUICK_PAUSE_MS = 3000;
42
- const PAUSED_TICK_MS = 15_000;
43
- const BEAT_EVERY_MS = 60_000; // v0.37.7 C1: the alive beat while the start command runs
44
- const VERSION_CHECK_MS = 10 * 60 * 1000; // v0.37.7 C7: look for a newer installed version this often
45
- const FINAL_UPLOAD_WAIT_MS = 20_000; // the last usage upload at the end of a run may take this long at most
46
- /** Exit code of "I was upgraded, start me again": non-zero on purpose (launchd KeepAlive / systemd Restart=on-failure). */
47
- export const EXIT_UPGRADED = 75;
48
-
49
- const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;
50
- const ORDER_EVENTS = new Set(['collab_message', 'collab_answered', 'collab_question']); // v0.38.7: order talk
51
- 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}$/;
52
-
53
- /** Only ids the platform really sends (a UUID or a plain number) may reach a command line or an environment variable. */
54
- export function isSafeId(x) {
55
- return typeof x === 'string' && SAFE_ID.test(x);
56
- }
57
-
58
- function defaultSleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
59
-
60
- /** The version of the package files on disk now (an upgrade replaces them while this process keeps the old code). */
61
- function installedVersionOnDisk() {
62
- try { return JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version || null; } catch { return null; }
63
- }
64
-
65
- /** `promise`, but never longer than `ms` (the timer is cleared either way). Never rejects. */
66
- async function within(promise, ms) {
67
- let t;
68
- try {
69
- return await Promise.race([promise, new Promise((r) => { t = setTimeout(r, ms); })]);
70
- } catch {
71
- return null;
72
- } finally {
73
- clearTimeout(t);
74
- }
75
- }
76
-
77
- /** Quote a path for the system shell (it comes from our own credentials directory, never from a message). */
78
- export function shellQuote(s, platform = process.platform) {
79
- if (platform === 'win32') return `"${String(s).replace(/"/g, '')}"`;
80
- return `'${String(s).replace(/'/g, `'\\''`)}'`;
81
- }
82
-
83
- /** Fill {sid} {session_key} {group_id} {prompt_file} in the start command. Values are checked ids or our own paths. */
84
- export function expandCommand(command, vals, platform = process.platform) {
85
- const map = {
86
- '{sid}': vals.sid,
87
- '{session_key}': vals.sessionKey,
88
- '{group_id}': vals.groupId || '',
89
- '{prompt_file}': shellQuote(vals.promptFile, platform),
90
- };
91
- let out = String(command);
92
- for (const [k, v] of Object.entries(map)) out = out.split(k).join(String(v));
93
- return out;
94
- }
95
-
96
- const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'LC_MESSAGES', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TEMP', 'TMP',
97
- 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'ComSpec', 'ProgramFiles'];
98
-
99
- /** The environment of a run: a short safe list + the names the owner chose with --env + the wake details. */
100
- export function buildRunEnv({ base, cfg, vals, credDir }) {
101
- const env = {};
102
- for (const k of ENV_KEEP) if (base[k] != null) env[k] = base[k];
103
- for (const k of cfg.env || []) if (base[k] != null) env[k] = base[k];
104
- env.ANYTOWORK_SID = vals.sid;
105
- env.ANYTOWORK_SESSION_KEY = vals.sessionKey;
106
- env.ANYTOWORK_GROUP_ID = vals.groupId || '';
107
- env.ANYTOWORK_WAKE_ID = vals.wakeId || '';
108
- env.ANYTOWORK_WAKE_REASON = vals.reason || '';
109
- if (vals.hireId) env.ANYTOWORK_HIRE_ID = vals.hireId;
110
- env.ANYTOWORK_PROMPT_FILE = vals.promptFile;
111
- // Same identity for every `anytowork chat ...` the Agent runs inside this run (several Agents on one computer).
112
- env.ANYTOWORK_CONFIG_DIR = credDir;
113
- return env;
114
- }
115
-
116
- /** Start the command through the system shell; resolves with {code, timedOut, error?, signal?, tail}. Never rejects. v0.38.76: tail = last few KB of its output, memory only. */
117
- export function defaultExec({ command, input, env, cwd, timeoutMs }) {
118
- return new Promise((resolve) => {
119
- let done = false;
120
- let timedOut = false;
121
- let timer = null;
122
- const finish = (r) => { if (done) return; done = true; if (timer) clearTimeout(timer); resolve(r); };
123
- const tail = makeTail();
124
- let child;
125
- try {
126
- child = spawn(command, {
127
- shell: true, env, cwd: cwd || undefined, stdio: ['pipe', 'pipe', 'pipe'],
128
- detached: process.platform !== 'win32', windowsHide: true,
129
- });
130
- } catch { return finish({ code: null, timedOut: false, error: 'spawn' }); }
131
- child.on('error', () => finish({ code: null, timedOut: false, error: 'spawn' }));
132
- child.on('close', (code, signal) => finish({ code, timedOut, signal: signal || null, tail: tail.text() }));
133
- for (const st of [child.stdout, child.stderr]) {
134
- if (!st) continue;
135
- st.on('data', (d) => tail.push(d));
136
- st.on('error', () => {});
137
- }
138
- child.stdin.on('error', () => { /* the command may not read its input */ });
139
- try { child.stdin.end(input); } catch { /* same */ }
140
- timer = setTimeout(() => {
141
- timedOut = true;
142
- try {
143
- if (process.platform === 'win32') spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
144
- else process.kill(-child.pid, 'SIGKILL');
145
- } catch { try { child.kill('SIGKILL'); } catch { /* already gone */ } }
146
- }, timeoutMs);
147
- });
148
- }
149
-
150
- function execName(command) {
151
- const first = String(command).trim().split(/\s+/)[0] || '';
152
- return path.basename(first).slice(0, 40);
153
- }
154
-
155
- export class Listener {
156
- /**
157
- * @param {object} p { cfg, baseUrl, credOpts, fetchImpl, log, err, deps, classify, flags }
158
- * deps: sleep, nowMs, random, execCommand, listenShouldStop, env — for tests
159
- */
160
- constructor(p) {
161
- this.cfg = { ...LISTENER_DEFAULTS, ...p.cfg }; // saved settings + the built-in safety numbers
162
- this.baseUrl = p.baseUrl;
163
- this.credOpts = p.credOpts;
164
- this.fetchImpl = p.fetchImpl;
165
- this.err = p.err || (() => {});
166
- this.classify = p.classify;
167
- const d = p.deps || {};
168
- this.sleep = d.sleep || defaultSleep;
169
- this.nowMs = d.nowMs || Date.now;
170
- this.random = d.random || Math.random;
171
- this.execCommand = d.execCommand || defaultExec;
172
- this.shouldStop = d.listenShouldStop || (() => false);
173
- this.autoCollect = d.autoCollect || autoCollect;
174
- this.env = d.env || process.env;
175
- this.runEndOff = false; // v0.38.76: the platform has no run-end route (older version): stop trying
176
- this.beatOff = false; // v0.37.7 C1: the platform has no beat route (older version): stop trying
177
- this.installedVersion = d.installedVersion || installedVersionOnDisk;
178
- this.versionCheckMs = Number(d.versionCheckMs || p.cfg && p.cfg.versionCheckMs) || VERSION_CHECK_MS;
179
- this.lastVersionCheck = 0;
180
- this.usage = d.usageTracker || new RunUsageTracker({
181
- baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl, env: d.env || process.env, home: d.home, sqlite: d.sqlite,
182
- nowMs: d.nowMs || Date.now, log: (m) => this.logLine(m),
183
- });
184
- this.queue = new WakeQueue({ config: { ...LISTENER_DEFAULTS, ...this.cfg }, nowMs: this.nowMs });
185
- this.state = readState(this.credOpts);
186
- this.active = new Set();
187
- this.runningTasks = new Map(); // sid -> task id of the run in progress (v0.38.7: order nudges must match it)
188
- this.timer = null;
189
- this.lastPlatformCheck = 0;
190
- this.credDir = resolveCredDir(this.credOpts);
191
- this.home = d.home;
192
- this.sqliteDep = d.sqlite;
193
- try { useAlertStore(path.join(this.credDir, 'format-alerts.json')); } catch { /* none */ } // alerts survive a restart
194
- }
195
-
196
- /** Who this listener is when it is not the computer's default identity (named in the prompt, see buildPrompt). */
197
- identity() {
198
- const profile = this.credOpts && this.credOpts.profile ? this.credOpts.profile : null;
199
- const named = String(this.env.ANYTOWORK_CONFIG_DIR || this.env.LINGER_CONFIG_DIR || '').trim();
200
- if (profile) return named ? { profile, dir: this.credDir } : { profile };
201
- return named ? { dir: this.credDir } : null;
202
- }
203
-
204
- /** v0.36: the job a wake belongs to (hire / task session) and its work folder on this computer, if any. */
205
- jobOf(payload) {
206
- try {
207
- const p = payload || {};
208
- const scope = p.hire_id ? 'hire' : (p.task_id ? 'task' : null);
209
- if (!scope) return null;
210
- const id = String(scope === 'hire' ? p.hire_id : p.task_id);
211
- if (!isSafeId(id)) return null;
212
- const w = workdirsForScope(this.credOpts, scope, id)[0];
213
- return { scope, id, path: w ? w.path : null };
214
- } catch {
215
- return null;
216
- }
217
- }
218
-
219
- // ---- state helpers ---------------------------------------------------------------------------------
220
- save() { writeState(this.state, this.credOpts); }
221
- logLine(line) { appendLog(this.credOpts, line, this.nowMs()); }
222
- isPaused() { return !!this.state.paused; }
223
-
224
- async report(body) {
225
- try {
226
- await reportListener(this.baseUrl, this.credOpts, {
227
- os: process.platform, exec_name: execName(this.cfg.exec), cli_version: CLI_VERSION, ...body,
228
- }, { fetchImpl: this.fetchImpl });
229
- } catch { /* an older platform has no report route; never stop for it */ }
230
- }
231
-
232
- /**
233
- * Round 4 (B5): tell the platform at once that this listener is going away, and forget the local "seen" time so
234
- * `listen status` stops saying it is running. Quiet, at most a few seconds, once.
235
- */
236
- async announceStop(waitMs = 3000) {
237
- if (this.stoppedAnnounced) return;
238
- this.stoppedAnnounced = true;
239
- this.state.seenAt = 0;
240
- try { this.save(); } catch { /* the state file is only a hint */ }
241
- this.logLine('stopped');
242
- await within(this.report({ state: 'stopped', runs_today: runsToday(this.state, this.nowMs()) }), waitMs);
243
- }
244
-
245
- /** v0.37.7 C1: every minute while the start command runs, say so to the platform (no model, nothing spent). */
246
- startBeat(sid) {
247
- const every = this.cfg.beatEveryMs != null ? Number(this.cfg.beatEveryMs) : BEAT_EVERY_MS;
248
- if (!(every > 0) || this.beatOff) return null;
249
- const startedAt = this.nowMs();
250
- const t = setInterval(async () => {
251
- if (this.beatOff) return;
252
- try {
253
- // v0.38.76: this listener started the program itself and it has not ended: say so, and for how long
254
- const ageS = Math.max(0, Math.round((this.nowMs() - startedAt) / 1000));
255
- await postListenerBeat(this.baseUrl, this.credOpts, sid, { fetchImpl: this.fetchImpl, childAlive: true, ageS });
256
- } catch (e) {
257
- // 404: an older platform without the route. 403: the platform did not take it for a listener call. Both: stop for good.
258
- if (e && (e.status === 404 || e.status === 403)) { this.beatOff = true; this.logLine(`beat off status=${e.status}`); }
259
- }
260
- }, every);
261
- if (t.unref) t.unref();
262
- return t;
263
- }
264
-
265
- /**
266
- * v0.38.76 (Echo 470 step 2): the program of this session ended. Tell the platform (no more "working") and, when it broke
267
- * off or left an error behind, which CATEGORY it was (quota / rate_limit / timeout / auth / network / other) with a short
268
- * code. No line of the program output is sent. An older platform without the route is asked once, then left alone.
269
- * Never throws.
270
- */
271
- async reportRunEnd(sid, res) {
272
- if (this.runEndOff) return;
273
- try {
274
- const r = classifyRunEnd(res);
275
- const body = { exit_code: res && res.code != null ? Number(res.code) : null, timed_out: !!(res && res.timedOut), category: r.category, code: r.code };
276
- if (r.broke) this.logLine(`run_end sid=${String(sid).slice(0, 8)} category=${r.category} code=${r.code}`);
277
- let t;
278
- try {
279
- await Promise.race([
280
- postListenerRunEnd(this.baseUrl, this.credOpts, sid, body, { fetchImpl: this.fetchImpl }),
281
- new Promise((r) => { t = setTimeout(r, 8000); }),
282
- ]);
283
- } finally { clearTimeout(t); }
284
- } catch (e) {
285
- if (e && (e.status === 404 || e.status === 403)) { this.runEndOff = true; this.logLine(`run_end off status=${e.status}`); }
286
- }
287
- }
288
-
289
- /** v0.37.7 C2: note a run that belongs to a hire / task; its usage is read from the local logs while it runs. */
290
- beginUsage(job, command, jobInfo) {
291
- try {
292
- const set = inrunSettings(this.cfg, this.state, this.env);
293
- if (!set.enabled) return null;
294
- const p = job.payload || {};
295
- const taskId = isSafeId(String(p.task_id || '')) ? String(p.task_id) : '';
296
- if (!job.hireId && !taskId) return null;
297
- return this.usage.begin({ sid: job.sid, wakeId: job.wakeId, command, startMs: this.nowMs(), wakeIds: job.wakeIds });
298
- } catch {
299
- return null;
300
- }
301
- }
302
-
303
- startUsageTimer(urun) {
304
- if (!urun) return null;
305
- const ms = inrunSettings(this.cfg, this.state, this.env).intervalMs;
306
- if (!ms) return null;
307
- const t = setInterval(() => { this.usage.upload(urun); }, ms);
308
- if (t.unref) t.unref();
309
- return t;
310
- }
311
-
312
- /** v0.37.7 C7: an upgrade replaced the files on disk; only a start-at-login listener ends itself (something starts it again). */
313
- upgradeDue() {
314
- const kind = this.cfg.autostartKind;
315
- if (kind !== 'launchd' && kind !== 'systemd') return false;
316
- const now = this.nowMs();
317
- if (this.active.size || now - this.lastVersionCheck < this.versionCheckMs) return false;
318
- this.lastVersionCheck = now;
319
- let v = null;
320
- try { v = this.installedVersion(); } catch { /* unreadable: stay */ }
321
- return !!v && v !== CLI_VERSION;
322
- }
323
-
324
- pause(reason, detail) {
325
- const now = this.nowMs();
326
- this.state.paused = { reason, at: now, detail: detail || null };
327
- this.queue.clearWaiting();
328
- this.save();
329
- this.logLine(`paused reason=${reason}${detail ? ` detail=${detail}` : ''}`);
330
- if (reason === 'fail' || reason === 'cap') {
331
- this.report({
332
- state: 'paused', reason, fails: this.state.fails, last_error: detail || undefined,
333
- runs_today: runsToday(this.state, now),
334
- });
335
- }
336
- }
337
-
338
- resume(how) {
339
- this.state.paused = null;
340
- this.state.fails = 0;
341
- this.save();
342
- this.logLine(`resumed by=${how}`);
343
- this.report({ state: 'running', runs_today: runsToday(this.state, this.nowMs()) });
344
- }
345
-
346
- // ---- waking ----------------------------------------------------------------------------------------
347
- /** Turn the events of one poll answer into queue entries; wb.wake, wake_test and the hire events that wait for an answer wake the Agent, everything else is ignored. */
348
- handleEvents(events) {
349
- // v0.36: a picked / signed event may carry the work folder of the job: set it up on this computer
350
- for (const e of events || []) { const wp = workdirFromEvent(this.credOpts, e); if (wp) this.logLine(`workdir ${wp}`); }
351
- // v0.37 PA-12: a wake-up test has no session. Recognise it before any session id is looked at; it never enters a
352
- // session's queue or context, and it is not counted against the daily limit.
353
- noteWakeTests(events, this.credOpts, this.nowMs());
354
- for (const e of events || []) {
355
- if (e && e.event_type === 'wake_test') this.handleWakeTest(e);
356
- }
357
- this.handleHireEvents(events);
358
- for (const e of events || []) {
359
- if (!e || e.event_type !== 'wb.wake') continue;
360
- const p = e.payload || {};
361
- const sid = p.session && p.session.id;
362
- if (!UUID.test(String(sid || ''))) { this.logLine(`ignored id=${e.id} why=bad_session`); continue; }
363
- if (this.isPaused()) continue;
364
- const now = this.nowMs();
365
- if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
366
- const wakeId = String(p.wake_id != null ? p.wake_id : (e.id != null ? e.id : ''));
367
- const fromAgent = (p.from && p.from.type === 'agent') || p.reason === 'agent_mention';
368
- const msg = Number(p.last_msg_id != null ? p.last_msg_id : (p.msg_id != null ? p.msg_id : p.first_msg_id));
369
- const r = this.queue.add({
370
- sid,
371
- groupId: isSafeId(String(p.group && p.group.id || '')) ? String(p.group.id) : '',
372
- wakeId: isSafeId(wakeId) ? wakeId : '',
373
- reason: /^[a-z_]{1,32}$/.test(String(p.reason || '')) ? p.reason : '',
374
- hireId: isSafeId(String(p.hire_id || '')) ? String(p.hire_id) : '',
375
- userKey: isSafeId(String(p.owner_key || (p.group && p.group.id) || '')) ? String(p.owner_key || p.group.id) : sid,
376
- human: !fromAgent,
377
- rewake: p.rewake === true,
378
- msgId: Number.isFinite(msg) ? msg : null,
379
- wakeIds: isSafeId(wakeId) ? [wakeId] : [],
380
- payload: p,
381
- });
382
- this.logLine(`wake id=${wakeId} sid=${String(sid).slice(0, 8)} ${r.result}${r.dropped ? ' dropped_oldest' : ''}`);
383
- // v0.38.7: the Agent is in the middle of this session: leave a note for its next command (the queue still keeps
384
- // one more run for after this one, and skips it if the Agent has read the conversation by then).
385
- if (r.result !== 'throttled' && this.queue.running.has(sid)) writeNudge(this.credOpts, sid, { kind: 'session' }, now);
386
- }
387
- // v0.38.7: an order message (supplement / question / progress question) while some run is going
388
- for (const e of events || []) {
389
- if (!e || !ORDER_EVENTS.has(e.event_type) || this.isPaused() || this.queue.running.size === 0) continue;
390
- const tid = String((e.payload && e.payload.task_id) || '');
391
- // only when a run in progress was woken for this very order (its wake-up carried the task id)
392
- if (isSafeId(tid) && [...this.runningTasks.values()].includes(tid)) writeNudge(this.credOpts, `task-${tid}`, { kind: 'order' }, this.nowMs());
393
- }
394
- this.pump();
395
- }
396
-
397
- /**
398
- * v0.38.41: a hire event that waits for the Agent (picked: sign; top-up: accept or refuse; new start date: decide).
399
- * One run for all such events of one poll answer, in the session `hire-events` (no workbench session needed). An event
400
- * id that was already handled is not started twice, an event whose own deadline has passed is skipped, a run already
401
- * going holds the next one back until it ends. Like a wake-up it stops while paused and counts against the daily limit.
402
- */
403
- handleHireEvents(events) {
404
- const fresh = hireWakeEvents(events);
405
- if (!fresh.length) return;
406
- if (!this.seenHire) this.seenHire = new Set();
407
- const now = this.nowMs();
408
- for (const e of fresh) {
409
- const key = String(e.id);
410
- if (this.seenHire.has(key)) continue;
411
- this.seenHire.add(key);
412
- if (this.seenHire.size > 200) this.seenHire.delete(this.seenHire.values().next().value);
413
- if (hireEventExpired(e, now)) { this.logLine(`hire event id=${key} expired`); continue; }
414
- if (this.isPaused()) { this.logLine(`hire event id=${key} paused`); continue; }
415
- (this.hireWaiting || (this.hireWaiting = [])).push(e);
416
- }
417
- this.pumpHire();
418
- }
419
-
420
- pumpHire() {
421
- if (this.hireRunning || !this.hireWaiting || !this.hireWaiting.length || this.isPaused()) return;
422
- const now = this.nowMs();
423
- if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.hireWaiting = []; this.pause('cap'); return; }
424
- const batch = this.hireWaiting.splice(0);
425
- countRun(this.state, now);
426
- this.save();
427
- this.hireRunning = true;
428
- const pr = this.runHireWake(batch).catch(() => {}).finally(() => { this.hireRunning = false; this.active.delete(pr); this.pumpHire(); });
429
- this.active.add(pr);
430
- }
431
-
432
- async runHireWake(batch) {
433
- const now0 = this.nowMs();
434
- const key = HIRE_WAKE_KEY;
435
- const firstId = String(batch[0].id);
436
- const promptFile = path.join(promptsDir(this.credOpts), `hire-${firstId}-${now0}.txt`);
437
- let wrote = false;
438
- const prompt = hireWakePrompt(batch, this.env);
439
- try {
440
- fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
441
- fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
442
- wrote = true;
443
- } catch { /* the prompt still goes on standard input */ }
444
- try {
445
- const hid = batch.map((e) => e.payload && e.payload.hire_id).find((h) => isSafeId(String(h || ''))) || '';
446
- const vals = { sid: key, sessionKey: key, groupId: '', wakeId: firstId, reason: 'hire_event', hireId: hid ? String(hid) : '', promptFile };
447
- const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
448
- const res = await this.execCommand({ command: expandCommand(this.cfg.exec, vals), input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
449
- const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
450
- this.logLine(`hire wake ids=${batch.map((e) => e.id).join(',')} ${ok ? 'ok' : 'fail'} ms=${this.nowMs() - now0}`);
451
- } finally {
452
- if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
453
- }
454
- }
455
-
456
- /**
457
- * v0.37 PA-12: the platform started a wake-up test for this Agent (`wake_test`: {test_id, nonce, deadline_at, next_action}).
458
- * Start the Agent once with a prompt that only asks it to answer the test. The isolation key is the fixed word
459
- * `wake-test`: no session id, no session queue, no session context, not counted in the daily limit, and a test that is
460
- * already running (or was handled) is not started twice.
461
- */
462
- handleWakeTest(e) {
463
- const p = (e && e.payload) || {};
464
- const testId = String(p.test_id || '');
465
- const nonce = testCode(p);
466
- if (!isSafeId(testId) || !/^[A-Za-z0-9]{4,32}$/.test(nonce)) { this.logLine(`ignored id=${e.id} why=bad_wake_test`); return; }
467
- if (!this.seenTests) this.seenTests = new Set();
468
- if (this.seenTests.has(testId)) return;
469
- this.seenTests.add(testId);
470
- if (this.seenTests.size > 50) this.seenTests.delete(this.seenTests.values().next().value);
471
- const dl = p.deadline_at ? Date.parse(p.deadline_at) : NaN;
472
- if (Number.isFinite(dl) && dl < this.nowMs()) { this.logLine(`wake_test id=${testId.slice(0, 8)} expired`); return; }
473
- const pr = this.runWakeTest({ testId, nonce, payload: p }).catch(() => {}).finally(() => this.active.delete(pr));
474
- this.active.add(pr);
475
- }
476
-
477
- async runWakeTest({ testId, nonce, payload }) {
478
- const now0 = this.nowMs();
479
- const key = 'wake-test';
480
- const promptFile = path.join(promptsDir(this.credOpts), `wake-test-${testId.slice(0, 8)}-${now0}.txt`);
481
- let wrote = false;
482
- const prompt = wakeTestPrompt({ ...payload, nonce }, this.env);
483
- try {
484
- fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
485
- fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
486
- wrote = true;
487
- } catch { /* the prompt still goes on standard input */ }
488
- try {
489
- const vals = { sid: key, sessionKey: key, groupId: '', wakeId: testId, reason: 'wake_test', hireId: '', promptFile };
490
- const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
491
- env.ANYTOWORK_WAKE_TEST_ID = testId;
492
- const res = await this.execCommand({ command: expandCommand(this.cfg.exec, vals), input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
493
- const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
494
- this.logLine(`wake_test id=${testId.slice(0, 8)} ${ok ? 'ok' : 'fail'} ms=${this.nowMs() - now0}`);
495
- } finally {
496
- if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
497
- }
498
- }
499
-
500
- /** Start whatever may start now, and arm a timer for what must wait. */
501
- pump() {
502
- if (this.isPaused()) return;
503
- for (;;) {
504
- const now = this.nowMs();
505
- if (this.queue.size && runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
506
- const job = this.queue.take();
507
- if (!job) break;
508
- countRun(this.state, now);
509
- this.save();
510
- if (job.payload && job.payload.task_id) this.runningTasks.set(job.sid, String(job.payload.task_id));
511
- const pr = this.runJob(job).catch(() => {}).finally(() => this.active.delete(pr));
512
- this.active.add(pr);
513
- }
514
- if (this.timer) { clearTimeout(this.timer); this.timer = null; }
515
- const wait = this.queue.nextDelayMs();
516
- if (wait != null && wait > 0) {
517
- this.timer = setTimeout(() => { this.timer = null; this.pump(); }, wait);
518
- if (this.timer.unref) this.timer.unref();
519
- }
520
- }
521
-
522
- async runJob(job) {
523
- const now0 = this.nowMs();
524
- let ranFile = null;
525
- let urun = null;
526
- let timers = [];
527
- try {
528
- // A wake that waited in the queue: if the Agent has read the conversation meanwhile, skip it.
529
- if (job.waited && job.msgId != null) {
530
- try {
531
- const rs = await getWbReadState(this.baseUrl, this.credOpts, job.sid, { fetchImpl: this.fetchImpl });
532
- if (rs && Number(rs.last_read_msg_id) >= job.msgId) {
533
- this.state.runsToday = Math.max(0, this.state.runsToday - 1);
534
- this.logLine(`skip id=${job.wakeId} sid=${job.sid.slice(0, 8)} already_read`);
535
- return;
536
- }
537
- } catch { /* cannot tell: run it */ }
538
- }
539
- const promptFile = path.join(promptsDir(this.credOpts), `${job.wakeId || job.sid.slice(0, 8)}-${now0}.txt`);
540
- const jobInfo = this.jobOf(job.payload);
541
- const vals = {
542
- sid: job.sid, sessionKey: `anytowork-${job.sid.slice(0, 8)}`, groupId: job.groupId, wakeId: job.wakeId,
543
- reason: job.reason, hireId: job.hireId, promptFile,
544
- };
545
- const command = expandCommand(this.cfg.exec, vals);
546
- // v0.38.10: check the log layout of this Agent program before the prompt is made, so a change is known on the first wake
547
- const program = programOfCommand(command);
548
- await precheckFormats({ program, home: this.home, env: this.env, nowMs: this.nowMs(), sqlite: this.sqliteDep, log: (m) => this.logLine(m) });
549
- const prompt = buildPrompt(job.payload, this.env, this.identity(), jobInfo, program);
550
- try {
551
- fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
552
- fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
553
- ranFile = promptFile;
554
- } catch { /* the prompt still goes on standard input */ }
555
- const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
556
- urun = this.beginUsage(job, command, jobInfo);
557
- timers = [this.startBeat(job.sid), this.startUsageTimer(urun)];
558
- let res;
559
- try {
560
- res = await this.execCommand({ command, input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
561
- } finally {
562
- for (const t of timers) if (t) clearInterval(t);
563
- }
564
- if (urun) await within(this.usage.finish(urun), FINAL_UPLOAD_WAIT_MS);
565
- await this.reportRunEnd(job.sid, res);
566
- const ok = res && res.code === 0 && !res.timedOut && !res.error;
567
- const ms = this.nowMs() - now0;
568
- const why = !res ? 'spawn' : (res.timedOut ? 'timeout' : (res.error ? 'spawn' : `exit_${res.code}`));
569
- this.state.last = { at: this.nowMs(), ok, code: res ? res.code : null, ms, why: ok ? null : why };
570
- this.logLine(`run id=${job.wakeId} sid=${job.sid.slice(0, 8)} ${ok ? 'ok' : `fail:${why}`} ms=${ms}`);
571
- if (ok) {
572
- this.state.fails = 0;
573
- } else {
574
- this.state.fails += 1;
575
- if (this.state.fails >= effectiveFailPause(this.cfg, this.state)) this.pause('fail', why);
576
- }
577
- } finally {
578
- if (ranFile) { try { fs.unlinkSync(ranFile); } catch { /* already gone */ } }
579
- this.queue.done(job.sid);
580
- this.runningTasks.delete(job.sid);
581
- this.save();
582
- this.pump();
583
- }
584
- }
585
-
586
- // ---- the loop --------------------------------------------------------------------------------------
587
- /** One step while paused: maybe resume. */
588
- async pausedStep() {
589
- const fileState = readState(this.credOpts);
590
- if (!fileState.paused) { this.state = fileState; this.logLine('resumed by=test'); return; } // `listen test` cleared it
591
- const p = this.state.paused;
592
- const now = this.nowMs();
593
- if (p.reason === 'cap' && now >= nextLocalMidnight(p.at)) return this.resume('midnight');
594
- if (p.reason === 'fail' && now - p.at >= this.cfg.autoRetryMs) return this.resume('auto_retry');
595
- if (p.reason === 'platform' && now - this.lastPlatformCheck >= this.cfg.pausedCheckMs) {
596
- this.lastPlatformCheck = now;
597
- try {
598
- const info = await getListenerInfo(this.baseUrl, this.credOpts, { fetchImpl: this.fetchImpl });
599
- if (!info || info.allowed !== false) return this.resume('platform');
600
- } catch (e) {
601
- if (this.classify && ['upgrade', 'auth'].includes(this.classify(e))) throw e;
602
- }
603
- }
604
- this.state.seenAt = now;
605
- this.save();
606
- await this.sleep(PAUSED_TICK_MS);
607
- }
608
-
609
- /** v0.12.63: the loop is alive (also while the platform is busy or unreachable): `listen status` reads this mark. Saved at most every 30 s. */
610
- beatAlive() {
611
- this.state.seenAt = this.nowMs();
612
- if (this.state.seenAt - (this.lastSeenSave || 0) >= 30000) { this.lastSeenSave = this.state.seenAt; this.save(); }
613
- }
614
-
615
- /** @returns {Promise<number>} exit code: 0 stopped on request, 2 login lost / refused */
616
- async loop() {
617
- this.state.startedAt = this.nowMs();
618
- this.save();
619
- this.report({ state: 'running', runs_today: runsToday(this.state, this.nowMs()) });
620
- let reconnectMs = RECONNECT_FIRST_MS;
621
- let broken = false;
622
- let cursor = readListenerCursor(this.credOpts, readCursor);
623
- this.lastVersionCheck = this.nowMs();
624
- while (!this.shouldStop()) {
625
- // v0.37.7 C7: the package on disk is newer than this running code: say so and end; launchd / systemd start the new one
626
- if (this.upgradeDue()) {
627
- this.logLine(`upgrade running=${CLI_VERSION}`);
628
- await this.announceStop();
629
- return EXIT_UPGRADED;
630
- }
631
- if (this.isPaused()) {
632
- try { await this.pausedStep(); } catch (e) {
633
- if (this.classify && this.classify(e) === 'upgrade') throw e;
634
- if (this.classify && this.classify(e) === 'auth') { this.err(lt('run.auth', {}, this.env)); return 2; }
635
- }
636
- continue;
637
- }
638
- // v0.36: while nothing is running, send new model call records every 10 minutes (no model, nothing spent)
639
- if (!this.active.size) await this.autoCollect({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, env: this.env, nowMs: this.nowMs() });
640
- // 2026-11-27: runs whose last usage upload did not get through (network down, restart) are sent again (at most every 5 minutes)
641
- if (!this.active.size && this.usage && typeof this.usage.backfill === 'function') {
642
- try { await this.usage.backfill(); } catch { /* never blocks the loop */ }
643
- }
644
- const started = this.nowMs();
645
- let data;
646
- try {
647
- data = await getPoll(this.baseUrl, this.credOpts, { cursor, mode: 'listen', fetchImpl: this.fetchImpl, headers: LISTENER_HEADER });
648
- } catch (e) {
649
- const kind = this.classify ? this.classify(e) : 'transient';
650
- if (kind === 'upgrade') throw e;
651
- if (kind === 'auth') { this.err(lt('run.auth', {}, this.env)); return 2; }
652
- if (kind === 'fatal') {
653
- const msg = (e.body && (e.body.message || (e.body.detail && e.body.detail.message))) || e.message || String(e);
654
- this.err(`平台拒绝了监听请求,已停止 / The platform refused the request, stopped: ${msg}`);
655
- return 2;
656
- }
657
- this.beatAlive();
658
- if (kind === 'busy') { await this.sleep(BUSY_MIN_MS + Math.floor(this.random() * BUSY_SPAN_MS)); continue; }
659
- if (!broken) this.err(`和平台的连接断了(${e && e.message ? e.message : '没有回应'}),正在自动重连,不用处理。 / Connection lost, reconnecting by itself.`);
660
- broken = true;
661
- await this.sleep(reconnectMs + Math.floor(this.random() * reconnectMs * 0.2));
662
- reconnectMs = Math.min(reconnectMs * 2, RECONNECT_MAX_MS);
663
- continue;
664
- }
665
- if (broken) this.err('已重新连上平台,继续监听。 / Connected again.');
666
- broken = false;
667
- reconnectMs = RECONNECT_FIRST_MS;
668
- if (data && data.next_cursor != null) { cursor = data.next_cursor; writeListenerCursor(cursor, this.credOpts); }
669
- this.beatAlive();
670
- const lis = data && data.listener;
671
- // v0.37 PA-06: the platform's own numbers (daily limit, failures before a pause) replace the local defaults
672
- if (lis && lis.limits && typeof lis.limits === 'object') {
673
- const was = JSON.stringify(this.state.limits || null);
674
- this.state.limits = {
675
- daily_max: Number(lis.limits.daily_max) || null, fail_pause_after: Number(lis.limits.fail_pause_after) || null,
676
- // v0.37.7: seconds between usage uploads while an Agent runs; 0 = off; absent = the built-in default
677
- ...(lis.limits.inrun_upload_sec != null && Number.isFinite(Number(lis.limits.inrun_upload_sec)) ? { inrun_upload_sec: Number(lis.limits.inrun_upload_sec) } : {}),
678
- };
679
- if (JSON.stringify(this.state.limits) !== was) this.save();
680
- }
681
- if (lis && lis.allowed === false) {
682
- // The platform asks to stop waking for now (for example the wake-ups are not being read). Check back later.
683
- this.lastPlatformCheck = this.nowMs();
684
- this.pause('platform', typeof lis.reason === 'string' ? lis.reason : 'platform');
685
- continue;
686
- }
687
- this.handleEvents((data && data.events) || []);
688
- if (!(data && data.events && data.events.length) && this.nowMs() - started < QUICK_REPLY_MS) await this.sleep(QUICK_PAUSE_MS);
689
- }
690
- await Promise.allSettled([...this.active]);
691
- await this.announceStop();
692
- return 0;
693
- }
694
- }
695
-
696
- /** `listen test`: start the command once with a fixed prompt; does not touch any platform message. */
697
- export async function runStartTest({ cfg, credOpts, deps = {}, env = process.env }) {
698
- const sid = '00000000-0000-4000-8000-000000000000';
699
- const execCommand = deps.execCommand || defaultExec;
700
- const credDir = resolveCredDir(credOpts);
701
- const promptFile = path.join(promptsDir(credOpts), `test-${Date.now()}.txt`);
702
- const prompt = testPrompt(env);
703
- let wrote = false;
704
- try {
705
- fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
706
- fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
707
- wrote = true;
708
- } catch { /* standard input still works */ }
709
- const vals = { sid, sessionKey: 'anytowork-test0000', groupId: '', wakeId: 'test', reason: 'test', hireId: '', promptFile };
710
- const res = await execCommand({
711
- command: expandCommand(cfg.exec, vals), input: prompt,
712
- env: buildRunEnv({ base: env, cfg, vals, credDir }), cwd: cfg.cwd, timeoutMs: cfg.timeoutMs,
713
- });
714
- if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
715
- const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
716
- const why = !res || res.error ? 'spawn' : (res.timedOut ? 'timeout' : `exit_${res.code}`);
717
- const st = readState(credOpts);
718
- st.last = { at: Date.now(), ok, code: res ? res.code : null, ms: 0, why: ok ? null : why };
719
- if (ok && st.paused && st.paused.reason === 'fail') { st.paused = null; st.fails = 0; }
720
- writeState(st, credOpts);
721
- appendLog(credOpts, `test ${ok ? 'ok' : `fail:${why}`}`);
722
- return { ok, why, code: res ? res.code : null };
723
- }