@anytowork/cli 0.12.67 → 0.12.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/package.json +1 -1
- package/src/api.js +15 -1
- package/src/listener/run-error.js +81 -0
- package/src/listener/run.js +41 -5
package/README.md
CHANGED
|
@@ -342,6 +342,7 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
|
|
|
342
342
|
- 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。用户级系统服务与开机定时项都装不上时,方案 A 不可用,改用方案 B。
|
|
343
343
|
- 日志在凭证目录的 `listener.log`(1 MB 轮转 3 份,只记编号、时间、退出码和耗时,不记消息内容)。
|
|
344
344
|
- 常驻监听有自己的游标,和 `anytowork poll` 互不影响;订单事件仍走你原来的 `poll` / `listen`。
|
|
345
|
+
- 0.12.68 起:你的命令运行期间,监听每分钟告诉平台它还在跑(同一次运行最长按 60 分钟算),工作台一直显示「在干活」;命令异常结束(退出码不是 0、超时,或只留下一条错误)时,监听只把错误的类别(额度不足、限流、超时、登录失效、网络、其他)和一个短代码告诉平台,工作台会用一句话提示主人。命令的输出内容不会上传,只在内存里取最后几 KB 判断类别,用完即弃。
|
|
345
346
|
|
|
346
347
|
**方案 B:每 1 分钟 poll**:定时任务每 1 分钟运行一次 `anytowork poll`:没有新事件时不输出、退出码 0,不启动模型;有新事件时打印并退出码 1,这时才把输出交给模型;出错退出码 2。这个定时任务同时是接单、求职的盯单,用方案 A 的也要保留;监听健康时新消息交给监听,不会叫醒两次。
|
|
347
348
|
|
package/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -1221,7 +1221,21 @@ export async function reportListener(baseUrl, credOpts = {}, body = {}, opts = {
|
|
|
1221
1221
|
* command for this session is still running (only with the listener header; an older platform answers 404).
|
|
1222
1222
|
*/
|
|
1223
1223
|
export async function postListenerBeat(baseUrl, credOpts = {}, sid, opts = {}) {
|
|
1224
|
-
|
|
1224
|
+
// v0.38.76: childAlive + ageS say the listener itself started the Agent program and it is still running (an older platform ignores both)
|
|
1225
|
+
const { childAlive, ageS, ...rest } = opts;
|
|
1226
|
+
const body = { source: 'listener', ...(childAlive ? { child_alive: true, age_s: Math.max(0, Math.floor(Number(ageS) || 0)) } : {}) };
|
|
1227
|
+
return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/beat`, credOpts, body, null,
|
|
1228
|
+
{ ...rest, headers: { ...LISTENER_HEADER, ...(rest.headers || {}) } });
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* POST /api/v1/agent/chat/sessions/{sid}/run-end - v0.38.76: the listener says the Agent program of this session ended and, when
|
|
1233
|
+
* it broke off, the error category (quota / rate_limit / timeout / auth / network / other) with a short code. Never any output text.
|
|
1234
|
+
* Only with the listener header; an older platform answers 404.
|
|
1235
|
+
*/
|
|
1236
|
+
export async function postListenerRunEnd(baseUrl, credOpts = {}, sid, body = {}, opts = {}) {
|
|
1237
|
+
const safe = { exit_code: body.exit_code ?? null, timed_out: !!body.timed_out, category: body.category || null, code: body.code || null };
|
|
1238
|
+
return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/run-end`, credOpts, safe, null,
|
|
1225
1239
|
{ ...opts, headers: { ...LISTENER_HEADER, ...(opts.headers || {}) } });
|
|
1226
1240
|
}
|
|
1227
1241
|
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// What went wrong when the Agent program the listener started ended badly (Echo 470 step 2).
|
|
2
|
+
//
|
|
3
|
+
// The listener keeps only the last few KB of the program's output in memory, reads them once with this small table and
|
|
4
|
+
// forgets them. Only a CATEGORY and a short code ever leave this module: never a line of the output, never a key, token
|
|
5
|
+
// or request. To teach it a new situation, add a row to RULES (first match wins, so put the specific ones first).
|
|
6
|
+
|
|
7
|
+
/** The categories the platform understands; anything else it stores as "other". */
|
|
8
|
+
export const RUN_ERROR_CATEGORIES = ['quota', 'rate_limit', 'timeout', 'auth', 'network', 'other'];
|
|
9
|
+
|
|
10
|
+
/** Bytes of output kept per stream while the program runs (the tail only; older output is dropped). */
|
|
11
|
+
export const TAIL_BYTES = 4096;
|
|
12
|
+
|
|
13
|
+
/** "status 402", "HTTP 402", "code: 402", "error 402" or "402 Payment Required" style mentions of one HTTP status. */
|
|
14
|
+
function status(n) {
|
|
15
|
+
return new RegExp(`(?:status(?:\\s*code)?|http|code|error|err)\\D{0,12}\\b${n}\\b|\\b${n}\\b\\s*(?:-|:)?\\s*(?:payment|too many|unauthori|forbidden|insufficient|error|client error)`, 'i');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Ordered rows: [category, short code, patterns]. The short code is a fixed word or the HTTP status, never text from the output.
|
|
20
|
+
* Quota first: a balance message often also mentions "limit" or "401-ish" words.
|
|
21
|
+
*/
|
|
22
|
+
export const RULES = [
|
|
23
|
+
['quota', '402', [
|
|
24
|
+
status(402),
|
|
25
|
+
/insufficient[\s_-]*(?:balance|funds|quota|credits?|account)|(?:balance|quota|credits?)\s*(?:is\s*)?(?:insufficient|exhausted|exceeded|depleted|used up|too low)|out of (?:credits?|quota|balance)|payment required|billing[^\n]{0,30}(?:not active|inactive|failed|required)|exceeded your current quota|余额不足|额度(?:不足|已用完|用完|耗尽)|欠费/i,
|
|
26
|
+
]],
|
|
27
|
+
['rate_limit', '429', [
|
|
28
|
+
status(429),
|
|
29
|
+
/rate[\s_-]*limit|too many requests|requests? per (?:minute|second)|overloaded|限流|请求过于频繁/i,
|
|
30
|
+
]],
|
|
31
|
+
['auth', '401', [
|
|
32
|
+
status(401), status(403),
|
|
33
|
+
/unauthori[sz]ed|invalid[\s_-]*(?:api[\s_-]*)?key|incorrect api key|authentication[\s_-]*(?:failed|error|required)|invalid[\s_-]*token|token (?:expired|has expired)|forbidden|认证失败|密钥(?:无效|错误)/i,
|
|
34
|
+
]],
|
|
35
|
+
['timeout', 'timeout', [
|
|
36
|
+
/timed? ?out|ETIMEDOUT|ESOCKETTIMEDOUT|deadline exceeded|超时/i,
|
|
37
|
+
]],
|
|
38
|
+
['network', 'net', [
|
|
39
|
+
/ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|socket hang up|getaddrinfo|connection (?:refused|reset|error|closed)|network (?:error|is unreachable)|fetch failed|网络(?:错误|异常)/i,
|
|
40
|
+
]],
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Put one ended run down to a category.
|
|
45
|
+
* @param {{code?: number|null, timedOut?: boolean, error?: string, signal?: string|null, tail?: string}} res what the exec helper returned
|
|
46
|
+
* @returns {{broke: boolean, category: string|null, code: string|null}}
|
|
47
|
+
* broke the program did not end in an orderly way (a non-zero exit, killed, timed out, could not start)
|
|
48
|
+
* category the matched category, or null when nothing in the output points at one (a broken run is then "other")
|
|
49
|
+
* code a short token (`402`, `429`, `timeout`, `net`, `exit_1`, `spawn`) or null
|
|
50
|
+
*/
|
|
51
|
+
export function classifyRunEnd(res) {
|
|
52
|
+
const r = res || {};
|
|
53
|
+
const exitCode = r.code == null ? null : Number(r.code);
|
|
54
|
+
const broke = !!r.timedOut || !!r.error || exitCode !== 0;
|
|
55
|
+
const text = String(r.tail || '').slice(-TAIL_BYTES);
|
|
56
|
+
let category = null;
|
|
57
|
+
let code = null;
|
|
58
|
+
if (r.timedOut) { category = 'timeout'; code = 'timeout'; }
|
|
59
|
+
else if (r.error) { category = 'other'; code = 'spawn'; }
|
|
60
|
+
else {
|
|
61
|
+
for (const [cat, short, patterns] of RULES) {
|
|
62
|
+
if (patterns.some((p) => p.test(text))) { category = cat; code = short; break; }
|
|
63
|
+
}
|
|
64
|
+
// the status mentioned decides the short code of the auth row (401 or 403)
|
|
65
|
+
if (category === 'auth' && status(403).test(text) && !status(401).test(text)) code = '403';
|
|
66
|
+
}
|
|
67
|
+
if (broke && !category) {
|
|
68
|
+
category = 'other';
|
|
69
|
+
code = exitCode != null ? `exit_${Math.abs(exitCode) % 1000}` : (r.signal ? 'signal' : 'exit');
|
|
70
|
+
}
|
|
71
|
+
return { broke, category, code };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A bounded tail buffer: keeps the last `max` characters of what is pushed in. */
|
|
75
|
+
export function makeTail(max = TAIL_BYTES) {
|
|
76
|
+
let buf = '';
|
|
77
|
+
return {
|
|
78
|
+
push(chunk) { buf = (buf + String(chunk)).slice(-max); },
|
|
79
|
+
text() { return buf; },
|
|
80
|
+
};
|
|
81
|
+
}
|
package/src/listener/run.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { spawn } from 'node:child_process';
|
|
15
|
-
import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, LISTENER_HEADER } from '../api.js';
|
|
15
|
+
import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, postListenerRunEnd, LISTENER_HEADER } from '../api.js';
|
|
16
16
|
import { readCursor } from '../poll-state.js';
|
|
17
17
|
import { resolveCredDir } from '../profile.js';
|
|
18
18
|
import { CLI_VERSION } from '../client-version.js';
|
|
@@ -20,6 +20,7 @@ import { WakeQueue } from './queue.js';
|
|
|
20
20
|
import { buildPrompt, testPrompt } from './prompt.js';
|
|
21
21
|
import { lt } from './text.js';
|
|
22
22
|
import { writeNudge } from './nudge.js';
|
|
23
|
+
import { classifyRunEnd, makeTail } from './run-error.js'; // v0.38.76: why a run broke off (category only)
|
|
23
24
|
import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
|
|
24
25
|
import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
|
|
25
26
|
import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
|
|
@@ -112,22 +113,28 @@ export function buildRunEnv({ base, cfg, vals, credDir }) {
|
|
|
112
113
|
return env;
|
|
113
114
|
}
|
|
114
115
|
|
|
115
|
-
/** Start the command through the system shell; resolves with {code, timedOut, error
|
|
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. */
|
|
116
117
|
export function defaultExec({ command, input, env, cwd, timeoutMs }) {
|
|
117
118
|
return new Promise((resolve) => {
|
|
118
119
|
let done = false;
|
|
119
120
|
let timedOut = false;
|
|
120
121
|
let timer = null;
|
|
121
122
|
const finish = (r) => { if (done) return; done = true; if (timer) clearTimeout(timer); resolve(r); };
|
|
123
|
+
const tail = makeTail();
|
|
122
124
|
let child;
|
|
123
125
|
try {
|
|
124
126
|
child = spawn(command, {
|
|
125
|
-
shell: true, env, cwd: cwd || undefined, stdio: ['pipe', '
|
|
127
|
+
shell: true, env, cwd: cwd || undefined, stdio: ['pipe', 'pipe', 'pipe'],
|
|
126
128
|
detached: process.platform !== 'win32', windowsHide: true,
|
|
127
129
|
});
|
|
128
130
|
} catch { return finish({ code: null, timedOut: false, error: 'spawn' }); }
|
|
129
131
|
child.on('error', () => finish({ code: null, timedOut: false, error: 'spawn' }));
|
|
130
|
-
child.on('close', (code) => finish({ code, timedOut }));
|
|
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
|
+
}
|
|
131
138
|
child.stdin.on('error', () => { /* the command may not read its input */ });
|
|
132
139
|
try { child.stdin.end(input); } catch { /* same */ }
|
|
133
140
|
timer = setTimeout(() => {
|
|
@@ -165,6 +172,7 @@ export class Listener {
|
|
|
165
172
|
this.shouldStop = d.listenShouldStop || (() => false);
|
|
166
173
|
this.autoCollect = d.autoCollect || autoCollect;
|
|
167
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
|
|
168
176
|
this.beatOff = false; // v0.37.7 C1: the platform has no beat route (older version): stop trying
|
|
169
177
|
this.installedVersion = d.installedVersion || installedVersionOnDisk;
|
|
170
178
|
this.versionCheckMs = Number(d.versionCheckMs || p.cfg && p.cfg.versionCheckMs) || VERSION_CHECK_MS;
|
|
@@ -238,10 +246,13 @@ export class Listener {
|
|
|
238
246
|
startBeat(sid) {
|
|
239
247
|
const every = this.cfg.beatEveryMs != null ? Number(this.cfg.beatEveryMs) : BEAT_EVERY_MS;
|
|
240
248
|
if (!(every > 0) || this.beatOff) return null;
|
|
249
|
+
const startedAt = this.nowMs();
|
|
241
250
|
const t = setInterval(async () => {
|
|
242
251
|
if (this.beatOff) return;
|
|
243
252
|
try {
|
|
244
|
-
|
|
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 });
|
|
245
256
|
} catch (e) {
|
|
246
257
|
// 404: an older platform without the route. 403: the platform did not take it for a listener call. Both: stop for good.
|
|
247
258
|
if (e && (e.status === 404 || e.status === 403)) { this.beatOff = true; this.logLine(`beat off status=${e.status}`); }
|
|
@@ -251,6 +262,30 @@ export class Listener {
|
|
|
251
262
|
return t;
|
|
252
263
|
}
|
|
253
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
|
+
|
|
254
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. */
|
|
255
290
|
beginUsage(job, command, jobInfo) {
|
|
256
291
|
try {
|
|
@@ -527,6 +562,7 @@ export class Listener {
|
|
|
527
562
|
for (const t of timers) if (t) clearInterval(t);
|
|
528
563
|
}
|
|
529
564
|
if (urun) await within(this.usage.finish(urun), FINAL_UPLOAD_WAIT_MS);
|
|
565
|
+
await this.reportRunEnd(job.sid, res);
|
|
530
566
|
const ok = res && res.code === 0 && !res.timedOut && !res.error;
|
|
531
567
|
const ms = this.nowMs() - now0;
|
|
532
568
|
const why = !res ? 'spawn' : (res.timedOut ? 'timeout' : (res.error ? 'spawn' : `exit_${res.code}`));
|