e2e-agent-runner 1.10.0 → 1.12.0
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/api.mjs +65 -6
- package/claude.mjs +26 -1
- package/package.json +1 -1
- package/runner.mjs +43 -7
package/api.mjs
CHANGED
|
@@ -30,14 +30,19 @@ function headers() {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
export class ApiError extends Error {
|
|
33
|
-
|
|
33
|
+
/** @param {{code?: string|null, retryAfterS?: number|null}} [extra] */
|
|
34
|
+
constructor(status, detail, path, extra = {}) {
|
|
34
35
|
super(`POST ${path} → ${status}: ${JSON.stringify(detail)}`);
|
|
35
36
|
this.status = status;
|
|
36
37
|
this.detail = detail;
|
|
38
|
+
this.code = extra.code ?? null; // 'd1_quota' 등 — 응답 JSON 의 code 또는 error.code
|
|
39
|
+
this.retryAfterS = extra.retryAfterS ?? null; // Retry-After 헤더(초)
|
|
37
40
|
}
|
|
38
41
|
}
|
|
39
42
|
|
|
40
43
|
/** POST 래퍼 — 네트워크 오류·5xx 만 2회 재시도(4xx 는 즉시 throw). 재시도 전 백오프.
|
|
44
|
+
* code === 'd1_quota'(D1 일일 한도 소진, UTC 자정까지 지속)는 재시도해도 무의미 — 즉시 throw.
|
|
45
|
+
* 비 JSON 응답(HTML 500 등)은 파싱 오류 대신 ApiError(status, 'non-JSON 응답(<status>)') 로 정규화.
|
|
41
46
|
* 30s 타임아웃 — 응답이 느리게 흐르는 서버 장애에서 폴 1회(재시도 포함)가 수 분씩
|
|
42
47
|
* 묶이며 heartbeat·이벤트 flush까지 함께 멈추지 않게 한다. */
|
|
43
48
|
export async function api(path, body = {}, { retries = 2 } = {}) {
|
|
@@ -52,9 +57,27 @@ export async function api(path, body = {}, { retries = 2 } = {}) {
|
|
|
52
57
|
signal: AbortSignal.timeout(30_000),
|
|
53
58
|
});
|
|
54
59
|
const text = await res.text();
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
60
|
+
let data;
|
|
61
|
+
try {
|
|
62
|
+
data = text ? JSON.parse(text) : {};
|
|
63
|
+
} catch {
|
|
64
|
+
data = null;
|
|
65
|
+
}
|
|
66
|
+
if (data === null || typeof data !== 'object') {
|
|
67
|
+
const err = new ApiError(res.status, `non-JSON 응답(${res.status})`, path);
|
|
68
|
+
if (res.status >= 500 && attempt < retries) {
|
|
69
|
+
lastErr = err;
|
|
70
|
+
retryable = true;
|
|
71
|
+
} else {
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
} else if (!res.ok) {
|
|
75
|
+
const ra = Number.parseInt(res.headers.get('retry-after') ?? '', 10);
|
|
76
|
+
const err = new ApiError(res.status, data.detail ?? data.error, path, {
|
|
77
|
+
code: data.code ?? data.error?.code ?? null,
|
|
78
|
+
retryAfterS: Number.isFinite(ra) && ra >= 0 ? ra : (data.retry_after_s ?? data.error?.details?.retry_after_s ?? null),
|
|
79
|
+
});
|
|
80
|
+
if (err.code === 'd1_quota') throw err; // 한도 소진 — 내부 재시도 없이 즉시
|
|
58
81
|
if (res.status >= 500 && attempt < retries) {
|
|
59
82
|
lastErr = err; // 5xx — 백오프 후 재시도
|
|
60
83
|
retryable = true;
|
|
@@ -65,8 +88,8 @@ export async function api(path, body = {}, { retries = 2 } = {}) {
|
|
|
65
88
|
return data;
|
|
66
89
|
}
|
|
67
90
|
} catch (e) {
|
|
68
|
-
if (e instanceof ApiError) throw e;
|
|
69
|
-
lastErr = e; // 네트워크
|
|
91
|
+
if (e instanceof ApiError && !retryable) throw e;
|
|
92
|
+
lastErr = e; // 네트워크 오류·재시도 대상 5xx — 백오프 후 재시도
|
|
70
93
|
retryable = true;
|
|
71
94
|
}
|
|
72
95
|
if (retryable && attempt < retries) await sleep(500 * (attempt + 1));
|
|
@@ -74,4 +97,40 @@ export async function api(path, body = {}, { retries = 2 } = {}) {
|
|
|
74
97
|
throw lastErr;
|
|
75
98
|
}
|
|
76
99
|
|
|
100
|
+
/** 같은 오류 문자열이 연속될 때 로그 폭주를 막는다 — 첫 1회 즉시, 이후 repeatMs 마다 1줄 요약,
|
|
101
|
+
* 성공 시 복구 1줄. now 는 테스트용 가짜 시계 주입점. */
|
|
102
|
+
export class ErrorLogThrottle {
|
|
103
|
+
constructor(logFn, { now = () => Date.now(), repeatMs = 300_000 } = {}) {
|
|
104
|
+
this.logFn = logFn;
|
|
105
|
+
this.now = now;
|
|
106
|
+
this.repeatMs = repeatMs;
|
|
107
|
+
this.key = null;
|
|
108
|
+
this.count = 0;
|
|
109
|
+
this.lastLogAt = 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
fail(key) {
|
|
113
|
+
const t = this.now();
|
|
114
|
+
if (key !== this.key) {
|
|
115
|
+
this.key = key;
|
|
116
|
+
this.count = 1;
|
|
117
|
+
this.lastLogAt = t;
|
|
118
|
+
this.logFn(key);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
this.count++;
|
|
122
|
+
if (t - this.lastLogAt >= this.repeatMs) {
|
|
123
|
+
this.lastLogAt = t;
|
|
124
|
+
this.logFn(`동일 오류 ${this.count}회 반복 중: ${key}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
ok() {
|
|
129
|
+
if (this.key === null) return;
|
|
130
|
+
this.logFn(`서버 연결 복구(오류 ${this.count}회 후)`);
|
|
131
|
+
this.key = null;
|
|
132
|
+
this.count = 0;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
77
136
|
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
package/claude.mjs
CHANGED
|
@@ -16,6 +16,31 @@ export function parsePhaseMarker(text) {
|
|
|
16
16
|
return m.length ? m[m.length - 1][1].toLowerCase() : null;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
// claude CLI 가 시작 시 stderr 로 찍는 정보성 경고 — 실패 원인이 아니므로 error 보고에서 제외한다.
|
|
20
|
+
// (GLM 프록시 머신은 ANTHROPIC_API_KEY/AUTH_TOKEN env 로 인증 → 매 실행 출력.) 서버
|
|
21
|
+
// (src/e2e/agent_prompts.py STDERR_NOISE_PATTERNS)와 같은 의미를 유지. 넓은 패턴 금지.
|
|
22
|
+
export const STDERR_NOISE = [
|
|
23
|
+
/claude\.ai connectors are disabled/i,
|
|
24
|
+
/^\s*$/,
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
export function cleanStderr(text) {
|
|
28
|
+
return String(text ?? '')
|
|
29
|
+
.split(/\r?\n/)
|
|
30
|
+
.filter((line) => !STDERR_NOISE.some((re) => re.test(line)))
|
|
31
|
+
.join('\n')
|
|
32
|
+
.trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 실패 error 문구: 정제된 stderr > 최종 보고(finalText) > 종료 코드. */
|
|
36
|
+
export function composeError({ stderr, finalText, code }) {
|
|
37
|
+
const cleaned = cleanStderr(stderr);
|
|
38
|
+
if (cleaned) return cleaned.slice(-1500);
|
|
39
|
+
const ft = (finalText ?? '').trim();
|
|
40
|
+
if (ft) return ft.length <= 1500 ? ft : `…${ft.slice(-600)}`;
|
|
41
|
+
return `claude 종료 코드 ${code}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
19
44
|
/** 자식 프로세스(claude·deploy_command)에 물려줄 env — 러너 토큰(E2E_RUNNER_TOKEN)은
|
|
20
45
|
* 머신 신원 그 자체(단계 클레임 = 임의 커맨드 실행 권한)라 제외한다. discover/qa/improve
|
|
21
46
|
* 페이즈의 claude 는 브라우저 MCP 로 외부 사이트를 직접 보므로, 주입된 지시가
|
|
@@ -211,7 +236,7 @@ export function runClaude(opts) {
|
|
|
211
236
|
} else {
|
|
212
237
|
finish({
|
|
213
238
|
ok: false, model: resolvedModel, finalText, sessionId, usage,
|
|
214
|
-
error:
|
|
239
|
+
error: composeError({ stderr: stderrTail, finalText, code }),
|
|
215
240
|
});
|
|
216
241
|
}
|
|
217
242
|
});
|
package/package.json
CHANGED
package/runner.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { spawn } from 'node:child_process';
|
|
|
15
15
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, statSync, renameSync, openSync, readSync, closeSync } from 'node:fs';
|
|
16
16
|
import { fileURLToPath } from 'node:url';
|
|
17
17
|
import { dirname, join } from 'node:path';
|
|
18
|
-
import { api, runnerIdFromToken, sleep } from './api.mjs';
|
|
18
|
+
import { api, ErrorLogThrottle, runnerIdFromToken, sleep } from './api.mjs';
|
|
19
19
|
import { childEnv, parsePhaseMarker, probeClaude, runClaude } from './claude.mjs';
|
|
20
20
|
import { collectArtifact, countRouteFiles, porcelain, prepareDiscover } from './discover.mjs';
|
|
21
21
|
import {
|
|
@@ -221,6 +221,28 @@ class EventBuffer {
|
|
|
221
221
|
|
|
222
222
|
// ─── 단계 실행 ────────────────────────────────────────────────────────────────
|
|
223
223
|
|
|
224
|
+
/** step_result 전송 — D1 한도 소진(d1_quota)·5xx·네트워크 장애로 종결 보고가 유실되지 않도록
|
|
225
|
+
* 한도 중에는 UTC 자정 복구까지(최대 26h) 최대 5분 간격으로 재시도한다. 그 외 오류(4xx 등)는 그대로 throw. */
|
|
226
|
+
async function reportStepResult(payload) {
|
|
227
|
+
const deadline = Date.now() + 26 * 3600 * 1000;
|
|
228
|
+
let throttle = null;
|
|
229
|
+
for (;;) {
|
|
230
|
+
try {
|
|
231
|
+
const res = await api('/ai/e2e/agent/runner/step_result', payload);
|
|
232
|
+
if (throttle) throttle.ok();
|
|
233
|
+
return res;
|
|
234
|
+
} catch (e) {
|
|
235
|
+
const transient = e.code === 'd1_quota' || e.status >= 500 || e.status === undefined;
|
|
236
|
+
if (!transient || authDead(e) || Date.now() > deadline) throw e;
|
|
237
|
+
throttle ??= new ErrorLogThrottle(log);
|
|
238
|
+
throttle.fail(e.code === 'd1_quota'
|
|
239
|
+
? '서버 DB 일일 한도 초과 — 단계 결과를 보관하고 5분 간격으로 재전송합니다'
|
|
240
|
+
: `step_result 전송 실패(${e.message}) — 재전송 대기`);
|
|
241
|
+
await sleep(Math.min(e.retryAfterS ?? 300, 300) * 1000);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
224
246
|
async function handleStep({ step, task, project }) {
|
|
225
247
|
const buf = new EventBuffer(task.id);
|
|
226
248
|
buf.start();
|
|
@@ -261,7 +283,7 @@ async function handleStep({ step, task, project }) {
|
|
|
261
283
|
}
|
|
262
284
|
|
|
263
285
|
const cancelledNow = cancelled() || result?.cancelled;
|
|
264
|
-
await
|
|
286
|
+
await reportStepResult({
|
|
265
287
|
step_id: step.id,
|
|
266
288
|
status: cancelledNow ? 'fail' : result.ok ? 'done' : 'fail',
|
|
267
289
|
result_md: result.finalText ?? null,
|
|
@@ -283,7 +305,7 @@ async function handleStep({ step, task, project }) {
|
|
|
283
305
|
} catch (e) {
|
|
284
306
|
// 프리플라이트 실패·예상치 못한 오류 — 단계 실패로 보고(상태머신이 task 수렴).
|
|
285
307
|
log(`단계 오류: ${e.message}`);
|
|
286
|
-
await
|
|
308
|
+
await reportStepResult({
|
|
287
309
|
step_id: step.id, status: 'fail', error: String(e.message).slice(0, 500),
|
|
288
310
|
cancelled: cancelled(),
|
|
289
311
|
}).catch((err) => {
|
|
@@ -645,6 +667,10 @@ function killGroup(child, signal) {
|
|
|
645
667
|
}
|
|
646
668
|
}
|
|
647
669
|
|
|
670
|
+
const QUOTA_LOG = '서버 DB 일일 한도 초과 — 자동 복구(UTC 자정)까지 5분 간격으로 확인';
|
|
671
|
+
const hbThrottle = new ErrorLogThrottle(log);
|
|
672
|
+
const pollThrottle = new ErrorLogThrottle(log);
|
|
673
|
+
|
|
648
674
|
async function heartbeat() {
|
|
649
675
|
try {
|
|
650
676
|
const res = await api('/ai/e2e/agent/runner/heartbeat', {
|
|
@@ -658,9 +684,10 @@ async function heartbeat() {
|
|
|
658
684
|
token_persisted: tokenFromFile,
|
|
659
685
|
});
|
|
660
686
|
mergeCancels(res);
|
|
687
|
+
hbThrottle.ok();
|
|
661
688
|
} catch (e) {
|
|
662
689
|
if (authDead(e)) warnAuthDead();
|
|
663
|
-
else
|
|
690
|
+
else hbThrottle.fail(e.code === 'd1_quota' ? `heartbeat: ${QUOTA_LOG}` : `heartbeat 실패: ${e.message}`);
|
|
664
691
|
}
|
|
665
692
|
}
|
|
666
693
|
|
|
@@ -915,6 +942,8 @@ async function main() {
|
|
|
915
942
|
let lastIdleLogAt = 0;
|
|
916
943
|
const IDLE_LOG_S = num(process.env.IDLE_LOG_S, 1200); // 기본 20분마다 재안내
|
|
917
944
|
|
|
945
|
+
let pollDelayS = POLL_S; // d1_quota 중에는 늘리고 복구 시 원복
|
|
946
|
+
|
|
918
947
|
for (;;) {
|
|
919
948
|
if (state.stopping) {
|
|
920
949
|
log('데몬을 종료합니다.');
|
|
@@ -926,6 +955,8 @@ async function main() {
|
|
|
926
955
|
mergeCancels(res);
|
|
927
956
|
handleProbe(res);
|
|
928
957
|
handlePrRequest(res);
|
|
958
|
+
pollThrottle.ok();
|
|
959
|
+
pollDelayS = POLL_S;
|
|
929
960
|
if (res.step) {
|
|
930
961
|
state.busy = true;
|
|
931
962
|
try {
|
|
@@ -942,8 +973,13 @@ async function main() {
|
|
|
942
973
|
if (firstIdle) console.log('웹 "머신" 페이지에서 이 머신이 온라인으로 표시되는지 확인하세요.');
|
|
943
974
|
}
|
|
944
975
|
} catch (e) {
|
|
945
|
-
if (e.
|
|
946
|
-
|
|
976
|
+
if (e.code === 'd1_quota') {
|
|
977
|
+
pollDelayS = Math.min(e.retryAfterS ?? 300, 300);
|
|
978
|
+
pollThrottle.fail(QUOTA_LOG);
|
|
979
|
+
} else if (e.status !== 503 && e.status !== 401) {
|
|
980
|
+
pollDelayS = POLL_S;
|
|
981
|
+
pollThrottle.fail(`poll 실패: ${e.message}`);
|
|
982
|
+
} else if (e.status === 503) log(`서버 미구성(E2E_D1_DATABASE_ID): ${e.message}`);
|
|
947
983
|
else if (e.status === 401) {
|
|
948
984
|
console.error('토큰이 거부되었습니다(폐기·오타) — 웹에서 머신을 재등록하고 E2E_RUNNER_TOKEN 을 갱신하세요.');
|
|
949
985
|
process.exit(1);
|
|
@@ -961,7 +997,7 @@ async function main() {
|
|
|
961
997
|
/* 그 외 probe 폴링 실패는 무시 — 다음 주기 재시도 */
|
|
962
998
|
}
|
|
963
999
|
}
|
|
964
|
-
await sleep(
|
|
1000
|
+
await sleep(pollDelayS * 1000);
|
|
965
1001
|
}
|
|
966
1002
|
}
|
|
967
1003
|
|