wildcrane 0.11.72 → 0.11.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/kanban.mjs +608 -334
- package/package.json +2 -2
package/dist/kanban.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// ai4kanban 0.11.
|
|
2
|
+
// ai4kanban 0.11.74 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
|
|
3
3
|
// Do not edit: every change belongs in cli/src/, and a build overwrites this file.
|
|
4
4
|
import { createRequire as __ai4kanbanRequire } from 'node:module'
|
|
5
5
|
const require = __ai4kanbanRequire(import.meta.url)
|
|
@@ -20849,6 +20849,9 @@ function parseReviewPlan(value, previews) {
|
|
|
20849
20849
|
}
|
|
20850
20850
|
return plan;
|
|
20851
20851
|
}
|
|
20852
|
+
function readReviewPlan(plan) {
|
|
20853
|
+
return plan?.map(({ id: id2, after: after2, previews }) => ({ id: id2, after: after2, previews })) ?? null;
|
|
20854
|
+
}
|
|
20852
20855
|
function reviewBoundary(review, assigned) {
|
|
20853
20856
|
const allowed = review.pending_plan ? [] : review.stages.filter((s) => (s.status === "available" || s.status === "running") && (!assigned || assigned.includes(s.id)));
|
|
20854
20857
|
return [
|
|
@@ -20865,7 +20868,6 @@ var init_review_plan = __esm({
|
|
|
20865
20868
|
id = external_exports.string().trim().min(1).max(100);
|
|
20866
20869
|
reviewNodeSchema = external_exports.object({
|
|
20867
20870
|
id,
|
|
20868
|
-
title: external_exports.string().trim().min(1).max(200),
|
|
20869
20871
|
after: external_exports.array(id).max(50).default([]),
|
|
20870
20872
|
previews: external_exports.array(id).max(50).default([])
|
|
20871
20873
|
}).strict();
|
|
@@ -20932,8 +20934,8 @@ function deferRefresh(session, error62, after2) {
|
|
|
20932
20934
|
const attempt2 = Math.min((readRetry(session)?.attempt ?? 0) + 1, 4);
|
|
20933
20935
|
const seconds = after2?.trim() ? Number(after2) : NaN;
|
|
20934
20936
|
const serverDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(after2 ?? "") - Date.now();
|
|
20935
|
-
const
|
|
20936
|
-
const retry2 = { key: refreshKey(session), until: Date.now() +
|
|
20937
|
+
const delay3 = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt2 - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
|
|
20938
|
+
const retry2 = { key: refreshKey(session), until: Date.now() + delay3, attempt: attempt2, error: error62 };
|
|
20937
20939
|
const temporary = `${retryFile()}.${process.pid}.tmp`;
|
|
20938
20940
|
fs3.writeFileSync(temporary, JSON.stringify(retry2), { mode: 384 });
|
|
20939
20941
|
fs3.renameSync(temporary, retryFile());
|
|
@@ -36765,7 +36767,7 @@ var init_preview_blocks = __esm({
|
|
|
36765
36767
|
});
|
|
36766
36768
|
|
|
36767
36769
|
// src/lib/agent/studio-def.ts
|
|
36768
|
-
function parseStudioFile(id2, source2, from) {
|
|
36770
|
+
function parseStudioFile(id2, source2, from, requirePreviewCopy = false) {
|
|
36769
36771
|
const problems = [];
|
|
36770
36772
|
const fail = (offset, path86, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path86, code, message, hint: hint2 });
|
|
36771
36773
|
const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
|
|
@@ -36793,7 +36795,7 @@ function parseStudioFile(id2, source2, from) {
|
|
|
36793
36795
|
const key = error62.params.additionalProperty ?? error62.params.missingProperty;
|
|
36794
36796
|
if (key) parts.push(String(key));
|
|
36795
36797
|
const node2 = parts.length ? document.getIn(parts, true) : document.contents;
|
|
36796
|
-
fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, icon?}} with the declared field types.");
|
|
36798
|
+
fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
|
|
36797
36799
|
}
|
|
36798
36800
|
}
|
|
36799
36801
|
const body = source2.slice(bodyOffset);
|
|
@@ -36803,6 +36805,20 @@ function parseStudioFile(id2, source2, from) {
|
|
|
36803
36805
|
const map3 = raw.previews ?? {};
|
|
36804
36806
|
for (const block of parsed.blocks) if (!Object.hasOwn(map3, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
|
|
36805
36807
|
for (const key of Object.keys(map3)) if (!parsed.blocks.some((b) => b.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
|
|
36808
|
+
if (requirePreviewCopy) for (const block of parsed.blocks) {
|
|
36809
|
+
const metadata = Object.hasOwn(map3, block.id) ? map3[block.id] : void 0;
|
|
36810
|
+
if (!metadata) continue;
|
|
36811
|
+
for (const field2 of ["title", "description"]) for (const lang of ["en", "zh"]) {
|
|
36812
|
+
if (metadata[field2]?.[lang]) continue;
|
|
36813
|
+
fail(
|
|
36814
|
+
bodyOffset + block.start,
|
|
36815
|
+
`previews.${block.id}.${field2}.${lang}`,
|
|
36816
|
+
"preview-display-missing",
|
|
36817
|
+
`Preview ${block.id} needs a ${lang} ${field2}`,
|
|
36818
|
+
"Add non-blank en and zh display text in the Preview metadata."
|
|
36819
|
+
);
|
|
36820
|
+
}
|
|
36821
|
+
}
|
|
36806
36822
|
if (problems.length) return result();
|
|
36807
36823
|
let rules = "", at = 0;
|
|
36808
36824
|
for (const block of parsed.blocks) {
|
|
@@ -36855,7 +36871,7 @@ var init_studio_def = __esm({
|
|
|
36855
36871
|
previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
|
|
36856
36872
|
type: "object",
|
|
36857
36873
|
additionalProperties: false,
|
|
36858
|
-
properties: { title: titles, icon }
|
|
36874
|
+
properties: { title: titles, description: titles, icon }
|
|
36859
36875
|
} }
|
|
36860
36876
|
}
|
|
36861
36877
|
};
|
|
@@ -36897,12 +36913,12 @@ function mcpProblem(text5) {
|
|
|
36897
36913
|
}
|
|
36898
36914
|
return null;
|
|
36899
36915
|
}
|
|
36900
|
-
function checkStudioFiles(value, official = false) {
|
|
36901
|
-
const read5 = inspect(value, official);
|
|
36916
|
+
function checkStudioFiles(value, official = false, allowLegacyPreviewCopy = false) {
|
|
36917
|
+
const read5 = inspect(value, official, allowLegacyPreviewCopy);
|
|
36902
36918
|
const first = read5.problems[0];
|
|
36903
36919
|
return first ? { ok: false, ...first, problems: read5.problems } : { ok: true, def: read5.def, files: read5.files };
|
|
36904
36920
|
}
|
|
36905
|
-
function inspect(value, official) {
|
|
36921
|
+
function inspect(value, official, allowLegacyPreviewCopy = false) {
|
|
36906
36922
|
const problems = [];
|
|
36907
36923
|
const fail = (file2, reason, tooLarge = false) => {
|
|
36908
36924
|
problems.push({ file: file2, reason, ...tooLarge ? { tooLarge } : {} });
|
|
@@ -36947,7 +36963,7 @@ function inspect(value, official) {
|
|
|
36947
36963
|
if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
|
|
36948
36964
|
}
|
|
36949
36965
|
const source2 = files[STUDIO_FILE];
|
|
36950
|
-
const read5 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE) : null;
|
|
36966
|
+
const read5 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE, !official && !allowLegacyPreviewCopy) : null;
|
|
36951
36967
|
if (!read5) fail(STUDIO_FILE, "is missing");
|
|
36952
36968
|
else if ("problem" in read5) for (const problem of read5.problems) problems.push({ ...problem, reason: problem.message });
|
|
36953
36969
|
if (!read5 || "problem" in read5) return { problems };
|
|
@@ -37532,6 +37548,7 @@ function loadGoals() {
|
|
|
37532
37548
|
if (held4.goals !== void 0 && held4.ideas !== void 0 && JSON.stringify(held4.goals) !== JSON.stringify(held4.ideas)) die("goals and ideas do not match.");
|
|
37533
37549
|
const goals = held4.goals ?? held4.ideas;
|
|
37534
37550
|
if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
|
|
37551
|
+
for (const goal of goals) if (goal.review_plan !== void 0) goal.review_plan = readReviewPlan(goal.review_plan);
|
|
37535
37552
|
return { file: file2, held: { ...held4, studios: held4.studios ?? [], goals } };
|
|
37536
37553
|
}
|
|
37537
37554
|
function studioOf(held4, asked) {
|
|
@@ -41157,6 +41174,16 @@ var init_card_studio_backfill = __esm({
|
|
|
41157
41174
|
}
|
|
41158
41175
|
});
|
|
41159
41176
|
|
|
41177
|
+
// src/lib/agent/wire/codex-background-types.ts
|
|
41178
|
+
function idleStopConfirmed(cleanup, session) {
|
|
41179
|
+
return !!session && cleanup?.status === "confirmed" && !!cleanup.instance && Array.isArray(cleanup.kept) && cleanup.kept.length === 0 && cleanup.idleStop?.threadId === session && typeof cleanup.idleStop.turnId === "string" && !!cleanup.idleStop.turnId;
|
|
41180
|
+
}
|
|
41181
|
+
var init_codex_background_types = __esm({
|
|
41182
|
+
"src/lib/agent/wire/codex-background-types.ts"() {
|
|
41183
|
+
"use strict";
|
|
41184
|
+
}
|
|
41185
|
+
});
|
|
41186
|
+
|
|
41160
41187
|
// src/lib/lock.ts
|
|
41161
41188
|
import { randomUUID } from "node:crypto";
|
|
41162
41189
|
import fs18 from "node:fs";
|
|
@@ -41366,6 +41393,68 @@ var init_connection_process = __esm({
|
|
|
41366
41393
|
}
|
|
41367
41394
|
});
|
|
41368
41395
|
|
|
41396
|
+
// src/lib/agent/retry.ts
|
|
41397
|
+
function backoffMs(attempt2, random = Math.random) {
|
|
41398
|
+
const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt2 - 2));
|
|
41399
|
+
return Math.round(step * (1 - 0.25 * random()));
|
|
41400
|
+
}
|
|
41401
|
+
function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs) {
|
|
41402
|
+
if (!Number.isSafeInteger(attempt2) || attempt2 < 1 || failure2.level === 3) return { pause: "needs-review" };
|
|
41403
|
+
const of = failure2.level === 1 ? 2 : 4;
|
|
41404
|
+
if (attempt2 >= of) return { pause: "limit" };
|
|
41405
|
+
const delay3 = failure2.retryAfterMs;
|
|
41406
|
+
const valid = delay3 !== void 0 && !Number.isNaN(delay3) && delay3 >= 0;
|
|
41407
|
+
const wait = valid ? delay3 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
|
|
41408
|
+
if (wait > CAP_MS) return { pause: "wait-too-long" };
|
|
41409
|
+
return { plan: { at: now + wait, of, failure: failure2 } };
|
|
41410
|
+
}
|
|
41411
|
+
function readFailure(raw) {
|
|
41412
|
+
if (!raw || typeof raw !== "object") return;
|
|
41413
|
+
const { code, level: level2, reason, source: source2, retryAfterMs: retryAfterMs2 } = raw;
|
|
41414
|
+
if (typeof code !== "string" || !code || typeof reason !== "string" || level2 !== 1 && level2 !== 2 && level2 !== 3) return;
|
|
41415
|
+
return { code, level: level2, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source2) ? { source: source2 } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
|
|
41416
|
+
}
|
|
41417
|
+
function readRetryPlan(raw, attempt2) {
|
|
41418
|
+
if (!raw || typeof raw !== "object") return;
|
|
41419
|
+
const { at, of, failure: rawFailure } = raw;
|
|
41420
|
+
const failure2 = readFailure(rawFailure);
|
|
41421
|
+
if (!failure2 || typeof at !== "number" || !Number.isFinite(at)) return;
|
|
41422
|
+
const decision = planRetry(failure2, attempt2);
|
|
41423
|
+
if ("plan" in decision && of === decision.plan.of) return { at, of, failure: failure2 };
|
|
41424
|
+
}
|
|
41425
|
+
function pauseLine(pause2, zh = translating()) {
|
|
41426
|
+
switch (pause2) {
|
|
41427
|
+
case "needs-review":
|
|
41428
|
+
return zh ? "\u5DF2\u6682\u505C\uFF0C\u8BF7\u68C0\u67E5\u5931\u8D25\u539F\u56E0\u540E\u7EED\u8DD1\u3002" : "Paused. Review the failure before resuming.";
|
|
41429
|
+
case "limit":
|
|
41430
|
+
return zh ? "\u5DF2\u8FBE\u5230\u81EA\u52A8\u91CD\u8BD5\u6B21\u6570\u4E0A\u9650\u3002" : "The automatic retry limit was reached.";
|
|
41431
|
+
case "wait-too-long":
|
|
41432
|
+
return zh ? "\u6240\u9700\u7B49\u5F85\u65F6\u95F4\u8D85\u8FC7\u4E24\u5206\u949F\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because the required wait exceeds two minutes.";
|
|
41433
|
+
case "unsafe":
|
|
41434
|
+
return zh ? "\u65E0\u6CD5\u786E\u8BA4\u53EF\u4EE5\u5B89\u5168\u7EED\u8DD1\uFF0C\u8BF7\u5148\u6838\u5BF9\u5DF2\u6709\u8FDB\u5EA6\u548C\u64CD\u4F5C\u7ED3\u679C\u3002" : "Check saved progress and operation results before resuming safely.";
|
|
41435
|
+
case "authorization":
|
|
41436
|
+
return zh ? "\u65E0\u6CD5\u786E\u8BA4\u7EED\u8DD1\u6388\u6743\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because authorization to resume could not be confirmed.";
|
|
41437
|
+
}
|
|
41438
|
+
}
|
|
41439
|
+
function retryLine(plan, attempt2, now = Date.now()) {
|
|
41440
|
+
const seconds = Math.max(0, Math.ceil((plan.at - now) / 1e3));
|
|
41441
|
+
return `${plan.failure.reason} \u2014 retrying ${seconds ? `in ${seconds}s` : "now"} (attempt ${attempt2 + 1} of ${plan.of}).`;
|
|
41442
|
+
}
|
|
41443
|
+
function syncRepairPrompt(reason) {
|
|
41444
|
+
return `The Harness could not synchronize the saved result. Correct the diagnostics below, verify the original result and its attachments, then continue from the saved work. Preserve completed work and archive state. Read the task review before changing an approved output and revise its stage first.
|
|
41445
|
+
|
|
41446
|
+
${reason}`;
|
|
41447
|
+
}
|
|
41448
|
+
var BASE_MS, CAP_MS;
|
|
41449
|
+
var init_retry = __esm({
|
|
41450
|
+
"src/lib/agent/retry.ts"() {
|
|
41451
|
+
"use strict";
|
|
41452
|
+
init_language();
|
|
41453
|
+
BASE_MS = 15e3;
|
|
41454
|
+
CAP_MS = 12e4;
|
|
41455
|
+
}
|
|
41456
|
+
});
|
|
41457
|
+
|
|
41369
41458
|
// src/lib/cloud/execution.ts
|
|
41370
41459
|
function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
|
|
41371
41460
|
try {
|
|
@@ -41683,8 +41772,8 @@ var init_package = __esm({
|
|
|
41683
41772
|
"package.json"() {
|
|
41684
41773
|
package_default = {
|
|
41685
41774
|
name: "wildcrane",
|
|
41686
|
-
version: "0.11.
|
|
41687
|
-
akbContract:
|
|
41775
|
+
version: "0.11.74",
|
|
41776
|
+
akbContract: 21,
|
|
41688
41777
|
description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
|
|
41689
41778
|
keywords: [
|
|
41690
41779
|
"kanban",
|
|
@@ -42696,71 +42785,6 @@ var init_types3 = __esm({
|
|
|
42696
42785
|
}
|
|
42697
42786
|
});
|
|
42698
42787
|
|
|
42699
|
-
// src/lib/agent/harnesses/transient.ts
|
|
42700
|
-
function reasonLine(text5, rule) {
|
|
42701
|
-
const line = text5.split("\n").find((l) => rule.test(l.toLowerCase())) ?? text5;
|
|
42702
|
-
const said2 = line.trim().replace(/\s+/g, " ");
|
|
42703
|
-
return said2.length > REASON_MAX ? `${said2.slice(0, REASON_MAX - 1)}\u2026` : said2;
|
|
42704
|
-
}
|
|
42705
|
-
function manualFailure(text5) {
|
|
42706
|
-
return MANUAL.some((rule) => rule.test(text5.toLowerCase()));
|
|
42707
|
-
}
|
|
42708
|
-
function providerBlip(...said2) {
|
|
42709
|
-
for (const text5 of said2) {
|
|
42710
|
-
if (!text5?.trim()) continue;
|
|
42711
|
-
const lower = text5.toLowerCase();
|
|
42712
|
-
if (manualFailure(text5)) return void 0;
|
|
42713
|
-
const limited2 = /\b429\b|rate[ _-]?limit/.test(lower);
|
|
42714
|
-
const hit = limited2 && RETRY_AFTER.test(text5) ? RETRY_AFTER : limited2 ? void 0 : PASSING.find((rule) => rule.test(lower));
|
|
42715
|
-
if (!hit) continue;
|
|
42716
|
-
const asked = RETRY_AFTER.exec(text5);
|
|
42717
|
-
const seconds = asked ? Number(asked[1]) : NaN;
|
|
42718
|
-
return {
|
|
42719
|
-
reason: reasonLine(text5, hit),
|
|
42720
|
-
...Number.isFinite(seconds) && seconds > 0 ? { retryAfterMs: seconds * 1e3 } : {}
|
|
42721
|
-
};
|
|
42722
|
-
}
|
|
42723
|
-
return void 0;
|
|
42724
|
-
}
|
|
42725
|
-
function recoveryFailure(text5) {
|
|
42726
|
-
const temporary = providerBlip(text5);
|
|
42727
|
-
if (temporary) return { ...temporary, handler: "execution" };
|
|
42728
|
-
if (!manualFailure(text5) && /(?:verification|validation|test|compilation|build) failed|syntax error|type error/i.test(text5)) {
|
|
42729
|
-
return { reason: text5, handler: "agent", retryAfterMs: 0 };
|
|
42730
|
-
}
|
|
42731
|
-
return void 0;
|
|
42732
|
-
}
|
|
42733
|
-
var MANUAL, PASSING, RETRY_AFTER, REASON_MAX;
|
|
42734
|
-
var init_transient = __esm({
|
|
42735
|
-
"src/lib/agent/harnesses/transient.ts"() {
|
|
42736
|
-
"use strict";
|
|
42737
|
-
MANUAL = [
|
|
42738
|
-
/\b(401|403)\b/,
|
|
42739
|
-
/unauthorized|forbidden|permission (?:denied|required|check failed)|permission_denied|soft.denied|auto-denied|权限拒绝/,
|
|
42740
|
-
/authenticat|invalid api key|api[_ ]key|not (?:logged|signed) in|please (?:log|sign) in|\/login|oauth/,
|
|
42741
|
-
/usage limit|quota|balance|credits?|insufficient|out of tokens|resource[ _-]?exhausted/,
|
|
42742
|
-
/cancell?ed|aborted by|interrupted by the user/,
|
|
42743
|
-
/maximum budget|max(imum)? turns|exceeded the budget/,
|
|
42744
|
-
/model not found|unknown model|invalid model|model (?:is )?unavailable|model[^\n]+ is (?:unavailable|not recognized)|unsupported|invalid[_ ]request/
|
|
42745
|
-
];
|
|
42746
|
-
PASSING = [
|
|
42747
|
-
// 502/503/529 are distinctive enough to read as a status wherever they appear. A bare
|
|
42748
|
-
// 500 is not — a failure line counting something would match it — so it is left to the
|
|
42749
|
-
// words below, which is how that status is actually written out.
|
|
42750
|
-
/\b(502|503|529)\b/,
|
|
42751
|
-
/at capacity|overloaded|service unavailable|bad gateway|internal server error|server_error/,
|
|
42752
|
-
/connection (lost|dropped|reset|error|closed)|socket hang up|stream (error|disconnected)/,
|
|
42753
|
-
/econnreset|econnrefused|etimedout|enetunreach|enotfound|eai_again/,
|
|
42754
|
-
/fetch failed|request timed out|network (?:error|failure)|temporary network failure/,
|
|
42755
|
-
/(?:initialize|connection|connect|response)[^\n]*timed out|idle[_ -]?timeout|stream[^\n]*timed out|no (?:response|events?) for 5 minutes/,
|
|
42756
|
-
/request failed:[^\n]*\b(?:unexpected )?eof\b/,
|
|
42757
|
-
/rpc error: code = (?:unavailable|deadlineexceeded)\b|deadline_exceeded|dial tcp[^\n]*(?:timeout|refused|no such host)/
|
|
42758
|
-
];
|
|
42759
|
-
RETRY_AFTER = /retry[-_\s]?after["':=\s]+(\d+)/i;
|
|
42760
|
-
REASON_MAX = 140;
|
|
42761
|
-
}
|
|
42762
|
-
});
|
|
42763
|
-
|
|
42764
42788
|
// src/lib/agent/prices.ts
|
|
42765
42789
|
function antigravityPrices(at) {
|
|
42766
42790
|
const pro = at < Date.parse("2026-12-01T00:00:00Z") ? 2 : 4;
|
|
@@ -43083,7 +43107,7 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
|
|
|
43083
43107
|
let partial2 = "";
|
|
43084
43108
|
let final;
|
|
43085
43109
|
let failure2;
|
|
43086
|
-
let
|
|
43110
|
+
let classified;
|
|
43087
43111
|
let imageFailure;
|
|
43088
43112
|
let requiredImages = [];
|
|
43089
43113
|
const readImages = /* @__PURE__ */ new Set();
|
|
@@ -43115,24 +43139,22 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
|
|
|
43115
43139
|
const calls = /* @__PURE__ */ new Set();
|
|
43116
43140
|
const closed2 = /* @__PURE__ */ new Set();
|
|
43117
43141
|
const events = createEventCollector();
|
|
43118
|
-
const fail = (reason) => {
|
|
43119
|
-
if (limited(reason)) rateLimit = failureHint(reason);
|
|
43120
|
-
if (failure2 && manualFailure(failure2) && !(limited(failure2) && limited(reason))) return;
|
|
43142
|
+
const fail = (reason, code = "provider_failed") => {
|
|
43121
43143
|
failure2 = failureHint(reason);
|
|
43144
|
+
classified = { code, level: 3, reason: failure2 };
|
|
43122
43145
|
events.error(failure2);
|
|
43123
43146
|
};
|
|
43124
43147
|
const reader = createLineReader((line) => {
|
|
43125
43148
|
const e = frame(line);
|
|
43126
43149
|
if (!e) {
|
|
43127
43150
|
offStream = line.trim() || offStream;
|
|
43128
|
-
if (/^(?:error:|rpc error:)/i.test(line.trim()) && limited(line)) fail(line.trim());
|
|
43129
43151
|
return `${line}
|
|
43130
43152
|
`;
|
|
43131
43153
|
}
|
|
43132
43154
|
if (e.event === "init") {
|
|
43133
43155
|
const got = str2(e.conversation_id);
|
|
43134
43156
|
if (expectedSession && got !== expectedSession) {
|
|
43135
|
-
fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.");
|
|
43157
|
+
fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.", "session_mismatch");
|
|
43136
43158
|
return "";
|
|
43137
43159
|
}
|
|
43138
43160
|
session = got || session;
|
|
@@ -43179,7 +43201,6 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
|
|
|
43179
43201
|
}
|
|
43180
43202
|
const error62 = obj2(tool.error);
|
|
43181
43203
|
const reason = str2(error62.message) || str2(error62.type);
|
|
43182
|
-
if (reason && /permission|denied|soft.den/i.test(reason)) fail(reason);
|
|
43183
43204
|
if (["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str2(step.state)) && !closed2.has(id2)) {
|
|
43184
43205
|
closed2.add(id2);
|
|
43185
43206
|
const failed2 = !!reason || step.state !== "DONE";
|
|
@@ -43204,7 +43225,7 @@ ${imageError(target, reason || str2(step.state))}
|
|
|
43204
43225
|
if (e.event === "result") {
|
|
43205
43226
|
const result = obj2(e.result);
|
|
43206
43227
|
if (expectedSession && str2(result.conversation_id) && result.conversation_id !== expectedSession) {
|
|
43207
|
-
fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.");
|
|
43228
|
+
fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.", "session_mismatch");
|
|
43208
43229
|
terminal = true;
|
|
43209
43230
|
return "";
|
|
43210
43231
|
}
|
|
@@ -43220,8 +43241,8 @@ ${imageError(target, reason || str2(step.state))}
|
|
|
43220
43241
|
if (imageFailure) events.error(imageFailure);
|
|
43221
43242
|
readImages.clear();
|
|
43222
43243
|
imageErrors.clear();
|
|
43223
|
-
if (Array.isArray(result.denied_actions) && result.denied_actions.length) fail(translating() ? "Antigravity \u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Antigravity permission denied. Check permission rules, then retry.");
|
|
43224
|
-
if (typeof result.response !== "string" || result.status !== "SUCCESS" || str2(result.error) || result.finished_reason && result.finished_reason !== "completed" && result.finished_reason !== "success") {
|
|
43244
|
+
if (Array.isArray(result.denied_actions) && result.denied_actions.length) fail(translating() ? "Antigravity \u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Antigravity permission denied. Check permission rules, then retry.", "permission_denied");
|
|
43245
|
+
else if (!failure2 && (typeof result.response !== "string" || result.status !== "SUCCESS" || str2(result.error) || result.finished_reason && result.finished_reason !== "completed" && result.finished_reason !== "success")) {
|
|
43225
43246
|
fail(result.status === "CANCELED" ? `Antigravity: CANCELED${result.error ? `: ${str2(result.error)}` : ""}` : str2(result.error) || `Antigravity: ${str2(result.status) || "missing status"}`);
|
|
43226
43247
|
}
|
|
43227
43248
|
events.end();
|
|
@@ -43243,17 +43264,13 @@ ${imageError(target, reason || str2(step.state))}
|
|
|
43243
43264
|
if (!terminal) {
|
|
43244
43265
|
incomplete = true;
|
|
43245
43266
|
const diagnostics = [stderr.trim(), offStream?.match(/^(?:error:|rpc error:|API error\b)/i) ? offStream : void 0];
|
|
43246
|
-
|
|
43247
|
-
if (diagnostic) fail(diagnostic);
|
|
43248
|
-
if (!failure2) fail(translating() ? "Antigravity \u672A\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u540E\u91CD\u8BD5\u3002" : "Antigravity returned no final result. Check the log, then retry.");
|
|
43267
|
+
if (!failure2) fail(diagnostics.find(Boolean) || (translating() ? "Antigravity \u672A\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u540E\u91CD\u8BD5\u3002" : "Antigravity returned no final result. Check the log, then retry."), "result_missing");
|
|
43249
43268
|
}
|
|
43250
43269
|
events.end();
|
|
43251
43270
|
return text5;
|
|
43252
43271
|
},
|
|
43253
43272
|
stderr(chunk) {
|
|
43254
43273
|
stderr = (stderr + chunk).slice(-16e3);
|
|
43255
|
-
if (limited(stderr)) fail(stderr.trim());
|
|
43256
|
-
if (/soft.denied|auto-denied|permission (?:denied|required)|denied by.*(?:policy|rule)|requires? (?:user )?(?:approval|permission)/i.test(stderr)) fail(stderr.trim());
|
|
43257
43274
|
},
|
|
43258
43275
|
result: () => final || (failure2 ? partial2 || void 0 : final),
|
|
43259
43276
|
resumeId: () => session,
|
|
@@ -43263,17 +43280,16 @@ ${imageError(target, reason || str2(step.state))}
|
|
|
43263
43280
|
costIncomplete: () => incomplete || void 0,
|
|
43264
43281
|
context: () => context,
|
|
43265
43282
|
failure: () => failure2 || imageFailure,
|
|
43266
|
-
|
|
43267
|
-
|
|
43283
|
+
terminalFailure: () => terminal && !!classified,
|
|
43284
|
+
executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
|
|
43268
43285
|
events: events.events,
|
|
43269
43286
|
activity: events.activity
|
|
43270
43287
|
};
|
|
43271
43288
|
}
|
|
43272
|
-
var KINDS, zero, usageOf, add,
|
|
43289
|
+
var KINDS, zero, usageOf, add, imagePath;
|
|
43273
43290
|
var init_antigravity = __esm({
|
|
43274
43291
|
"src/lib/agent/wire/antigravity.ts"() {
|
|
43275
43292
|
"use strict";
|
|
43276
|
-
init_transient();
|
|
43277
43293
|
init_prices();
|
|
43278
43294
|
init_language();
|
|
43279
43295
|
init_events();
|
|
@@ -43301,7 +43317,6 @@ var init_antigravity = __esm({
|
|
|
43301
43317
|
return { input: num2(u.input_tokens), output: num2(u.output_tokens), cacheRead: num2(u.cache_read_tokens), cacheCreation: 0 };
|
|
43302
43318
|
};
|
|
43303
43319
|
add = (a, b) => ({ input: a.input + b.input, output: a.output + b.output, cacheRead: a.cacheRead + b.cacheRead, cacheCreation: 0 });
|
|
43304
|
-
limited = (reason) => /\b429\b|rate[ _-]?limit|resource[ _-]?exhausted|quota[^\n]*\b(?:exceeded|exhausted|depleted|reached)\b|(?:exceed|exhaust|deplet)[^\n]*quota|(?:insufficient|exhausted|out of|no remaining) (?:credits?|quota)|credits?[^\n]*(?:exhaust|deplet|exceed)/i.test(reason);
|
|
43305
43320
|
imagePath = (target) => /\.(?:png|jpe?g|gif|webp|bmp|tiff?|svg)$/i.test(target);
|
|
43306
43321
|
}
|
|
43307
43322
|
});
|
|
@@ -43343,7 +43358,6 @@ var init_antigravity2 = __esm({
|
|
|
43343
43358
|
init_spawnable();
|
|
43344
43359
|
init_models();
|
|
43345
43360
|
init_types3();
|
|
43346
|
-
init_transient();
|
|
43347
43361
|
init_language();
|
|
43348
43362
|
init_antigravity();
|
|
43349
43363
|
EFFORT_ID = /-(?:low|medium|high|xhigh|max)$/i;
|
|
@@ -43410,11 +43424,10 @@ ${rule}
|
|
|
43410
43424
|
`);
|
|
43411
43425
|
return { args: ["--add-dir", root2] };
|
|
43412
43426
|
},
|
|
43413
|
-
transient: ({ failure: failure2 }) => providerBlip(failure2),
|
|
43414
43427
|
reports: ["cost", "tokens", "model", "context"],
|
|
43415
43428
|
adoptsSessionId: false,
|
|
43416
43429
|
savesSessionAtOpen: true,
|
|
43417
|
-
stopsOnRateLimit:
|
|
43430
|
+
stopsOnRateLimit: false,
|
|
43418
43431
|
// `models` is read-only. Only explicit authentication errors mean signed out.
|
|
43419
43432
|
login: {
|
|
43420
43433
|
args: ["models"],
|
|
@@ -43513,6 +43526,76 @@ var init_check = __esm({
|
|
|
43513
43526
|
}
|
|
43514
43527
|
});
|
|
43515
43528
|
|
|
43529
|
+
// src/lib/agent/wire/failures.ts
|
|
43530
|
+
function executionFailure(error62) {
|
|
43531
|
+
if (error62 instanceof ExecutionError) return error62.failure;
|
|
43532
|
+
const code = str2(obj2(error62).code);
|
|
43533
|
+
const reason = error62 instanceof Error ? error62.message : String(error62);
|
|
43534
|
+
return {
|
|
43535
|
+
code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
|
|
43536
|
+
level: NETWORK.has(code) ? 2 : 3,
|
|
43537
|
+
source: "harness",
|
|
43538
|
+
reason
|
|
43539
|
+
};
|
|
43540
|
+
}
|
|
43541
|
+
function retryAfterMs(value, now = Date.now()) {
|
|
43542
|
+
if (typeof value !== "string") return;
|
|
43543
|
+
const header = value.trim();
|
|
43544
|
+
if (/^\d+$/.test(header)) return Math.min(Number(header) * 1e3, Number.MAX_SAFE_INTEGER);
|
|
43545
|
+
if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header)) return;
|
|
43546
|
+
const date5 = Date.parse(header);
|
|
43547
|
+
if (Number.isFinite(date5)) return Math.max(0, date5 - now);
|
|
43548
|
+
}
|
|
43549
|
+
function providerFailure(error62, reason) {
|
|
43550
|
+
const info = obj2(error62);
|
|
43551
|
+
const status = typeof info.status === "number" ? info.status : void 0;
|
|
43552
|
+
const headers = obj2(info.headers);
|
|
43553
|
+
const wait = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
|
|
43554
|
+
const code = info.code ?? info.type;
|
|
43555
|
+
if (code === "session_not_found") return { code, source: "provider", level: 3, reason };
|
|
43556
|
+
if (status === 401 || status === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(code))) {
|
|
43557
|
+
return { code: "provider_refused", source: "provider", level: 3, reason };
|
|
43558
|
+
}
|
|
43559
|
+
if (code === "rate_limit_error") return { code: "rate_limited", source: "provider", level: 2, reason, retryAfterMs: wait };
|
|
43560
|
+
if (TEMPORARY_HTTP.has(status ?? 0) || code === "overloaded_error") return { code: "service_overloaded", source: "provider", level: 2, reason, retryAfterMs: wait };
|
|
43561
|
+
if (NETWORK.has(str2(code))) return { code: "connection_lost", source: "provider", level: 2, reason, retryAfterMs: wait };
|
|
43562
|
+
return { code: "provider_failed", source: "provider", level: 3, reason };
|
|
43563
|
+
}
|
|
43564
|
+
function codexFailure(raw, fallback) {
|
|
43565
|
+
const error62 = obj2(raw);
|
|
43566
|
+
const failure2 = readFailure(error62.wildcraneFailure);
|
|
43567
|
+
if (failure2?.source === "harness" || failure2?.source === "invariant") return failure2;
|
|
43568
|
+
const reason = str2(error62.message) || fallback;
|
|
43569
|
+
const info = error62.codexErrorInfo;
|
|
43570
|
+
if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason);
|
|
43571
|
+
if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason);
|
|
43572
|
+
const types = obj2(info);
|
|
43573
|
+
for (const kind of ["httpConnectionFailed", "responseStreamConnectionFailed", "responseStreamDisconnected", "responseTooManyFailedAttempts"]) {
|
|
43574
|
+
if (!(kind in types)) continue;
|
|
43575
|
+
const status = obj2(types[kind]).httpStatusCode;
|
|
43576
|
+
if (typeof status === "number") return providerFailure({ ...error62, status }, reason);
|
|
43577
|
+
if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason);
|
|
43578
|
+
}
|
|
43579
|
+
return providerFailure(error62, reason);
|
|
43580
|
+
}
|
|
43581
|
+
var ExecutionError, NETWORK, TEMPORARY_HTTP;
|
|
43582
|
+
var init_failures = __esm({
|
|
43583
|
+
"src/lib/agent/wire/failures.ts"() {
|
|
43584
|
+
"use strict";
|
|
43585
|
+
init_retry();
|
|
43586
|
+
init_json();
|
|
43587
|
+
ExecutionError = class extends Error {
|
|
43588
|
+
constructor(failure2) {
|
|
43589
|
+
super(failure2.reason);
|
|
43590
|
+
this.failure = failure2;
|
|
43591
|
+
}
|
|
43592
|
+
failure;
|
|
43593
|
+
};
|
|
43594
|
+
NETWORK = /* @__PURE__ */ new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "ENETUNREACH", "EAI_AGAIN", "UND_ERR_SOCKET"]);
|
|
43595
|
+
TEMPORARY_HTTP = /* @__PURE__ */ new Set([502, 503, 504, 529]);
|
|
43596
|
+
}
|
|
43597
|
+
});
|
|
43598
|
+
|
|
43516
43599
|
// src/lib/agent/wire/claude-stream.ts
|
|
43517
43600
|
function targetOf2(input2) {
|
|
43518
43601
|
const args2 = obj2(input2);
|
|
@@ -43572,7 +43655,8 @@ function createStreamRenderer() {
|
|
|
43572
43655
|
let context;
|
|
43573
43656
|
let limit;
|
|
43574
43657
|
let failure2;
|
|
43575
|
-
let
|
|
43658
|
+
let apiFailure;
|
|
43659
|
+
let classified;
|
|
43576
43660
|
let background;
|
|
43577
43661
|
const turns = [];
|
|
43578
43662
|
const backgrounded = /* @__PURE__ */ new Set();
|
|
@@ -43588,16 +43672,14 @@ function createStreamRenderer() {
|
|
|
43588
43672
|
const renderLine = (line) => {
|
|
43589
43673
|
if (!line.trim()) return "";
|
|
43590
43674
|
const ev = frame(line);
|
|
43591
|
-
if (!ev) {
|
|
43592
|
-
offStream = line.trim();
|
|
43593
|
-
return `${line}
|
|
43675
|
+
if (!ev) return `${line}
|
|
43594
43676
|
`;
|
|
43595
|
-
}
|
|
43596
43677
|
if (model === void 0) model = eventModel(ev);
|
|
43597
43678
|
if (str2(ev.parent_tool_use_id)) return "";
|
|
43598
43679
|
if (ev.type === "assistant" || ev.type === "stream_event" && obj2(ev.event).type === "content_block_delta") events.progress();
|
|
43599
43680
|
switch (ev.type) {
|
|
43600
43681
|
case "assistant": {
|
|
43682
|
+
apiFailure = typeof ev.error === "string" ? providerFailure({ type: ev.error }, "Claude could not complete the request.") : void 0;
|
|
43601
43683
|
const msg = ev.message;
|
|
43602
43684
|
const holding = promptSize(msg?.usage);
|
|
43603
43685
|
if (holding) context = { used: holding };
|
|
@@ -43650,6 +43732,8 @@ function createStreamRenderer() {
|
|
|
43650
43732
|
const turnUsage = usageOf2(ev.usage);
|
|
43651
43733
|
if (turnUsage) usage3 = usage3 ? addUsage(usage3, turnUsage) : turnUsage;
|
|
43652
43734
|
failure2 = ev.is_error === true ? whyItFailed(ev) : void 0;
|
|
43735
|
+
classified = failure2 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, source: "validation", reason: failure2 } : { ...apiFailure ?? providerFailure(ev.error, failure2), reason: failure2 } : void 0;
|
|
43736
|
+
apiFailure = void 0;
|
|
43653
43737
|
if (failure2) events.error(failure2);
|
|
43654
43738
|
turns.push({
|
|
43655
43739
|
...typeof ev.result === "string" ? { result: ev.result } : {},
|
|
@@ -43684,7 +43768,7 @@ function createStreamRenderer() {
|
|
|
43684
43768
|
context: () => context && limit ? { ...context, limit } : context,
|
|
43685
43769
|
model: () => model,
|
|
43686
43770
|
failure: () => failure2,
|
|
43687
|
-
|
|
43771
|
+
executionFailure: () => classified,
|
|
43688
43772
|
background: () => background,
|
|
43689
43773
|
turns: () => turns,
|
|
43690
43774
|
events: events.events,
|
|
@@ -43706,6 +43790,7 @@ var ARG_KEYS, TOOL_KINDS2, SUBAGENT_TOOLS, USER_FIXES, addUsage;
|
|
|
43706
43790
|
var init_claude_stream = __esm({
|
|
43707
43791
|
"src/lib/agent/wire/claude-stream.ts"() {
|
|
43708
43792
|
"use strict";
|
|
43793
|
+
init_failures();
|
|
43709
43794
|
init_events();
|
|
43710
43795
|
init_json();
|
|
43711
43796
|
init_stream();
|
|
@@ -44133,15 +44218,15 @@ function createCodexStreamRenderer(carried = false) {
|
|
|
44133
44218
|
return "";
|
|
44134
44219
|
// 最终失败保留;连接提示只在没有后续成功完成时才作为失败。
|
|
44135
44220
|
case "turn.failed": {
|
|
44136
|
-
const said2 = str2(obj2(ev.error).message) || failure2 || "Codex
|
|
44137
|
-
failure2 = said2;
|
|
44221
|
+
const said2 = str2(obj2(ev.error).message) || failure2?.reason || "Codex execution failed.";
|
|
44222
|
+
failure2 = codexFailure(ev.error, said2);
|
|
44138
44223
|
events.error(said2);
|
|
44139
44224
|
return `[error] ${said2}
|
|
44140
44225
|
`;
|
|
44141
44226
|
}
|
|
44142
44227
|
case "error": {
|
|
44143
44228
|
const said2 = str2(ev.message);
|
|
44144
|
-
failure2 =
|
|
44229
|
+
if (ev.willRetry !== true && ev.will_retry !== true && said2) failure2 = codexFailure(ev.error ?? ev, said2);
|
|
44145
44230
|
events.log(`[Codex] ${said2}
|
|
44146
44231
|
`);
|
|
44147
44232
|
return `[Codex] ${said2}
|
|
@@ -44188,7 +44273,8 @@ function createCodexStreamRenderer(carried = false) {
|
|
|
44188
44273
|
},
|
|
44189
44274
|
costIncomplete: () => childSpend(subagents, since).costIncomplete || childSpend(subagents, since).costUsd !== void 0 && priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own2()) === void 0 || void 0,
|
|
44190
44275
|
resumeId: () => threadId,
|
|
44191
|
-
failure: () => failure2 ?? background.failure(),
|
|
44276
|
+
failure: () => failure2?.reason ?? background.failure(),
|
|
44277
|
+
executionFailure: () => failure2,
|
|
44192
44278
|
background: () => subagents.size ? background.count() : void 0,
|
|
44193
44279
|
events: events.events,
|
|
44194
44280
|
activity: events.activity
|
|
@@ -44198,6 +44284,7 @@ var imageSafeText, CALLS, LOOK_EVERY_MS;
|
|
|
44198
44284
|
var init_codex_stream = __esm({
|
|
44199
44285
|
"src/lib/agent/wire/codex-stream.ts"() {
|
|
44200
44286
|
"use strict";
|
|
44287
|
+
init_failures();
|
|
44201
44288
|
init_background();
|
|
44202
44289
|
init_codex_session();
|
|
44203
44290
|
init_events();
|
|
@@ -44546,7 +44633,7 @@ function connect(stdout, stdin, onCall, dialect = {}) {
|
|
|
44546
44633
|
const closed2 = (why2) => {
|
|
44547
44634
|
if (gone) return;
|
|
44548
44635
|
gone = why2;
|
|
44549
|
-
for (const { fail } of waiting.values()) fail(
|
|
44636
|
+
for (const { fail } of waiting.values()) fail(why2);
|
|
44550
44637
|
waiting.clear();
|
|
44551
44638
|
};
|
|
44552
44639
|
stdout.on("data", (chunk) => {
|
|
@@ -44571,17 +44658,17 @@ function connect(stdout, stdin, onCall, dialect = {}) {
|
|
|
44571
44658
|
waiting.delete(String(msg.id));
|
|
44572
44659
|
if (msg.error) {
|
|
44573
44660
|
const said2 = [str2(msg.error.message), str2(obj2(msg.error.data).message)].filter(Boolean).join(": ");
|
|
44574
|
-
pending.fail(new RpcError(said2 || `the agent refused (${msg.error.code ?? "no code"})`, msg.error.code));
|
|
44661
|
+
pending.fail(new RpcError(said2 || `the agent refused (${msg.error.code ?? "no code"})`, msg.error.code, msg.error.data));
|
|
44575
44662
|
} else pending.ok(obj2(msg.result));
|
|
44576
44663
|
}
|
|
44577
44664
|
});
|
|
44578
|
-
stdout.on("close", () => closed2("
|
|
44579
|
-
stdout.on("error", (err) => closed2(
|
|
44580
|
-
stdin.on("error", (err) => closed2(
|
|
44665
|
+
stdout.on("close", () => closed2(new ExecutionError({ code: "connection_lost", level: 2, reason: "The agent closed the connection." })));
|
|
44666
|
+
stdout.on("error", (err) => closed2(new ExecutionError(executionFailure(err))));
|
|
44667
|
+
stdin.on("error", (err) => closed2(new ExecutionError(executionFailure(err))));
|
|
44581
44668
|
return {
|
|
44582
44669
|
/** Ask the agent something. Rejects with the agent's own words when it says no. */
|
|
44583
44670
|
call(method, params) {
|
|
44584
|
-
if (gone) return Promise.reject(
|
|
44671
|
+
if (gone) return Promise.reject(gone);
|
|
44585
44672
|
const id2 = dialect.stringIds ? String(nextId++) : nextId++;
|
|
44586
44673
|
return new Promise((ok, fail) => {
|
|
44587
44674
|
waiting.set(String(id2), { ok, fail });
|
|
@@ -44606,14 +44693,17 @@ var RpcError;
|
|
|
44606
44693
|
var init_rpc = __esm({
|
|
44607
44694
|
"src/lib/agent/wire/rpc.ts"() {
|
|
44608
44695
|
"use strict";
|
|
44696
|
+
init_failures();
|
|
44609
44697
|
init_json();
|
|
44610
44698
|
RpcError = class extends Error {
|
|
44611
|
-
constructor(message, code) {
|
|
44699
|
+
constructor(message, code, data) {
|
|
44612
44700
|
super(message);
|
|
44613
44701
|
this.code = code;
|
|
44702
|
+
this.data = data;
|
|
44614
44703
|
this.name = "RpcError";
|
|
44615
44704
|
}
|
|
44616
44705
|
code;
|
|
44706
|
+
data;
|
|
44617
44707
|
};
|
|
44618
44708
|
}
|
|
44619
44709
|
});
|
|
@@ -44722,9 +44812,6 @@ function usageOf3(value, grossInput = false) {
|
|
|
44722
44812
|
const sum = counts.input + counts.cacheCreation + counts.cacheRead + counts.output;
|
|
44723
44813
|
return sum > 0 ? counts : void 0;
|
|
44724
44814
|
}
|
|
44725
|
-
function sessionGone(e) {
|
|
44726
|
-
return e instanceof RpcError && e.code === INVALID_PARAMS && /session\b.*\bnot found/i.test(e.message);
|
|
44727
|
-
}
|
|
44728
44815
|
async function newSession(rpc, cwd, mcpServers) {
|
|
44729
44816
|
const opened = await rpc.call("session/new", { cwd, mcpServers });
|
|
44730
44817
|
const sessionId = str2(opened.sessionId);
|
|
@@ -44756,6 +44843,8 @@ async function oneTurn(io, options) {
|
|
|
44756
44843
|
const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
|
|
44757
44844
|
let started = false;
|
|
44758
44845
|
let contentAt = 0;
|
|
44846
|
+
let thinkingAt = 0;
|
|
44847
|
+
let thinking = false;
|
|
44759
44848
|
let currentSession = "";
|
|
44760
44849
|
const events = createEventCollector();
|
|
44761
44850
|
const emit = () => {
|
|
@@ -44785,7 +44874,20 @@ async function oneTurn(io, options) {
|
|
|
44785
44874
|
}
|
|
44786
44875
|
if (live && (!obj2(msg.params).sessionId || obj2(msg.params).sessionId === currentSession)) {
|
|
44787
44876
|
const kind = str2(obj2(obj2(msg.params).update).sessionUpdate);
|
|
44788
|
-
if (["agent_message_chunk", "agent_thought_chunk"].includes(kind)
|
|
44877
|
+
if (["agent_message_chunk", "agent_thought_chunk"].includes(kind) && str2(obj2(obj2(obj2(msg.params).update).content).text)) {
|
|
44878
|
+
io.activity?.();
|
|
44879
|
+
if (kind === "agent_thought_chunk") {
|
|
44880
|
+
if (!thinking || Date.now() - thinkingAt >= 1e3) {
|
|
44881
|
+
io.event?.({ kind: "status", data: { state: "thinking", source: "acp" } });
|
|
44882
|
+
thinkingAt = Date.now();
|
|
44883
|
+
}
|
|
44884
|
+
thinking = true;
|
|
44885
|
+
}
|
|
44886
|
+
}
|
|
44887
|
+
if (thinking && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
|
|
44888
|
+
thinking = false;
|
|
44889
|
+
io.event?.({ kind: "status", data: { state: "running", source: "acp" } });
|
|
44890
|
+
}
|
|
44789
44891
|
if (!started && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
|
|
44790
44892
|
started = true;
|
|
44791
44893
|
phase("started");
|
|
@@ -44835,7 +44937,10 @@ async function oneTurn(io, options) {
|
|
|
44835
44937
|
try {
|
|
44836
44938
|
opened = await bounded(rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers }), preparingUntil - Date.now(), "ACP session/load timed out.");
|
|
44837
44939
|
} catch (e) {
|
|
44838
|
-
|
|
44940
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
44941
|
+
const failure2 = e instanceof RpcError ? providerFailure(e.data, reason) : executionFailure(e);
|
|
44942
|
+
if (failure2.code !== "session_not_found") throw e;
|
|
44943
|
+
if (!io.restartPrompt) throw new ExecutionError(failure2);
|
|
44839
44944
|
const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
|
|
44840
44945
|
opened = fresh.opened;
|
|
44841
44946
|
sessionId = fresh.sessionId;
|
|
@@ -44882,7 +44987,7 @@ async function oneTurn(io, options) {
|
|
|
44882
44987
|
`);
|
|
44883
44988
|
events.error(why2);
|
|
44884
44989
|
emit();
|
|
44885
|
-
return { ok: false, result, error: why2, usage: usage3, context, costUsd };
|
|
44990
|
+
return { ok: false, result, error: why2, failure: { code: stopReason2, level: 3, reason: why2 }, usage: usage3, context, costUsd };
|
|
44886
44991
|
}
|
|
44887
44992
|
emit();
|
|
44888
44993
|
return { ok: true, result, usage: usage3, context, costUsd };
|
|
@@ -44895,7 +45000,7 @@ async function oneTurn(io, options) {
|
|
|
44895
45000
|
events.error(error62);
|
|
44896
45001
|
emit();
|
|
44897
45002
|
if (currentSession) saveAcpCost(acpCostFile(options.tool ?? "acp", io.cwd, currentSession), costUsd);
|
|
44898
|
-
return { ok: false, result, error: error62, usage: void 0, costUsd: costUsd === void 0 || costBefore === void 0 ? void 0 : costUsd < costBefore ? costUsd : costUsd - costBefore };
|
|
45003
|
+
return { ok: false, result, error: error62, failure: e instanceof RpcError ? providerFailure(e.data, error62) : executionFailure(e), usage: void 0, costUsd: costUsd === void 0 || costBefore === void 0 ? void 0 : costUsd < costBefore ? costUsd : costUsd - costBefore };
|
|
44899
45004
|
} finally {
|
|
44900
45005
|
io.signal?.removeEventListener("abort", cancelled);
|
|
44901
45006
|
}
|
|
@@ -44946,10 +45051,11 @@ function decide(params, tail, events) {
|
|
|
44946
45051
|
if (!no) return { outcome: { outcome: "cancelled" } };
|
|
44947
45052
|
return { outcome: { outcome: "selected", optionId: no.optionId } };
|
|
44948
45053
|
}
|
|
44949
|
-
var PROTOCOL_VERSION, CLIENT_CAPABILITIES,
|
|
45054
|
+
var PROTOCOL_VERSION, CLIENT_CAPABILITIES, RESTARTED, TICKS_PER_USD, STOPPED;
|
|
44950
45055
|
var init_acp = __esm({
|
|
44951
45056
|
"src/lib/agent/wire/acp.ts"() {
|
|
44952
45057
|
"use strict";
|
|
45058
|
+
init_failures();
|
|
44953
45059
|
init_acp_cost();
|
|
44954
45060
|
init_conversation();
|
|
44955
45061
|
init_events();
|
|
@@ -44962,7 +45068,6 @@ var init_acp = __esm({
|
|
|
44962
45068
|
fs: { readTextFile: false, writeTextFile: false },
|
|
44963
45069
|
terminal: false
|
|
44964
45070
|
};
|
|
44965
|
-
INVALID_PARAMS = -32602;
|
|
44966
45071
|
RESTARTED = "[board] that conversation is gone \u2014 the task was restarted in a new session\n";
|
|
44967
45072
|
TICKS_PER_USD = 1e10;
|
|
44968
45073
|
STOPPED = {
|
|
@@ -45198,14 +45303,14 @@ async function oneTurn2(io, options) {
|
|
|
45198
45303
|
if (!done.ok) {
|
|
45199
45304
|
const why2 = done.error ?? "the agent stopped without saying why";
|
|
45200
45305
|
stopped(io, why2);
|
|
45201
|
-
return { ok: false, result, error: why2, usage: usage3, context };
|
|
45306
|
+
return { ok: false, result, error: why2, failure: done.failure, usage: usage3, context };
|
|
45202
45307
|
}
|
|
45203
45308
|
return { ok: true, result, usage: usage3, context };
|
|
45204
45309
|
} catch (e) {
|
|
45205
45310
|
const error62 = e instanceof Error ? e.message : String(e);
|
|
45206
45311
|
const result = tail.end();
|
|
45207
45312
|
stopped(io, error62);
|
|
45208
|
-
return { ok: false, result, error: error62 };
|
|
45313
|
+
return { ok: false, result, error: error62, failure: executionFailure(e) };
|
|
45209
45314
|
} finally {
|
|
45210
45315
|
io.signal?.removeEventListener("abort", cancelled);
|
|
45211
45316
|
}
|
|
@@ -45253,7 +45358,8 @@ function event(envelope2, parts, tail, live, ended) {
|
|
|
45253
45358
|
}
|
|
45254
45359
|
case "turn.failed": {
|
|
45255
45360
|
const error62 = obj2(payload.error);
|
|
45256
|
-
|
|
45361
|
+
const failure2 = providerFailure(error62, str2(error62.message) || "the turn failed");
|
|
45362
|
+
return ended({ ok: false, error: failure2.reason, failure: failure2 });
|
|
45257
45363
|
}
|
|
45258
45364
|
case "session.closed":
|
|
45259
45365
|
return ended({ ok: false, error: str2(payload.reason) || "the agent closed the session" });
|
|
@@ -45270,6 +45376,7 @@ var STOPPED2, MODE, RUNTIME_PREFERENCES, MISSING_KEY;
|
|
|
45270
45376
|
var init_zcode = __esm({
|
|
45271
45377
|
"src/lib/agent/wire/zcode.ts"() {
|
|
45272
45378
|
"use strict";
|
|
45379
|
+
init_failures();
|
|
45273
45380
|
init_usage2();
|
|
45274
45381
|
init_events();
|
|
45275
45382
|
init_json();
|
|
@@ -45293,6 +45400,90 @@ var init_zcode = __esm({
|
|
|
45293
45400
|
}
|
|
45294
45401
|
});
|
|
45295
45402
|
|
|
45403
|
+
// src/lib/agent/idle.ts
|
|
45404
|
+
function createIdleWatchdog(expired, busy = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
|
|
45405
|
+
const calls = /* @__PURE__ */ new Set();
|
|
45406
|
+
const local = /* @__PURE__ */ new Set();
|
|
45407
|
+
const seen = /* @__PURE__ */ new Map();
|
|
45408
|
+
let last = now();
|
|
45409
|
+
let working = false;
|
|
45410
|
+
let closed2 = false;
|
|
45411
|
+
let recoveringAt;
|
|
45412
|
+
let retryUntil = 0;
|
|
45413
|
+
const touch = () => {
|
|
45414
|
+
if (!closed2) {
|
|
45415
|
+
last = now();
|
|
45416
|
+
recoveringAt = void 0;
|
|
45417
|
+
retryUntil = 0;
|
|
45418
|
+
}
|
|
45419
|
+
};
|
|
45420
|
+
const check2 = () => {
|
|
45421
|
+
if (closed2) return;
|
|
45422
|
+
if (retryUntil > now()) return;
|
|
45423
|
+
const active3 = calls.size > 0 || busy();
|
|
45424
|
+
if (active3 || working) last = now();
|
|
45425
|
+
working = active3;
|
|
45426
|
+
if (!active3 && now() - last >= milliseconds) {
|
|
45427
|
+
close();
|
|
45428
|
+
expired();
|
|
45429
|
+
}
|
|
45430
|
+
};
|
|
45431
|
+
const timer = setInterval(check2, Math.min(1e3, milliseconds));
|
|
45432
|
+
timer.unref?.();
|
|
45433
|
+
const close = () => {
|
|
45434
|
+
closed2 = true;
|
|
45435
|
+
clearInterval(timer);
|
|
45436
|
+
calls.clear();
|
|
45437
|
+
local.clear();
|
|
45438
|
+
seen.clear();
|
|
45439
|
+
};
|
|
45440
|
+
return {
|
|
45441
|
+
touch,
|
|
45442
|
+
check: check2,
|
|
45443
|
+
close,
|
|
45444
|
+
event(e) {
|
|
45445
|
+
if (closed2) return;
|
|
45446
|
+
if (e.kind === "status") {
|
|
45447
|
+
if (e.data.state !== "retrying") touch();
|
|
45448
|
+
else {
|
|
45449
|
+
recoveringAt ??= now();
|
|
45450
|
+
retryUntil = Math.min(now() + PROVIDER_RETRY_MS.announcement, recoveringAt + PROVIDER_RETRY_MS.episode);
|
|
45451
|
+
}
|
|
45452
|
+
check2();
|
|
45453
|
+
return;
|
|
45454
|
+
}
|
|
45455
|
+
if (e.kind === "log" || e.kind === "context") return;
|
|
45456
|
+
if (e.kind === "phase" && !e.data.contentAt) return;
|
|
45457
|
+
const key = e.kind === "tool_call" || e.kind === "tool_call_update" ? `${e.kind}:${e.data.toolCallId}` : e.kind;
|
|
45458
|
+
const value = JSON.stringify(e.data);
|
|
45459
|
+
if (seen.get(key) === value) return;
|
|
45460
|
+
seen.set(key, value);
|
|
45461
|
+
if (e.kind === "tool_call" && (e.data.kind === "execute" || e.data.subagent)) local.add(e.data.toolCallId);
|
|
45462
|
+
if (e.kind === "tool_call" || e.kind === "tool_call_update") {
|
|
45463
|
+
const { toolCallId, status } = e.data;
|
|
45464
|
+
if (local.has(toolCallId) && ["in_progress", "running"].includes(status)) calls.add(toolCallId);
|
|
45465
|
+
if (["completed", "failed"].includes(status)) {
|
|
45466
|
+
calls.delete(toolCallId);
|
|
45467
|
+
local.delete(toolCallId);
|
|
45468
|
+
}
|
|
45469
|
+
}
|
|
45470
|
+
touch();
|
|
45471
|
+
check2();
|
|
45472
|
+
}
|
|
45473
|
+
};
|
|
45474
|
+
}
|
|
45475
|
+
var IDLE_MS, IDLE_TIMEOUT, IDLE_ERROR, IDLE_FAILURE, PROVIDER_RETRY_MS;
|
|
45476
|
+
var init_idle = __esm({
|
|
45477
|
+
"src/lib/agent/idle.ts"() {
|
|
45478
|
+
"use strict";
|
|
45479
|
+
IDLE_MS = 5 * 6e4;
|
|
45480
|
+
IDLE_TIMEOUT = { milliseconds: IDLE_MS };
|
|
45481
|
+
IDLE_ERROR = "No response for 5 minutes (idle timeout).";
|
|
45482
|
+
IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
|
|
45483
|
+
PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
|
|
45484
|
+
}
|
|
45485
|
+
});
|
|
45486
|
+
|
|
45296
45487
|
// src/guide/settle-background.md
|
|
45297
45488
|
var settle_background_default;
|
|
45298
45489
|
var init_settle_background = __esm({
|
|
@@ -45502,6 +45693,7 @@ var init_codex_work = __esm({
|
|
|
45502
45693
|
|
|
45503
45694
|
// src/lib/agent/wire/codex.ts
|
|
45504
45695
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
45696
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
45505
45697
|
function createCodexConnection(argv) {
|
|
45506
45698
|
const execAt = argv.indexOf("exec");
|
|
45507
45699
|
if (execAt < 1) return void 0;
|
|
@@ -45554,6 +45746,7 @@ function createCodexClient(options = { images: [] }) {
|
|
|
45554
45746
|
return {
|
|
45555
45747
|
structured: true,
|
|
45556
45748
|
managedProcess: true,
|
|
45749
|
+
idleRecovery: true,
|
|
45557
45750
|
background: () => background,
|
|
45558
45751
|
turn: (io) => run(io, options, (count3) => {
|
|
45559
45752
|
background = count3;
|
|
@@ -45563,11 +45756,26 @@ function createCodexClient(options = { images: [] }) {
|
|
|
45563
45756
|
async function run(io, options, count3) {
|
|
45564
45757
|
const since = Date.now();
|
|
45565
45758
|
const renderer = createCodexStreamRenderer();
|
|
45566
|
-
|
|
45759
|
+
let idling = false;
|
|
45760
|
+
let preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
|
|
45567
45761
|
const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
|
|
45568
45762
|
let submitted = false;
|
|
45569
45763
|
let started = false;
|
|
45570
45764
|
let contentAt = 0;
|
|
45765
|
+
let status;
|
|
45766
|
+
let statusAt = 0;
|
|
45767
|
+
const thinking = () => {
|
|
45768
|
+
if (status !== "thinking" || Date.now() - statusAt >= 1e3) {
|
|
45769
|
+
io.event?.({ kind: "status", data: { state: "thinking", source: "codex" } });
|
|
45770
|
+
statusAt = Date.now();
|
|
45771
|
+
}
|
|
45772
|
+
status = "thinking";
|
|
45773
|
+
};
|
|
45774
|
+
const recovered = () => {
|
|
45775
|
+
if (!status) return;
|
|
45776
|
+
io.event?.({ kind: "status", data: { state: "running", source: "codex" } });
|
|
45777
|
+
status = void 0;
|
|
45778
|
+
};
|
|
45571
45779
|
let startupTimer;
|
|
45572
45780
|
const began = () => {
|
|
45573
45781
|
if (!submitted || started || ended) return;
|
|
@@ -45611,18 +45819,19 @@ async function run(io, options, count3) {
|
|
|
45611
45819
|
io.log(renderer.push(JSON.stringify({ type, ...extra }) + "\n"));
|
|
45612
45820
|
for (const event2 of renderer.events?.() ?? []) io.event?.(event2);
|
|
45613
45821
|
};
|
|
45614
|
-
const end2 = (error62) => {
|
|
45822
|
+
const end2 = (error62, classified) => {
|
|
45615
45823
|
if (ended) return;
|
|
45616
45824
|
ended = true;
|
|
45617
45825
|
clearTimeout(timer);
|
|
45618
45826
|
clearTimeout(startupTimer);
|
|
45619
45827
|
clearTimeout(settleTimer);
|
|
45620
45828
|
io.signal?.removeEventListener("abort", cancelled);
|
|
45829
|
+
io.idleSignal?.removeEventListener("abort", idle);
|
|
45621
45830
|
count3(0);
|
|
45622
45831
|
io.stdout.off("close", closed2);
|
|
45623
45832
|
io.stdin.off("error", inputFailed);
|
|
45624
45833
|
if (settlement) flushMessages(work.work().some((w) => !w.intentionalStop && !["running", "unknown"].includes(w.status) && presented.get(w.id) !== snapshot2(w)));
|
|
45625
|
-
cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status, disposition }) => ({ id: id2, threadId: threadId2, processId, status, disposition }));
|
|
45834
|
+
cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status2, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status2, disposition }));
|
|
45626
45835
|
io.log(renderer.flush());
|
|
45627
45836
|
const usage3 = ownUsage(total, baseline);
|
|
45628
45837
|
const child = childSpend(children, since);
|
|
@@ -45631,15 +45840,16 @@ async function run(io, options, count3) {
|
|
|
45631
45840
|
const costUsd = cost === void 0 ? child.costUsd : cost + (child.costUsd ?? 0);
|
|
45632
45841
|
const failure2 = error62 || (cleanup.status === "unconfirmed" ? cleanup.detail : void 0) || work.work().filter((w) => !w.intentionalStop && ["failed", "interrupted"].includes(w.status)).map((w) => w.result || `Background work ${w.id} ${w.status}.`).join("\n") || void 0;
|
|
45633
45842
|
if (failure2) io.event?.({ kind: "error", data: { text: failure2 } });
|
|
45634
|
-
resolve2({ ok: !failure2, error: failure2, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
|
|
45843
|
+
resolve2({ ok: !failure2, error: failure2, failure: failure2 ? classified ?? { code: "execution_failed", level: 3, reason: failure2 } : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
|
|
45635
45844
|
};
|
|
45636
45845
|
const closed2 = () => {
|
|
45637
|
-
|
|
45638
|
-
|
|
45846
|
+
const reason = "Codex connection closed before all work and results finished.";
|
|
45847
|
+
if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection lost; managed cleanup is unconfirmed.");
|
|
45848
|
+
end2(reason, { code: "connection_lost", level: 2, reason });
|
|
45639
45849
|
};
|
|
45640
45850
|
const inputFailed = (e) => {
|
|
45641
|
-
note("Connection input failed; managed cleanup is unconfirmed.");
|
|
45642
|
-
end2(e.message);
|
|
45851
|
+
if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection input failed; managed cleanup is unconfirmed.");
|
|
45852
|
+
end2(e.message, executionFailure(e));
|
|
45643
45853
|
};
|
|
45644
45854
|
io.stdout.once("close", closed2);
|
|
45645
45855
|
io.stdin.once("error", inputFailed);
|
|
@@ -45651,10 +45861,32 @@ async function run(io, options, count3) {
|
|
|
45651
45861
|
};
|
|
45652
45862
|
const cancelled = () => {
|
|
45653
45863
|
work.freeze();
|
|
45654
|
-
note("Execution stopped; no further cleanup turn was submitted.");
|
|
45864
|
+
if (submitted || threadId) note("Execution stopped; no further cleanup turn was submitted.");
|
|
45655
45865
|
end2("Codex execution stopped.");
|
|
45656
45866
|
};
|
|
45657
45867
|
io.signal?.addEventListener("abort", cancelled, { once: true });
|
|
45868
|
+
const idle = async () => {
|
|
45869
|
+
if (ended || idling) return;
|
|
45870
|
+
idling = true;
|
|
45871
|
+
const unknownWork = () => [...work.entries.values()].some((item2) => ["running", "unknown", "interrupted"].includes(item2.status));
|
|
45872
|
+
const uncertain = unknownWork();
|
|
45873
|
+
const ownedTurn = currentTurn2;
|
|
45874
|
+
try {
|
|
45875
|
+
if (host2.idleRecovery !== true || !threadId || !ownedTurn || !active3 || settlement) throw Error("Codex did not confirm that this turn can be interrupted for recovery.");
|
|
45876
|
+
const receipt = await bounded(
|
|
45877
|
+
rpc.call("wildcrane/stopForRetry", { threadId, turnId: ownedTurn, instance: host2.instance, lease: host2.lease }),
|
|
45878
|
+
CONVERSATION_MS.prepare,
|
|
45879
|
+
"Codex did not confirm stopping the idle turn."
|
|
45880
|
+
);
|
|
45881
|
+
if (receipt.instance !== host2.instance || receipt.lease !== host2.lease || receipt.threadId !== threadId || receipt.turnId !== ownedTurn) throw Error("Codex returned a different turn or owner.");
|
|
45882
|
+
if (uncertain || unknownWork()) throw Error("Codex has operations with unconfirmed results.");
|
|
45883
|
+
cleanup.idleStop = { threadId, turnId: ownedTurn };
|
|
45884
|
+
} catch (error62) {
|
|
45885
|
+
if (!ended) note(error62 instanceof Error ? error62.message : String(error62));
|
|
45886
|
+
}
|
|
45887
|
+
if (!ended) end2(IDLE_FAILURE.reason, IDLE_FAILURE);
|
|
45888
|
+
};
|
|
45889
|
+
io.idleSignal?.addEventListener("abort", idle, { once: true });
|
|
45658
45890
|
const childUpdates = () => {
|
|
45659
45891
|
for (const w of work.entries.values()) {
|
|
45660
45892
|
if (w.kind !== "agent" || childEvents.get(w.id) === w.status) continue;
|
|
@@ -45868,9 +46100,13 @@ async function run(io, options, count3) {
|
|
|
45868
46100
|
childUpdates();
|
|
45869
46101
|
return;
|
|
45870
46102
|
}
|
|
45871
|
-
if (submitted && /\/delta$/.test(msg.method ?? "") && str2(p.delta)) io.activity?.();
|
|
45872
46103
|
const turnId = str2(p.turnId) || str2(obj2(p.turn).id);
|
|
45873
46104
|
if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
|
|
46105
|
+
if (submitted && ["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "") && str2(p.delta)) {
|
|
46106
|
+
if (msg.method?.startsWith("item/reasoning/")) thinking();
|
|
46107
|
+
else recovered();
|
|
46108
|
+
io.activity?.();
|
|
46109
|
+
}
|
|
45874
46110
|
if (msg.method === "turn/started") {
|
|
45875
46111
|
if (!submitted || completedTurns.has(turnId)) return;
|
|
45876
46112
|
currentTurn2 = turnId;
|
|
@@ -45883,7 +46119,10 @@ async function run(io, options, count3) {
|
|
|
45883
46119
|
contentAt = Date.now();
|
|
45884
46120
|
io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
|
|
45885
46121
|
}
|
|
45886
|
-
if (msg.method === "item/started" || msg.method === "item/completed")
|
|
46122
|
+
if (msg.method === "item/started" || msg.method === "item/completed") {
|
|
46123
|
+
recovered();
|
|
46124
|
+
item(obj2(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
|
|
46125
|
+
}
|
|
45887
46126
|
if (msg.method === "thread/tokenUsage/updated") {
|
|
45888
46127
|
if (!submitted) return;
|
|
45889
46128
|
const token2 = obj2(p.tokenUsage);
|
|
@@ -45901,7 +46140,15 @@ async function run(io, options, count3) {
|
|
|
45901
46140
|
context = { used: (Number(last.inputTokens) || 0) + (Number(last.outputTokens) || 0), ...Number(token2.modelContextWindow) > 0 ? { limit: Number(token2.modelContextWindow) } : {} };
|
|
45902
46141
|
io.gotContext?.(context);
|
|
45903
46142
|
}
|
|
45904
|
-
if (msg.method === "error"
|
|
46143
|
+
if (msg.method === "error") {
|
|
46144
|
+
const failure2 = codexFailure(p.error, "Codex failed.");
|
|
46145
|
+
if (p.willRetry === true && submitted && active3 && !idling) {
|
|
46146
|
+
status = "retrying";
|
|
46147
|
+
io.log(`[Codex recovery] ${failure2.code}: ${failure2.reason}
|
|
46148
|
+
`);
|
|
46149
|
+
io.event?.({ kind: "status", data: { state: "retrying", source: "codex", code: failure2.code } });
|
|
46150
|
+
} else if (p.willRetry !== true) end2(failure2.reason, failure2);
|
|
46151
|
+
}
|
|
45905
46152
|
if (msg.method === "turn/completed") {
|
|
45906
46153
|
const turn2 = obj2(p.turn);
|
|
45907
46154
|
const id2 = str2(turn2.id);
|
|
@@ -45911,8 +46158,11 @@ async function run(io, options, count3) {
|
|
|
45911
46158
|
work.observe(threadId, raw);
|
|
45912
46159
|
item(raw, true);
|
|
45913
46160
|
}
|
|
46161
|
+
if (idling) return;
|
|
45914
46162
|
if (turn2.status !== "completed") {
|
|
45915
|
-
|
|
46163
|
+
const reason = str2(obj2(turn2.error).message) || `Codex turn ${str2(turn2.status)}.`;
|
|
46164
|
+
const failure2 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
|
|
46165
|
+
end2(reason, failure2);
|
|
45916
46166
|
return;
|
|
45917
46167
|
}
|
|
45918
46168
|
active3 = false;
|
|
@@ -45929,6 +46179,10 @@ async function run(io, options, count3) {
|
|
|
45929
46179
|
cancelled();
|
|
45930
46180
|
return done;
|
|
45931
46181
|
}
|
|
46182
|
+
if (io.idleSignal?.aborted) {
|
|
46183
|
+
void idle();
|
|
46184
|
+
return done;
|
|
46185
|
+
}
|
|
45932
46186
|
phase("preparing");
|
|
45933
46187
|
const initialized = await bounded(rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), preparingUntil - Date.now(), "Codex initialize timed out.");
|
|
45934
46188
|
host2 = obj2(initialized.wildcrane);
|
|
@@ -45936,17 +46190,31 @@ async function run(io, options, count3) {
|
|
|
45936
46190
|
phase("initialized");
|
|
45937
46191
|
rpc.notify("initialized");
|
|
45938
46192
|
const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
|
|
46193
|
+
const method = `thread/${mode ?? "start"}`;
|
|
46194
|
+
const params = { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} };
|
|
45939
46195
|
let response;
|
|
45940
|
-
|
|
45941
|
-
|
|
45942
|
-
|
|
45943
|
-
|
|
45944
|
-
|
|
46196
|
+
let waiting = false;
|
|
46197
|
+
while (!ended && !response) {
|
|
46198
|
+
try {
|
|
46199
|
+
response = await bounded(rpc.call(method, params), preparingUntil - Date.now(), `Codex ${method} timed out.`);
|
|
46200
|
+
} catch (error62) {
|
|
46201
|
+
const failure2 = error62 instanceof RpcError ? codexFailure(error62.data, error62.message) : void 0;
|
|
46202
|
+
if (mode !== "fork" || failure2?.source !== "harness" || failure2.code !== "codex_source_busy") throw error62;
|
|
46203
|
+
if (!waiting) {
|
|
46204
|
+
waiting = true;
|
|
46205
|
+
io.event?.({ kind: "log", data: { text: failure2.reason } });
|
|
46206
|
+
}
|
|
46207
|
+
io.activity?.();
|
|
46208
|
+
await delay(500, void 0, { signal: io.signal });
|
|
46209
|
+
preparingUntil = Date.now() + CONVERSATION_MS.prepare;
|
|
46210
|
+
}
|
|
45945
46211
|
}
|
|
46212
|
+
if (ended || !response) return done;
|
|
45946
46213
|
const thread = obj2(response.thread);
|
|
45947
46214
|
for (const turn2 of list2(thread.turns)) historicalTurns.add(str2(turn2.id));
|
|
45948
46215
|
threadId = str2(thread.id);
|
|
45949
46216
|
if (!threadId) throw Error("Codex did not return a thread id.");
|
|
46217
|
+
if (mode === "resume" && threadId !== params.threadId) throw Error("Codex did not return the requested session.");
|
|
45950
46218
|
work.root(threadId, list2(response.retainedThreads).map((t) => str2(t.id)));
|
|
45951
46219
|
for (const terminal of list2(response.retainedTerminals)) retained.set(`terminal:${str2(terminal.threadId)}:${str2(terminal.itemId)}`, str2(terminal.processId));
|
|
45952
46220
|
provider = str2(thread.modelProvider) || void 0;
|
|
@@ -45959,7 +46227,8 @@ async function run(io, options, count3) {
|
|
|
45959
46227
|
phase("ready");
|
|
45960
46228
|
await start(io.prompt, options.images);
|
|
45961
46229
|
} catch (e) {
|
|
45962
|
-
|
|
46230
|
+
const failure2 = e instanceof RpcError ? codexFailure(e.data, e.message) : executionFailure(e);
|
|
46231
|
+
end2(failure2.reason, failure2);
|
|
45963
46232
|
}
|
|
45964
46233
|
return done;
|
|
45965
46234
|
}
|
|
@@ -45967,6 +46236,8 @@ var list2;
|
|
|
45967
46236
|
var init_codex = __esm({
|
|
45968
46237
|
"src/lib/agent/wire/codex.ts"() {
|
|
45969
46238
|
"use strict";
|
|
46239
|
+
init_idle();
|
|
46240
|
+
init_failures();
|
|
45970
46241
|
init_conversation();
|
|
45971
46242
|
init_codex_background();
|
|
45972
46243
|
init_codex_work();
|
|
@@ -46016,16 +46287,14 @@ function claudeOnWindows() {
|
|
|
46016
46287
|
])
|
|
46017
46288
|
);
|
|
46018
46289
|
}
|
|
46019
|
-
var
|
|
46290
|
+
var MODEL_ALIASES, readsStdin, userMessage, CLAUDE_CODE;
|
|
46020
46291
|
var init_claude_code = __esm({
|
|
46021
46292
|
"src/lib/agent/harnesses/claude-code.ts"() {
|
|
46022
46293
|
"use strict";
|
|
46023
46294
|
init_locate();
|
|
46024
46295
|
init_wire();
|
|
46025
46296
|
init_models();
|
|
46026
|
-
init_transient();
|
|
46027
46297
|
init_types3();
|
|
46028
|
-
cliSaid = (said2) => /^\s*API Error\b/i.test(said2 ?? "") ? said2 : void 0;
|
|
46029
46298
|
MODEL_ALIASES = ["opus", "sonnet", "haiku", "fable"];
|
|
46030
46299
|
readsStdin = (argv) => argv.includes("--input-format=stream-json") || argv[argv.indexOf("--input-format") + 1] === "stream-json";
|
|
46031
46300
|
userMessage = (prompt) => `${JSON.stringify({ type: "user", message: { role: "user", content: prompt } })}
|
|
@@ -46246,18 +46515,6 @@ var init_claude_code = __esm({
|
|
|
46246
46515
|
reports: ["cost", "tokens", "model", "context"],
|
|
46247
46516
|
// The variable above is the switch: the first 429 exits non-zero and the card is free.
|
|
46248
46517
|
stopsOnRateLimit: true,
|
|
46249
|
-
// A provider that stumbled, in the three ways `claude -p` reports one (#525).
|
|
46250
|
-
//
|
|
46251
|
-
// `failure` is a `result` event marked `is_error`, which the renderer already reads for
|
|
46252
|
-
// its own reason. `offStream` is a line the CLI printed outside its events, and it is how
|
|
46253
|
-
// BOTH failures this board captured arrived — "API Error: Connection dropped
|
|
46254
|
-
// (ECONNRESET)" and "API Error: Connection lost mid-response.": the connection goes and
|
|
46255
|
-
// no `result` event is ever written. `result` is the agent's own last message, read for
|
|
46256
|
-
// the same words in case a future CLI puts them there.
|
|
46257
|
-
//
|
|
46258
|
-
// The last two only behind the `API Error:` prefix the CLI writes them under: everything
|
|
46259
|
-
// else on those two is the agent's prose, and prose quoting an error is not a failure.
|
|
46260
|
-
transient: ({ failure: failure2, result, offStream }) => providerBlip(failure2, cliSaid(offStream), cliSaid(result)),
|
|
46261
46518
|
renderer: createStreamRenderer,
|
|
46262
46519
|
stdinPrompt: (argv) => readsStdin(argv) ? userMessage : void 0,
|
|
46263
46520
|
// `--session-id` above makes Claude Code run under the id we generated, so our key IS
|
|
@@ -46446,7 +46703,6 @@ var init_codex2 = __esm({
|
|
|
46446
46703
|
init_locate();
|
|
46447
46704
|
init_models();
|
|
46448
46705
|
init_worktree();
|
|
46449
|
-
init_transient();
|
|
46450
46706
|
init_types3();
|
|
46451
46707
|
QUIET_CONFIG = ["check_for_update_on_startup=false", "notice.hide_rate_limit_model_nudge=true"];
|
|
46452
46708
|
ARCHES = ["x86_64", "aarch64", "i686", "x64", "arm64", "x86"];
|
|
@@ -46625,7 +46881,6 @@ var init_codex2 = __esm({
|
|
|
46625
46881
|
// failed: its `turn.failed` and `error` events, which the renderer keeps as this run's
|
|
46626
46882
|
// failure (#525). Its final message is not read the way Claude Code's is — Codex puts the
|
|
46627
46883
|
// reason on the stream, so a message that merely mentions one is the agent's prose.
|
|
46628
|
-
transient: ({ failure: failure2 }) => providerBlip(failure2),
|
|
46629
46884
|
// resumeArgs/forkArgs end on the subcommand and the thread id.
|
|
46630
46885
|
renderer: (_cwd, _binary, argv = []) => createCodexStreamRenderer(["resume", "fork"].includes(argv.at(-2) ?? "")),
|
|
46631
46886
|
// Codex re-reads its model list on a timer and traces the attempt to stderr every time,
|
|
@@ -48500,6 +48755,9 @@ function parseStore() {
|
|
|
48500
48755
|
ok: typeof entry.ok === "boolean" ? entry.ok : void 0,
|
|
48501
48756
|
code: entry.code ?? null,
|
|
48502
48757
|
error: typeof entry.error === "string" ? entry.error : void 0,
|
|
48758
|
+
failure: readFailure(entry.failure),
|
|
48759
|
+
validationFailure: readFailure(entry.validationFailure),
|
|
48760
|
+
retryPause: entry.retryPause,
|
|
48503
48761
|
blocker: readBlocker(entry.blocker),
|
|
48504
48762
|
// A run that never reported a cost shows none, rather than a zero it didn't earn.
|
|
48505
48763
|
costUsd: typeof entry.costUsd === "number" && entry.costUsd >= 0 ? entry.costUsd : void 0,
|
|
@@ -48580,7 +48838,7 @@ function readRetry2(raw) {
|
|
|
48580
48838
|
if (!raw || typeof raw !== "object") return void 0;
|
|
48581
48839
|
const r = raw;
|
|
48582
48840
|
const whole2 = Number.isInteger(r.attempt) && r.attempt > 0 && Number.isInteger(r.of) && r.of > 0 && typeof r.reason === "string" && !!r.reason && typeof r.at === "number" && typeof r.since === "number";
|
|
48583
|
-
return whole2 ? { attempt: r.attempt, of: r.of, reason: r.reason, at: r.at, since: r.since } : void 0;
|
|
48841
|
+
return whole2 ? { attempt: r.attempt, of: r.of, reason: r.reason, at: r.at, since: r.since, pending: readRetryPlan(r.pending, r.attempt), launching: r.launching === true || void 0 } : void 0;
|
|
48584
48842
|
}
|
|
48585
48843
|
function readMarks(raw) {
|
|
48586
48844
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
@@ -48865,6 +49123,7 @@ var KEEP_RUNS, KEEP_DELIVERIES, logPathOf, eventsPathOf, WAS_CLARIFY, RETIRED_AC
|
|
|
48865
49123
|
var init_store = __esm({
|
|
48866
49124
|
"src/lib/agent/store.ts"() {
|
|
48867
49125
|
"use strict";
|
|
49126
|
+
init_retry();
|
|
48868
49127
|
init_execution();
|
|
48869
49128
|
init_file_memo();
|
|
48870
49129
|
init_lock();
|
|
@@ -49267,8 +49526,7 @@ function openPlan(plan) {
|
|
|
49267
49526
|
// Read off the argv, so a plan written before the CLI took its turns on stdin still runs.
|
|
49268
49527
|
stdinPrompt: harness.stdinPrompt?.(argv),
|
|
49269
49528
|
quietStderr: harness.quietStderr,
|
|
49270
|
-
images: harness.images
|
|
49271
|
-
transient: harness.transient?.bind(harness)
|
|
49529
|
+
images: harness.images
|
|
49272
49530
|
};
|
|
49273
49531
|
}
|
|
49274
49532
|
function resumesUnder(harnessName) {
|
|
@@ -51625,6 +51883,11 @@ function reap(runs, reaped = [], restore = []) {
|
|
|
51625
51883
|
if (r.status !== "running" || runIsLive(r)) continue;
|
|
51626
51884
|
r.status = r.stopping ? "stopped" : "interrupted";
|
|
51627
51885
|
r.code = null;
|
|
51886
|
+
if (r.status === "stopped" && r.retry) delete r.retry.pending;
|
|
51887
|
+
if (r.retry?.launching) {
|
|
51888
|
+
r.retryPause = "unsafe";
|
|
51889
|
+
r.error = [r.retry.reason, pauseLine("unsafe")].filter(Boolean).join("\n");
|
|
51890
|
+
}
|
|
51628
51891
|
if (r.managedProcess) void stopConnection(r.agentPid ? { pid: r.agentPid, identity: r.agentIdentity } : void 0, 12e3);
|
|
51629
51892
|
else if (r.pid) killMarked(runMark(r.sessionId), r.agentPid && r.agentStartedAt ? { pid: r.agentPid, since: r.agentStartedAt } : void 0);
|
|
51630
51893
|
r.endedAt = now;
|
|
@@ -52104,6 +52367,19 @@ async function openResume(id2, options) {
|
|
|
52104
52367
|
}
|
|
52105
52368
|
const ended = endedDeliveryRefusal(prev);
|
|
52106
52369
|
if (ended) return ended;
|
|
52370
|
+
const automatic = typeof options === "object" && options.automatic === true;
|
|
52371
|
+
const pending = !forced && prev.status !== "stopped" ? prev.retry?.pending : void 0;
|
|
52372
|
+
if (automatic && !pending) return refusal("runContinued", "The automatic retry is no longer pending.");
|
|
52373
|
+
if (pending) {
|
|
52374
|
+
const root2 = prev.agentPid ? { pid: prev.agentPid, since: prev.agentStartedAt ?? prev.startedAt, identity: prev.agentIdentity } : void 0;
|
|
52375
|
+
const stopped2 = prev.managedProcess ? connectionStopped(root2) : processesStopped(runMark(prev.sessionId, prev.agentStartedAt), root2);
|
|
52376
|
+
const session2 = resumeSessionId(prev);
|
|
52377
|
+
if (!stopped2 || !session2 || prev.managedProcess && pending.failure.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session2)) {
|
|
52378
|
+
return retryRefusal(prev, "unsafe");
|
|
52379
|
+
}
|
|
52380
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.max(0, pending.at - Date.now())));
|
|
52381
|
+
if (!await executionHeld(executionOf())) return retryRefusal(prev, "authorization");
|
|
52382
|
+
}
|
|
52107
52383
|
const resuming = prev.deliveryId ? findDelivery(prev.deliveryId) : void 0;
|
|
52108
52384
|
const cwd = deliveryCwd(resuming ?? {});
|
|
52109
52385
|
const sessionId = randomUUID6();
|
|
@@ -52118,7 +52394,7 @@ async function openResume(id2, options) {
|
|
|
52118
52394
|
plan = planResume({ harness: prev.harness, resumeId: session, cwd }, prev.agent, prev.runtime ? { pin: prev.runtime } : {});
|
|
52119
52395
|
} else {
|
|
52120
52396
|
const ask2 = retryAsk(prev) ?? requestOf(prev);
|
|
52121
|
-
const started = await
|
|
52397
|
+
const started = await planRetry2(prev, ask2, sessionId, cwd);
|
|
52122
52398
|
if ("error" in started) return started;
|
|
52123
52399
|
({ plan, fresh } = started);
|
|
52124
52400
|
const restart = prev.action === "spec" ? void 0 : restartPrompt({ ...requestOf(prev), runtime: plan.runtime }, prev.deliveryId);
|
|
@@ -52130,14 +52406,14 @@ async function openResume(id2, options) {
|
|
|
52130
52406
|
return refusal("runForeign", `this version can't continue a conversation ${agent} opened`, { agent });
|
|
52131
52407
|
}
|
|
52132
52408
|
const buildResume = prev.action === "implement" && prev.deliveryId ? resumePrompt(prev.deliveryId, prev.action) : void 0;
|
|
52133
|
-
const opened = await resumeHeld(prev, plan, sessionId, resuming, fresh);
|
|
52409
|
+
const opened = await resumeHeld(prev, plan, sessionId, resuming, fresh, !!pending);
|
|
52134
52410
|
if ("error" in opened) return opened;
|
|
52135
52411
|
if (!opened.spec.prompt && buildResume) opened.spec.prompt = buildResume;
|
|
52136
52412
|
if (build?.notes?.trim()) opened.spec.prompt = [opened.spec.prompt || resumePrompt(prev.deliveryId, prev.action), build.notes.trim()].join("\n\n");
|
|
52137
52413
|
if (build || buildResume) writeSpec(opened.spec);
|
|
52138
52414
|
return opened;
|
|
52139
52415
|
}
|
|
52140
|
-
async function
|
|
52416
|
+
async function planRetry2(prev, ask2, sessionId, cwd) {
|
|
52141
52417
|
const runtime = prev.runtime && runtimeById(prev.runtime) ? prev.runtime : void 0;
|
|
52142
52418
|
const { note, ...plan } = planRun(sessionId, cwd, prev.agent ?? agentForRun(ask2), {
|
|
52143
52419
|
...runtime ? { pin: runtime } : {},
|
|
@@ -52146,7 +52422,16 @@ async function planRetry(prev, ask2, sessionId, cwd) {
|
|
|
52146
52422
|
const { prompt, notes } = buildRun({ ...ask2, title: titleOf(ask2.id), runtime: plan.runtime, pictures: prev.pictures });
|
|
52147
52423
|
return { plan, fresh: { prompt, notes: note ? [...notes, note] : notes, retry: true } };
|
|
52148
52424
|
}
|
|
52149
|
-
|
|
52425
|
+
function retryRefusal(prev, pause2) {
|
|
52426
|
+
const reason = pauseLine(pause2);
|
|
52427
|
+
patch(prev.sessionId, (run3) => {
|
|
52428
|
+
if (run3.retry) delete run3.retry.pending;
|
|
52429
|
+
run3.retryPause = pause2;
|
|
52430
|
+
run3.error = [run3.error ?? run3.retry?.reason, reason].filter(Boolean).join("\n");
|
|
52431
|
+
});
|
|
52432
|
+
return refusal("runContinued", reason);
|
|
52433
|
+
}
|
|
52434
|
+
async function resumeHeld(prev, plan, sessionId, resuming, fresh, automatic = false) {
|
|
52150
52435
|
const retry2 = fresh?.retry === true;
|
|
52151
52436
|
const record2 = {
|
|
52152
52437
|
sessionId,
|
|
@@ -52174,12 +52459,10 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
|
|
|
52174
52459
|
resumedFrom: prev.sessionId,
|
|
52175
52460
|
// Taken now: the run being continued is dropped once this one starts (#1483).
|
|
52176
52461
|
sessionCostFrom: reportsSessionTotal(prev.harness) ? prev.sessionCostUsd ?? prev.sessionCostFrom : void 0,
|
|
52177
|
-
// The retry chain carries on rather than starting over (#525): this run IS the attempt
|
|
52178
|
-
// the failed one scheduled, so its count and its window come with it.
|
|
52179
|
-
retry: prev.retry,
|
|
52180
52462
|
...prev.retry && prev.result ? { result: prev.result } : {}
|
|
52181
52463
|
},
|
|
52182
|
-
|
|
52464
|
+
failure: automatic ? prev.retry?.pending?.failure : void 0,
|
|
52465
|
+
retry: prev.retry ? { ...prev.retry, pending: void 0, launching: automatic ? true : void 0 } : void 0,
|
|
52183
52466
|
logPath: logPathOf(sessionId),
|
|
52184
52467
|
specAgent: prev.specAgent,
|
|
52185
52468
|
...prev.action === "scheduled" ? { studio: prev.studio } : {},
|
|
@@ -52193,6 +52476,9 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
|
|
|
52193
52476
|
const all2 = store.runs;
|
|
52194
52477
|
const latest = all2.find((r) => r.sessionId === prev.sessionId);
|
|
52195
52478
|
if (!latest) return refusal("runContinued", "that run has already been continued");
|
|
52479
|
+
if (automatic && (latest.stopping || latest.status === "stopped" || !latest.retry?.pending)) {
|
|
52480
|
+
return refusal("runContinued", "The automatic retry is no longer pending.");
|
|
52481
|
+
}
|
|
52196
52482
|
if (latest.discardedCards?.some((c) => c.pending || locate(c.id))) {
|
|
52197
52483
|
return refusal("discardUnfinished", "A card discard did not finish. Retry discarding it before resuming creation.");
|
|
52198
52484
|
}
|
|
@@ -52304,6 +52590,12 @@ async function closeRun(sessionId, res) {
|
|
|
52304
52590
|
if (res.ok !== void 0) run3.ok = res.ok;
|
|
52305
52591
|
run3.code = res.code ?? null;
|
|
52306
52592
|
if (res.error) run3.error = res.error;
|
|
52593
|
+
run3.failure = res.failure;
|
|
52594
|
+
run3.retryPause = res.retryPause;
|
|
52595
|
+
if (run3.retry) {
|
|
52596
|
+
delete run3.retry.launching;
|
|
52597
|
+
if (res.status === "stopped") delete run3.retry.pending;
|
|
52598
|
+
}
|
|
52307
52599
|
if (res.note) run3.note = res.note;
|
|
52308
52600
|
if (res.errorWhy?.length) run3.errorWhy = res.errorWhy;
|
|
52309
52601
|
if (res.noteWhy?.length) run3.noteWhy = res.noteWhy;
|
|
@@ -52464,7 +52756,9 @@ var INDEX_ACTIONS, SINGLETON_ACTIONS, VERB, SINGLETON_BUSY, RUN_STATUS, specPath
|
|
|
52464
52756
|
var init_sessions = __esm({
|
|
52465
52757
|
"src/lib/agent/sessions.ts"() {
|
|
52466
52758
|
"use strict";
|
|
52759
|
+
init_codex_background_types();
|
|
52467
52760
|
init_connection_process();
|
|
52761
|
+
init_retry();
|
|
52468
52762
|
init_execution();
|
|
52469
52763
|
init_cards();
|
|
52470
52764
|
init_frontmatter();
|
|
@@ -52761,8 +53055,8 @@ var init_inbox = __esm({
|
|
|
52761
53055
|
META_LINE = /^\s+("(?:[^"\\]|\\.)*"|[^:]+):\s*(.*)$/;
|
|
52762
53056
|
slugOf = (said2) => said2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56).replace(/-+$/, "");
|
|
52763
53057
|
fileName = (title, slug = "") => `${slugOf(slug) || slugOf(title) || "item"}.md`;
|
|
52764
|
-
readArchived = () => readFolder(
|
|
52765
|
-
readAllDismissed = () => readFolder(
|
|
53058
|
+
readArchived = (dir = SIGNALS_ARCHIVED) => readFolder(dir);
|
|
53059
|
+
readAllDismissed = (dir = SIGNALS_DISMISSED) => readFolder(dir, true);
|
|
52766
53060
|
}
|
|
52767
53061
|
});
|
|
52768
53062
|
|
|
@@ -55392,13 +55686,20 @@ function cmdValidate(id2) {
|
|
|
55392
55686
|
const cards = [...snapshotSpecs()].filter(([, card]) => id2 === void 0 || card.id === id2);
|
|
55393
55687
|
if (id2 !== void 0 && !cards.length) die(`no task with id ${id2}`, { kind: "card-not-found", id: id2 });
|
|
55394
55688
|
const errors = cards.flatMap(([file2, card]) => validateSpec(file2, card.text, card.id));
|
|
55395
|
-
|
|
55689
|
+
const reason = errors.length ? formatContractErrors(errors) : void 0;
|
|
55690
|
+
const session = insideRun();
|
|
55691
|
+
if (session) patch(session, (run3) => {
|
|
55692
|
+
run3.validationFailure = reason ? { code: "validation_failed", level: 1, source: "validation", reason } : void 0;
|
|
55693
|
+
});
|
|
55694
|
+
if (reason) die(reason, { kind: "spec-contract", errors });
|
|
55396
55695
|
say(`Spec format valid (${cards.length} card${cards.length === 1 ? "" : "s"}).`);
|
|
55397
55696
|
return { valid: true, checked: cards.length, errors: [] };
|
|
55398
55697
|
}
|
|
55399
55698
|
var init_validate2 = __esm({
|
|
55400
55699
|
"src/commands/validate.ts"() {
|
|
55401
55700
|
"use strict";
|
|
55701
|
+
init_env();
|
|
55702
|
+
init_sessions();
|
|
55402
55703
|
init_io();
|
|
55403
55704
|
init_paths();
|
|
55404
55705
|
init_spec_contract();
|
|
@@ -61418,7 +61719,7 @@ var init_reply_log = __esm({
|
|
|
61418
61719
|
});
|
|
61419
61720
|
|
|
61420
61721
|
// src/commands/task-chat.ts
|
|
61421
|
-
import { setTimeout as
|
|
61722
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
61422
61723
|
function validateChatOptions(message, opts) {
|
|
61423
61724
|
if (opts.limit !== void 0 && opts.all || message.length && (opts.limit !== void 0 || opts.all || opts.follow || opts.stop) || opts.stop && (opts.limit !== void 0 || opts.all || opts.follow)) {
|
|
61424
61725
|
throw new BoardError("Use a message, history options [--limit <n> | --all] [--follow], or --stop separately.", { kind: "bad-args" });
|
|
@@ -61554,7 +61855,7 @@ async function taskChatFollow(id2, opts) {
|
|
|
61554
61855
|
if (!active2(reply)) {
|
|
61555
61856
|
break;
|
|
61556
61857
|
}
|
|
61557
|
-
await
|
|
61858
|
+
await delay2(1e3, void 0, { signal: controller.signal });
|
|
61558
61859
|
}
|
|
61559
61860
|
} else {
|
|
61560
61861
|
body = first.chat.messages.at(-1)?.role === "agent" ? first.chat.messages.at(-1).body : null;
|
|
@@ -61652,7 +61953,7 @@ var init_describe_project = __esm({
|
|
|
61652
61953
|
var discuss_goal_default;
|
|
61653
61954
|
var init_discuss_goal = __esm({
|
|
61654
61955
|
"src/guide/discuss-goal.md"() {
|
|
61655
|
-
discuss_goal_default = "# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately with a title, outcome (at most 150 words), and verifiable `## Done when` criteria. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user's choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope. Its Preview IDs name outputs, not agents.\n- **Review**: save `--review-file <json>`
|
|
61956
|
+
discuss_goal_default = "# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately with a title, outcome (at most 150 words), and verifiable `## Done when` criteria. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user's choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope. Its Preview IDs name outputs, not agents.\n- **Review**: before saving a Goal, choose the human review points and save them with the Goal using `--review-file <json>` (`{id,after?,previews?}`). Use the Studio\u2019s Preview IDs, stable node IDs and `after` for dependencies. Require approval only where downstream work needs it.\n- **Review state**: save `[]` when no extra review is needed and `null` only while a decision is missing. Keep the saved arrangement when editing other details.\n- **Decisions**: explain the proposed outcome and review arrangement before saving. Ask only for choices the user must make, with a recommendation.\n- **Start**: the user starts each Goal from the page; starting accepts its arrangement, never skips its review gates. Changing the arrangement after starting requires plan confirmation.\n- **Communication**: the remote user sees tasks and previews. Use plain words and button labels, omitting internal paths, commands and tools.\n";
|
|
61656
61957
|
}
|
|
61657
61958
|
});
|
|
61658
61959
|
|
|
@@ -61708,7 +62009,7 @@ var init_review_rejections = __esm({
|
|
|
61708
62009
|
var refine_default;
|
|
61709
62010
|
var init_refine = __esm({
|
|
61710
62011
|
"src/guide/refine.md"() {
|
|
61711
|
-
refine_default = '# Refine a card\n\nPlan one card until it is buildable.\n\n- **Unchecked cards**: check cards with `triage:` and empty `## Scope` against the project, rejecting obsolete or completed work with `akb raw reject <id> --reason "<evidence>"` and stopping.\n- **Other obsolete or completed cards**: ask whether to discard, run no previews, and stop.\n- **Groups**: preserve subtask coverage and progress, fill gaps without duplication, and do not mark the parent ready merely because its split is complete.\n- **Verification**: plan representative checks for the outcome, project rules and material risks, confirm prerequisites, and keep optional coverage optional.\n- **Review**: read `akb task review <id>`. If the arrangement is undecided, propose it with `--file <json> --revision <n>` and wait for confirmation. Work only on dispatched, unlocked nodes; keep independent work moving while other nodes await review.\n- **Previews**: prepare only the unlocked nodes\u2019 outputs per the Studio\u2019s `<Preview>` blocks. Before revising an approved output, use `--revise-from <stage> --revision <n>`; preserve unrelated outputs and approvals.\n- **Submit**: synchronize body and assets, then report `--stage <id> --status done --revision <n>`. Re-read after conflicts; never treat submission, question answers or plan confirmation as product approval.\n- **References**: rewrite mentions of cards no longer on the board.\n- **Decisions**: settle choices supported by evidence and ask only as `akb guide update-questions` allows.\n- **Card**: follow studio rules and `akb guide writing`, fixing all errors from `akb raw validate <id>`.\n- **Ready**: when validated and buildable with prerequisites settled, run `akb raw update <id> --status ready`; otherwise leave blockers as open questions.\n\nFollow the printed closing steps. Wait only for required approvals; completion still requires Studio delivery checks.\n';
|
|
62012
|
+
refine_default = '# Refine a card\n\nPlan one card until it is buildable.\n\n- **Unchecked cards**: check cards with `triage:` and empty `## Scope` against the project, rejecting obsolete or completed work with `akb raw reject <id> --reason "<evidence>"` and stopping.\n- **Other obsolete or completed cards**: ask whether to discard, run no previews, and stop.\n- **Groups**: preserve subtask coverage and progress, fill gaps without duplication, and do not mark the parent ready merely because its split is complete.\n- **Verification**: plan representative checks for the outcome, project rules and material risks, confirm prerequisites, and keep optional coverage optional.\n- **Review**: read `akb task review <id>`. If the arrangement is undecided, propose it with `--file <json> --revision <n>` and wait for confirmation. Work only on dispatched, unlocked nodes; keep independent work moving while other nodes await review.\n- **Previews**: prepare only the unlocked nodes\u2019 outputs per the Studio\u2019s `<Preview>` blocks. Before revising an approved output, use `--revise-from <stage> --revision <n>`; preserve unrelated outputs and approvals.\n- **Submit**: synchronize body and assets, then report `--stage <id> --status done --revision <n>`. Re-read after conflicts; never treat submission, question answers or plan confirmation as product approval.\n- **Delivery handoff**: for Studios with separate delivery, finish the review plan with a handoff; implementation and its checks run in delivery.\n- **References**: rewrite mentions of cards no longer on the board.\n- **Decisions**: settle choices supported by evidence and ask only as `akb guide update-questions` allows.\n- **Card**: follow studio rules and `akb guide writing`, fixing all errors from `akb raw validate <id>`.\n- **Ready**: when validated and buildable with prerequisites settled, run `akb raw update <id> --status ready`; otherwise leave blockers as open questions.\n\nFollow the printed closing steps. Wait only for required approvals; completion still requires Studio delivery checks.\n';
|
|
61712
62013
|
}
|
|
61713
62014
|
});
|
|
61714
62015
|
|
|
@@ -62504,7 +62805,8 @@ var init_memory_review = __esm({
|
|
|
62504
62805
|
import fs77 from "node:fs";
|
|
62505
62806
|
import path78 from "node:path";
|
|
62506
62807
|
function rejectionsToReview() {
|
|
62507
|
-
const
|
|
62808
|
+
const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
|
|
62809
|
+
const dir = path78.join(scratch ? path78.join(scratch, ".archive") : ARCHIVE, REJECTIONS_TO_REVIEW);
|
|
62508
62810
|
if (!fs77.existsSync(dir)) return [];
|
|
62509
62811
|
const found2 = [];
|
|
62510
62812
|
for (const file2 of walkMd(dir)) {
|
|
@@ -62521,7 +62823,7 @@ function rejectionsToReview() {
|
|
|
62521
62823
|
return found2.sort((a, b) => a.rejectedAt.localeCompare(b.rejectedAt) || a.id - b.id);
|
|
62522
62824
|
}
|
|
62523
62825
|
function dismissalsToReview() {
|
|
62524
|
-
return
|
|
62826
|
+
return reviewDismissed().filter((s) => s.dismissedBy === "user" && s.dismissedReason.trim()).sort((a, b) => a.dismissedAt.localeCompare(b.dismissedAt)).map((s) => ({
|
|
62525
62827
|
sourceId: s.sourceId,
|
|
62526
62828
|
title: s.title,
|
|
62527
62829
|
file: s.relPath,
|
|
@@ -62547,11 +62849,12 @@ function withdrawnSources() {
|
|
|
62547
62849
|
}
|
|
62548
62850
|
}))];
|
|
62549
62851
|
if (cited.length === 0) return [];
|
|
62550
|
-
const
|
|
62551
|
-
const
|
|
62852
|
+
const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
|
|
62853
|
+
const dismissed = new Set(reviewDismissed().map((s) => s.sourceId));
|
|
62854
|
+
const restored = new Set([...readInbox(), ...readArchived(scratch ? path78.join(scratch, "triage", "archived") : void 0)].map((s) => s.sourceId));
|
|
62552
62855
|
return cited.filter((id2) => restored.has(id2) && !dismissed.has(id2));
|
|
62553
62856
|
}
|
|
62554
|
-
var SOURCES;
|
|
62857
|
+
var reviewDismissed, SOURCES;
|
|
62555
62858
|
var init_dismissal_review = __esm({
|
|
62556
62859
|
"src/lib/agent/dismissal-review.ts"() {
|
|
62557
62860
|
"use strict";
|
|
@@ -62561,6 +62864,10 @@ var init_dismissal_review = __esm({
|
|
|
62561
62864
|
init_paths();
|
|
62562
62865
|
init_inbox();
|
|
62563
62866
|
init_archive();
|
|
62867
|
+
reviewDismissed = () => {
|
|
62868
|
+
const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
|
|
62869
|
+
return readAllDismissed(scratch ? path78.join(scratch, "triage", "dismissed") : void 0);
|
|
62870
|
+
};
|
|
62564
62871
|
SOURCES = /\(([^()]+)\)\s*$/;
|
|
62565
62872
|
}
|
|
62566
62873
|
});
|
|
@@ -63131,7 +63438,11 @@ function refinementStep(card) {
|
|
|
63131
63438
|
function refinementRequest(req) {
|
|
63132
63439
|
const card = req.id === void 0 ? null : currentCard(req.id);
|
|
63133
63440
|
if (!card) return { error: `task #${req.id} does not exist` };
|
|
63134
|
-
const
|
|
63441
|
+
const context = process.env.AI4KANBAN_TASK_REVIEW;
|
|
63442
|
+
const review = context ? JSON.parse(context) : void 0;
|
|
63443
|
+
const assigned = process.env.AI4KANBAN_REVIEW_STAGES ? JSON.parse(process.env.AI4KANBAN_REVIEW_STAGES) : void 0;
|
|
63444
|
+
const authorized = review && !review.pending_plan && (review.plan === null || review.stages.some((s) => ["available", "running"].includes(s.status) && (!assigned || assigned.includes(s.id))));
|
|
63445
|
+
const step = review ? authorized && !card.questions.some((q) => q.options?.length) ? "clarify" : "done" : refinementStep(card);
|
|
63135
63446
|
if (step === "done") {
|
|
63136
63447
|
const waiting = card.questions.length > 0 && canRefine({ ...card, questions: [] });
|
|
63137
63448
|
return {
|
|
@@ -63317,99 +63628,6 @@ var init_propose = __esm({
|
|
|
63317
63628
|
}
|
|
63318
63629
|
});
|
|
63319
63630
|
|
|
63320
|
-
// src/lib/agent/idle.ts
|
|
63321
|
-
function createIdleWatchdog(expired, busy = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
|
|
63322
|
-
const calls = /* @__PURE__ */ new Set();
|
|
63323
|
-
const local = /* @__PURE__ */ new Set();
|
|
63324
|
-
const seen = /* @__PURE__ */ new Map();
|
|
63325
|
-
let last = now();
|
|
63326
|
-
let working = false;
|
|
63327
|
-
let closed2 = false;
|
|
63328
|
-
const touch = () => {
|
|
63329
|
-
if (!closed2) last = now();
|
|
63330
|
-
};
|
|
63331
|
-
const check2 = () => {
|
|
63332
|
-
if (closed2) return;
|
|
63333
|
-
const active3 = calls.size > 0 || busy();
|
|
63334
|
-
if (active3 || working) last = now();
|
|
63335
|
-
working = active3;
|
|
63336
|
-
if (!active3 && now() - last >= milliseconds) {
|
|
63337
|
-
close();
|
|
63338
|
-
expired();
|
|
63339
|
-
}
|
|
63340
|
-
};
|
|
63341
|
-
const timer = setInterval(check2, Math.min(1e3, milliseconds));
|
|
63342
|
-
timer.unref?.();
|
|
63343
|
-
const close = () => {
|
|
63344
|
-
closed2 = true;
|
|
63345
|
-
clearInterval(timer);
|
|
63346
|
-
calls.clear();
|
|
63347
|
-
local.clear();
|
|
63348
|
-
seen.clear();
|
|
63349
|
-
};
|
|
63350
|
-
return {
|
|
63351
|
-
touch,
|
|
63352
|
-
check: check2,
|
|
63353
|
-
close,
|
|
63354
|
-
event(e) {
|
|
63355
|
-
if (closed2 || e.kind === "log" || e.kind === "context") return;
|
|
63356
|
-
if (e.kind === "phase" && !e.data.contentAt) return;
|
|
63357
|
-
const key = e.kind === "tool_call" || e.kind === "tool_call_update" ? `${e.kind}:${e.data.toolCallId}` : e.kind;
|
|
63358
|
-
const value = JSON.stringify(e.data);
|
|
63359
|
-
if (seen.get(key) === value) return;
|
|
63360
|
-
seen.set(key, value);
|
|
63361
|
-
if (e.kind === "tool_call" && (e.data.kind === "execute" || e.data.subagent)) local.add(e.data.toolCallId);
|
|
63362
|
-
if (e.kind === "tool_call" || e.kind === "tool_call_update") {
|
|
63363
|
-
const { toolCallId, status } = e.data;
|
|
63364
|
-
if (local.has(toolCallId) && ["in_progress", "running"].includes(status)) calls.add(toolCallId);
|
|
63365
|
-
if (["completed", "failed"].includes(status)) {
|
|
63366
|
-
calls.delete(toolCallId);
|
|
63367
|
-
local.delete(toolCallId);
|
|
63368
|
-
}
|
|
63369
|
-
}
|
|
63370
|
-
touch();
|
|
63371
|
-
check2();
|
|
63372
|
-
}
|
|
63373
|
-
};
|
|
63374
|
-
}
|
|
63375
|
-
var IDLE_MS, IDLE_TIMEOUT;
|
|
63376
|
-
var init_idle = __esm({
|
|
63377
|
-
"src/lib/agent/idle.ts"() {
|
|
63378
|
-
"use strict";
|
|
63379
|
-
IDLE_MS = 5 * 6e4;
|
|
63380
|
-
IDLE_TIMEOUT = { milliseconds: IDLE_MS };
|
|
63381
|
-
}
|
|
63382
|
-
});
|
|
63383
|
-
|
|
63384
|
-
// src/lib/agent/retry.ts
|
|
63385
|
-
function backoffMs(attempt2, random = Math.random) {
|
|
63386
|
-
const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt2 - 2));
|
|
63387
|
-
return Math.round(step * (1 - JITTER * random()));
|
|
63388
|
-
}
|
|
63389
|
-
function planRetry2(prev, failure2, startedAt, now = Date.now(), random = Math.random) {
|
|
63390
|
-
const attempt2 = (prev?.attempt ?? 1) + 1;
|
|
63391
|
-
if (attempt2 > RETRY_ATTEMPTS) return null;
|
|
63392
|
-
const since = prev?.since ?? startedAt;
|
|
63393
|
-
const wait = failure2.retryAfterMs ?? backoffMs(attempt2, random);
|
|
63394
|
-
const at = now + wait;
|
|
63395
|
-
if (wait > CAP_MS || wait < 0 || !Number.isFinite(wait)) return null;
|
|
63396
|
-
return { attempt: attempt2, of: RETRY_ATTEMPTS, reason: failure2.reason, at, since };
|
|
63397
|
-
}
|
|
63398
|
-
function retryLine(retry2, now = Date.now()) {
|
|
63399
|
-
const seconds = Math.max(1, Math.round((retry2.at - now) / 1e3));
|
|
63400
|
-
return `${retry2.reason} \u2014 this run tries again in ${seconds}s (attempt ${retry2.attempt} of ${retry2.of}).`;
|
|
63401
|
-
}
|
|
63402
|
-
var RETRY_ATTEMPTS, BASE_MS, CAP_MS, JITTER;
|
|
63403
|
-
var init_retry = __esm({
|
|
63404
|
-
"src/lib/agent/retry.ts"() {
|
|
63405
|
-
"use strict";
|
|
63406
|
-
RETRY_ATTEMPTS = 2;
|
|
63407
|
-
BASE_MS = 15e3;
|
|
63408
|
-
CAP_MS = 12e4;
|
|
63409
|
-
JITTER = 0.25;
|
|
63410
|
-
}
|
|
63411
|
-
});
|
|
63412
|
-
|
|
63413
63631
|
// src/lib/agent/watch.ts
|
|
63414
63632
|
var watch_exports = {};
|
|
63415
63633
|
__export(watch_exports, {
|
|
@@ -63417,7 +63635,7 @@ __export(watch_exports, {
|
|
|
63417
63635
|
});
|
|
63418
63636
|
import { spawn as spawn3 } from "node:child_process";
|
|
63419
63637
|
import fs79 from "node:fs";
|
|
63420
|
-
async function watchRun(sessionId, resume = startResume) {
|
|
63638
|
+
async function watchRun(sessionId, resume = startResume, retryBackoff = backoffMs) {
|
|
63421
63639
|
const spec = readSpec(sessionId);
|
|
63422
63640
|
const run3 = peekRun(sessionId);
|
|
63423
63641
|
if (!run3 || !spec) {
|
|
@@ -63487,7 +63705,7 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63487
63705
|
const basePrompt = record2.resumedFrom ? spec.prompt || resumePrompt(record2.deliveryId, record2.action) : spec.prompt;
|
|
63488
63706
|
const recoveryPrompt = record2.harness === "antigravity" && record2.resumedFrom ? "First verify existing progress and operation results. Preserve user decisions and completed work; do not repeat completed operations. Check actual state before continuing any operation whose result is uncertain." : "";
|
|
63489
63707
|
const boundary = process.env.AI4KANBAN_TASK_REVIEW ? reviewBoundary(JSON.parse(process.env.AI4KANBAN_TASK_REVIEW), process.env.AI4KANBAN_REVIEW_STAGES ? JSON.parse(process.env.AI4KANBAN_REVIEW_STAGES) : void 0) : "";
|
|
63490
|
-
const prompt = [record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, recoveryPrompt, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
|
|
63708
|
+
const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, recoveryPrompt, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
|
|
63491
63709
|
const before = markBoard();
|
|
63492
63710
|
const takes = active3.images;
|
|
63493
63711
|
active3.renderer?.setRequiredImages?.(record2.pictures ?? []);
|
|
@@ -63498,11 +63716,23 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63498
63716
|
void refreshCatalog();
|
|
63499
63717
|
const client = active3.client;
|
|
63500
63718
|
if (active3.harness === "codex" && !client) log.write("[Codex] Custom command preserved; managed background cleanup is unavailable for this command shape.\n");
|
|
63501
|
-
const restartBase = !client || record2.cardId !== null ? void 0 : record2.resumedFrom ? restartPrompt(requestOf(record2), record2.deliveryId) : record2.continues && !record2.continues.fork ? spec.prompt : void 0;
|
|
63719
|
+
const restartBase = !client || record2.cardId !== null || record2.retry?.launching ? void 0 : record2.resumedFrom ? restartPrompt(requestOf(record2), record2.deliveryId) : record2.continues && !record2.continues.fork ? spec.prompt : void 0;
|
|
63502
63720
|
const restart = restartBase ? [restartBase, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n") : void 0;
|
|
63503
63721
|
const stdinPrompt = client ? void 0 : active3.stdinPrompt;
|
|
63504
63722
|
const stdio = [client || stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"];
|
|
63505
63723
|
let child;
|
|
63724
|
+
if (record2.retry?.launching && !await executionHeld(executionOf())) {
|
|
63725
|
+
log.end();
|
|
63726
|
+
await closeRun(sessionId, { status: "error", code: null, error: joinNotes(record2.retry.reason, pauseLine("authorization")), retryPause: "authorization", failure: record2.failure });
|
|
63727
|
+
letGo();
|
|
63728
|
+
return 1;
|
|
63729
|
+
}
|
|
63730
|
+
if (record2.retry?.launching && peekRun(sessionId)?.stopping) {
|
|
63731
|
+
log.end();
|
|
63732
|
+
await closeRun(sessionId, { status: "stopped", code: null });
|
|
63733
|
+
letGo();
|
|
63734
|
+
return 1;
|
|
63735
|
+
}
|
|
63506
63736
|
try {
|
|
63507
63737
|
const start = spawnable(cmd, client || stdinPrompt ? args2 : [...args2, prompt], {
|
|
63508
63738
|
// Where this run works: the project, or — inside a delivery with a worktree of its
|
|
@@ -63526,13 +63756,17 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63526
63756
|
patch(sessionId, (r) => {
|
|
63527
63757
|
r.unspawned = true;
|
|
63528
63758
|
});
|
|
63529
|
-
await closeRun(sessionId, { status: "error", ok: false, code: null, error: String(e) });
|
|
63759
|
+
await closeRun(sessionId, { status: "error", ok: false, code: null, error: String(e), failure: executionFailure(e) });
|
|
63530
63760
|
letGo();
|
|
63531
63761
|
return 1;
|
|
63532
63762
|
}
|
|
63533
63763
|
const agentStartedAt = Date.now();
|
|
63534
63764
|
if (child.pid) {
|
|
63535
63765
|
patch(sessionId, (r) => {
|
|
63766
|
+
if (r.retry?.launching) {
|
|
63767
|
+
r.retry.attempt++;
|
|
63768
|
+
delete r.retry.launching;
|
|
63769
|
+
}
|
|
63536
63770
|
r.agentPid = child.pid;
|
|
63537
63771
|
r.agentStartedAt = agentStartedAt;
|
|
63538
63772
|
r.managedProcess = client?.managedProcess;
|
|
@@ -63595,7 +63829,7 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63595
63829
|
let touch = () => {
|
|
63596
63830
|
};
|
|
63597
63831
|
let activityVersion = 0;
|
|
63598
|
-
let
|
|
63832
|
+
let endTerminal = () => {
|
|
63599
63833
|
};
|
|
63600
63834
|
child.stdout.on("data", (d) => {
|
|
63601
63835
|
if (renderer) {
|
|
@@ -63605,7 +63839,7 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63605
63839
|
gotModel(renderer.model?.());
|
|
63606
63840
|
gotContext(renderer.context?.());
|
|
63607
63841
|
afterTurn();
|
|
63608
|
-
if (renderer.
|
|
63842
|
+
if (renderer.terminalFailure?.()) endTerminal();
|
|
63609
63843
|
}
|
|
63610
63844
|
const version2 = renderer?.activity?.() ?? 0;
|
|
63611
63845
|
if (version2 !== activityVersion) {
|
|
@@ -63616,13 +63850,14 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63616
63850
|
const errs = createStderrFilter(active3.quietStderr);
|
|
63617
63851
|
child.stderr.on("data", (d) => {
|
|
63618
63852
|
renderer?.stderr?.(d.toString());
|
|
63619
|
-
if (renderer?.rateLimit?.()) endLimited();
|
|
63620
63853
|
const text5 = errs.push(d.toString());
|
|
63621
63854
|
if (text5) log.write(text5);
|
|
63622
63855
|
});
|
|
63623
63856
|
let spawnError;
|
|
63857
|
+
let spawnFailure;
|
|
63624
63858
|
let spawnWhy;
|
|
63625
63859
|
child.on("error", (err) => {
|
|
63860
|
+
spawnFailure = executionFailure(err);
|
|
63626
63861
|
const missing = err?.code === "ENOENT";
|
|
63627
63862
|
spawnError = missing ? `${cmd} isn't installed, or isn't on this run's PATH. Install it with: ${active3.install}` : String(err);
|
|
63628
63863
|
spawnWhy = missing ? { kind: "notInstalled", args: { cmd, install: active3.install } } : void 0;
|
|
@@ -63638,6 +63873,7 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63638
63873
|
let done = false;
|
|
63639
63874
|
let spoken;
|
|
63640
63875
|
let silent = false;
|
|
63876
|
+
let uncertainAtIdle = false;
|
|
63641
63877
|
let watchdog;
|
|
63642
63878
|
let wakeUp;
|
|
63643
63879
|
const sleep4 = (ms) => new Promise((wake) => {
|
|
@@ -63680,41 +63916,45 @@ async function watchRun(sessionId, resume = startResume) {
|
|
|
63680
63916
|
if (errRest) log.write(errRest);
|
|
63681
63917
|
const endedAt = Date.now();
|
|
63682
63918
|
const blocker = peekRun(sessionId)?.blocker;
|
|
63683
|
-
let failure2 = renderer?.failure?.() ?? (!taskCompleted && renderer?.background?.() ? "The agent exited with unfinished background tasks." : void 0);
|
|
63684
|
-
if (!asked && pendingOperations.size > 0 && (code !== 0 || spoken?.ok === false || renderer?.failure?.())) {
|
|
63685
|
-
failure2 = `${failure2 ?? spoken?.error ?? "Agent exited."} Operation results are unconfirmed; automatic recovery was skipped.`;
|
|
63686
|
-
}
|
|
63687
|
-
const unfinished = blocker || failure2;
|
|
63688
|
-
const result = spoken ? spoken.result : renderer?.result();
|
|
63689
63919
|
const held4 = peekRun(sessionId) ?? record2;
|
|
63690
|
-
const
|
|
63691
|
-
const said2 =
|
|
63692
|
-
const
|
|
63693
|
-
const
|
|
63694
|
-
|
|
63695
|
-
|
|
63696
|
-
|
|
63697
|
-
|
|
63698
|
-
const
|
|
63699
|
-
|
|
63700
|
-
if (
|
|
63701
|
-
|
|
63702
|
-
|
|
63703
|
-
|
|
63704
|
-
|
|
63705
|
-
|
|
63706
|
-
|
|
63707
|
-
|
|
63708
|
-
|
|
63920
|
+
const rendered = renderer?.failure?.() ?? (!taskCompleted && renderer?.background?.() ? "The agent exited with unfinished background tasks." : void 0);
|
|
63921
|
+
const said2 = spawnError ?? (silent ? silenceSaid(silenceFor) : spoken?.error ?? rendered);
|
|
63922
|
+
const failed2 = code !== 0 || spoken?.ok === false || !!rendered || silent || !!blocker;
|
|
63923
|
+
const failure2 = failed2 && !asked ? silent ? { ...IDLE_FAILURE, reason: said2 ?? IDLE_FAILURE.reason } : spawnFailure ?? spoken?.failure ?? renderer?.executionFailure?.() ?? (!blocker ? held4.validationFailure : void 0) ?? { code: blocker ? "execution_blocked" : "execution_failed", level: 3, reason: said2 ?? blocker?.cause ?? `Agent exited with code ${code}.` } : void 0;
|
|
63924
|
+
const result = spoken ? spoken.result : renderer?.result();
|
|
63925
|
+
let retryPause;
|
|
63926
|
+
let retrying = false;
|
|
63927
|
+
if (failure2 && !sub && !taskCompleted) {
|
|
63928
|
+
const attempt2 = held4.retry?.attempt ?? 1;
|
|
63929
|
+
const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff);
|
|
63930
|
+
if ("pause" in decision) retryPause = decision.pause;
|
|
63931
|
+
else if (blocker || pendingOperations.size || !structured || !resumeSessionId(held4) || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, resumeSessionId(held4)))) retryPause = "unsafe";
|
|
63932
|
+
else {
|
|
63933
|
+
const mark = runMark(sessionId, agentStartedAt);
|
|
63934
|
+
const root2 = child.pid ? { pid: child.pid, since: agentStartedAt, identity: held4.agentIdentity } : void 0;
|
|
63935
|
+
const stopped3 = () => client?.managedProcess ? connectionStopped(root2) : processesStopped(mark, root2);
|
|
63936
|
+
const until = Date.now() + STOP_GRACE_MS + STOP_CLOSE_MS;
|
|
63937
|
+
while (!stopped3() && Date.now() < until) await sleep4(100);
|
|
63938
|
+
if (!stopped3()) retryPause = "unsafe";
|
|
63939
|
+
else {
|
|
63940
|
+
const pending = decision.plan;
|
|
63941
|
+
patch(sessionId, (r) => {
|
|
63942
|
+
r.failure = failure2;
|
|
63943
|
+
r.error = said2 ?? failure2.reason;
|
|
63944
|
+
r.retry = { attempt: attempt2, of: pending.of, reason: failure2.reason, at: pending.at, since: held4.retry?.since ?? held4.startedAt, pending };
|
|
63945
|
+
});
|
|
63946
|
+
log.write(`
|
|
63947
|
+
[board] ${retryLine(pending, attempt2)}
|
|
63709
63948
|
`);
|
|
63710
|
-
|
|
63711
|
-
|
|
63712
|
-
|
|
63713
|
-
|
|
63714
|
-
if (stopped2 || peekRun(sessionId)?.stopping === true) asked = true;
|
|
63949
|
+
if (!stoppedByUser()) await sleep4(Math.max(0, pending.at - Date.now()));
|
|
63950
|
+
retrying = true;
|
|
63951
|
+
}
|
|
63952
|
+
}
|
|
63715
63953
|
}
|
|
63716
|
-
|
|
63717
|
-
|
|
63954
|
+
asked ||= stoppedByUser();
|
|
63955
|
+
retrying &&= !asked;
|
|
63956
|
+
const error62 = asked ? void 0 : joinNotes(said2 ?? failure2?.reason, retryPause && failure2?.source !== "invariant" ? pauseLine(retryPause) : void 0);
|
|
63957
|
+
const status = asked ? "stopped" : failed2 || code !== 0 ? "error" : "done";
|
|
63718
63958
|
const reported = spoken ? spoken.costUsd : renderer?.costUsd?.();
|
|
63719
63959
|
const totals = reportsSessionTotal(record2.harness);
|
|
63720
63960
|
const sessionTotal = totals ? reported : void 0;
|
|
@@ -63752,17 +63992,17 @@ ${result}
|
|
|
63752
63992
|
...spawnWhy ? [spawnWhy] : [],
|
|
63753
63993
|
...saidOurs ? [{ kind: "silent", args: { n: String(silenceFor) } }] : []
|
|
63754
63994
|
];
|
|
63755
|
-
const quietSaid = silenceSaid(silenceFor);
|
|
63756
63995
|
if (sub) {
|
|
63757
63996
|
await closeRun(sessionId, {
|
|
63758
63997
|
status,
|
|
63759
63998
|
ok: asked ? void 0 : status === "done",
|
|
63760
63999
|
code: asked ? null : code,
|
|
63761
|
-
error:
|
|
64000
|
+
error: error62,
|
|
64001
|
+
failure: failure2,
|
|
63762
64002
|
errorWhy,
|
|
63763
64003
|
endedAt
|
|
63764
64004
|
});
|
|
63765
|
-
|
|
64005
|
+
finishWatch(status === "done" ? 0 : 1);
|
|
63766
64006
|
return;
|
|
63767
64007
|
}
|
|
63768
64008
|
await closeRun(sessionId, {
|
|
@@ -63774,7 +64014,9 @@ ${result}
|
|
|
63774
64014
|
// What went wrong, in whoever's words know: ours when the command wouldn't start or
|
|
63775
64015
|
// when it went quiet, the agent's own when the conversation ended badly or its
|
|
63776
64016
|
// stream said so. That cause leads; a card it left half-written follows.
|
|
63777
|
-
error:
|
|
64017
|
+
error: error62,
|
|
64018
|
+
failure: failure2,
|
|
64019
|
+
retryPause,
|
|
63778
64020
|
note,
|
|
63779
64021
|
errorWhy,
|
|
63780
64022
|
noteWhy,
|
|
@@ -63782,15 +64024,16 @@ ${result}
|
|
|
63782
64024
|
});
|
|
63783
64025
|
letGo();
|
|
63784
64026
|
if (retrying) {
|
|
63785
|
-
const next = await resume(sessionId);
|
|
64027
|
+
const next = await resume(sessionId, { automatic: true });
|
|
63786
64028
|
if ("error" in next) patch(sessionId, (r) => {
|
|
64029
|
+
if (r.retry) delete r.retry.pending;
|
|
63787
64030
|
r.error = joinNotes(r.error, `Could not try again: ${next.error}`);
|
|
63788
64031
|
r.errorWhy = [...r.errorWhy ?? [], { kind: "retryUnstarted", refusals: [next] }];
|
|
63789
64032
|
});
|
|
63790
64033
|
}
|
|
63791
64034
|
if (status === "done") queueCompleted(before.keys());
|
|
63792
64035
|
if (status === "done") await followUp(sessionId, record2.flowId, settled?.runs ?? []);
|
|
63793
|
-
|
|
64036
|
+
finishWatch(status === "done" ? 0 : 1);
|
|
63794
64037
|
};
|
|
63795
64038
|
let ending = false;
|
|
63796
64039
|
const endChild = () => {
|
|
@@ -63810,13 +64053,19 @@ ${result}
|
|
|
63810
64053
|
const giveUp = (asked) => {
|
|
63811
64054
|
endChild();
|
|
63812
64055
|
after(STOP_GRACE_MS + STOP_CLOSE_MS, () => {
|
|
64056
|
+
if (done) return;
|
|
63813
64057
|
after(STOP_FINISH_MS, () => process.exit(0));
|
|
63814
64058
|
void finish(null, asked).finally(() => process.exit(0));
|
|
63815
64059
|
});
|
|
63816
64060
|
};
|
|
63817
|
-
|
|
64061
|
+
endTerminal = () => {
|
|
64062
|
+
watchdog?.close();
|
|
64063
|
+
giveUp(false);
|
|
64064
|
+
};
|
|
63818
64065
|
const cancellation = new AbortController();
|
|
64066
|
+
const idle = new AbortController();
|
|
63819
64067
|
let stopped2 = false;
|
|
64068
|
+
const stoppedByUser = () => stopped2 || peekRun(sessionId)?.stopping === true;
|
|
63820
64069
|
const askToStop = () => {
|
|
63821
64070
|
if (stopped2) return;
|
|
63822
64071
|
stopped2 = true;
|
|
@@ -63828,6 +64077,11 @@ ${result}
|
|
|
63828
64077
|
if (done) return;
|
|
63829
64078
|
giveUp(true);
|
|
63830
64079
|
};
|
|
64080
|
+
const finishWatch = (code) => {
|
|
64081
|
+
process.off("SIGTERM", askToStop);
|
|
64082
|
+
process.off("SIGINT", askToStop);
|
|
64083
|
+
resolve2(code);
|
|
64084
|
+
};
|
|
63831
64085
|
process.on("SIGTERM", askToStop);
|
|
63832
64086
|
process.on("SIGINT", askToStop);
|
|
63833
64087
|
watchdog = createIdleWatchdog(() => {
|
|
@@ -63836,7 +64090,15 @@ ${result}
|
|
|
63836
64090
|
log.write(`
|
|
63837
64091
|
[board] ${silenceSaid(silenceFor)}
|
|
63838
64092
|
`);
|
|
63839
|
-
|
|
64093
|
+
if (!client?.idleRecovery) {
|
|
64094
|
+
giveUp(false);
|
|
64095
|
+
return;
|
|
64096
|
+
}
|
|
64097
|
+
uncertainAtIdle = pendingOperations.size > 0;
|
|
64098
|
+
patch(sessionId, (run4) => {
|
|
64099
|
+
run4.cleanup = { status: "unconfirmed", execution: sessionId, kept: [] };
|
|
64100
|
+
});
|
|
64101
|
+
idle.abort();
|
|
63840
64102
|
}, () => !!(client?.background?.() ?? renderer?.background?.()) || liveSubRuns(sessionId).length > 0);
|
|
63841
64103
|
touch = watchdog.touch;
|
|
63842
64104
|
observeActivity = watchdog.event;
|
|
@@ -63864,12 +64126,13 @@ ${result}
|
|
|
63864
64126
|
gotContext,
|
|
63865
64127
|
completed,
|
|
63866
64128
|
activity: touch,
|
|
63867
|
-
signal: cancellation.signal
|
|
64129
|
+
signal: cancellation.signal,
|
|
64130
|
+
idleSignal: idle.signal
|
|
63868
64131
|
}).then((end2) => {
|
|
63869
64132
|
if (done) return;
|
|
63870
64133
|
spoken = end2;
|
|
63871
64134
|
if (end2.cleanup) patch(sessionId, (r) => {
|
|
63872
|
-
r.cleanup = end2.cleanup;
|
|
64135
|
+
r.cleanup = uncertainAtIdle || silent && pendingOperations.size ? { ...end2.cleanup, status: "unconfirmed" } : end2.cleanup;
|
|
63873
64136
|
});
|
|
63874
64137
|
endChild();
|
|
63875
64138
|
void finish(end2.ok ? 0 : 1, peekRun(sessionId)?.stopping === true || stopped2);
|
|
@@ -63942,9 +64205,11 @@ var init_watch = __esm({
|
|
|
63942
64205
|
init_wire();
|
|
63943
64206
|
init_prompts();
|
|
63944
64207
|
init_resolve();
|
|
63945
|
-
init_transient();
|
|
63946
64208
|
init_idle();
|
|
64209
|
+
init_codex_background_types();
|
|
63947
64210
|
init_retry();
|
|
64211
|
+
init_failures();
|
|
64212
|
+
init_execution();
|
|
63948
64213
|
init_refine2();
|
|
63949
64214
|
init_sessions();
|
|
63950
64215
|
init_start();
|
|
@@ -64295,7 +64560,16 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
|
|
|
64295
64560
|
seen.add(current.sessionId);
|
|
64296
64561
|
printed = 0;
|
|
64297
64562
|
const deliveryId2 = first.deliveryId ?? last.deliveryId;
|
|
64298
|
-
|
|
64563
|
+
let following = nextInFlow(first, current.sessionId, seen);
|
|
64564
|
+
if (!following && last.retry?.pending) {
|
|
64565
|
+
const resumed = await startResume(last.sessionId, { automatic: true });
|
|
64566
|
+
if ("run" in resumed) following = resumed.run;
|
|
64567
|
+
else {
|
|
64568
|
+
last = await getRun(last.sessionId) ?? last;
|
|
64569
|
+
following = nextInFlow(first, current.sessionId, seen);
|
|
64570
|
+
}
|
|
64571
|
+
}
|
|
64572
|
+
const next = following ?? (deliveryId2 ? await moveDelivery(deliveryId2, idle) : void 0);
|
|
64299
64573
|
if (next === void 0) break;
|
|
64300
64574
|
if (next === null) {
|
|
64301
64575
|
await pause(follow.pollMs);
|