@dadado/agent-kit-cli 6.23.0 → 6.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dashboard/dashboard-data.mjs +126 -5
- package/dashboard/dashboard.html +48 -7
- package/dashboard/lib/guards.mjs +1 -0
- package/dashboard/lib/live-refresh.mjs +1 -0
- package/dist/{add-RKZQX6ZK.js → add-G7KEZLWP.js} +17 -8
- package/dist/{chunk-7HDQEK6T.js → chunk-2G4K4ZI5.js} +7 -3
- package/dist/{chunk-5PSV76CQ.js → chunk-2GXN7HVG.js} +26 -7
- package/dist/chunk-2QYWMSI5.js +193 -0
- package/dist/{chunk-B3VR5YBQ.js → chunk-2TW7ENWC.js} +12 -11
- package/dist/{chunk-IESSMKOV.js → chunk-5A72LTR3.js} +7 -7
- package/dist/{chunk-R4DUO5DA.js → chunk-AXQMVQ6O.js} +61 -237
- package/dist/{chunk-6WUKLS4D.js → chunk-BIFTTL2O.js} +1 -1
- package/dist/{chunk-AWQ6KRFV.js → chunk-BVZDPVUL.js} +1 -1
- package/dist/{chunk-QNISTPPZ.js → chunk-ENRXS5O6.js} +19 -12
- package/dist/chunk-FB6G6OD6.js +519 -0
- package/dist/{chunk-MFKHIWEL.js → chunk-FOVHFMSH.js} +1 -1
- package/dist/{chunk-6BEFGKCU.js → chunk-FUSNEYGU.js} +29 -3
- package/dist/chunk-H7KAXI5R.js +357 -0
- package/dist/chunk-HGB4DHXV.js +138 -0
- package/dist/{chunk-W3ZJVBNY.js → chunk-HXV6VQD4.js} +2374 -983
- package/dist/{chunk-BGL5DRK2.js → chunk-I3FGWNU5.js} +4 -4
- package/dist/chunk-IHVJTGYR.js +144 -0
- package/dist/{chunk-5LNHRL5E.js → chunk-IUY24WPE.js} +93 -263
- package/dist/chunk-JG5MKMOM.js +248 -0
- package/dist/{chunk-SGTTC2JP.js → chunk-JWIJHO67.js} +17 -2
- package/dist/chunk-KMK4T4ZM.js +34 -0
- package/dist/{chunk-ZMYV6PRE.js → chunk-LEVNLHH3.js} +2 -1
- package/dist/{chunk-2IP4OO6R.js → chunk-MGVV6YC4.js} +1 -1
- package/dist/{chunk-7TYA3GMI.js → chunk-MWRYQLEG.js} +7 -4
- package/dist/chunk-NHJ4IAVN.js +435 -0
- package/dist/{chunk-C4Q77GGJ.js → chunk-O7VMHCNN.js} +6 -0
- package/dist/{chunk-5EBT3V7G.js → chunk-OVRGTHZD.js} +1 -1
- package/dist/{chunk-F7YAAKYP.js → chunk-PCIYXGB3.js} +7 -5
- package/dist/{chunk-UJCATSYO.js → chunk-PLLXFSN2.js} +46 -17
- package/dist/{chunk-OYFCBYMP.js → chunk-RJP47EGS.js} +18 -1
- package/dist/{chunk-KDJ4ML7I.js → chunk-RRJVC35Y.js} +4 -4
- package/dist/{chunk-DRZFWIBN.js → chunk-SWJJW624.js} +1 -1
- package/dist/{chunk-MJJBIOSY.js → chunk-SYRJ5TTK.js} +34 -12
- package/dist/{chunk-L5V3W3DY.js → chunk-TTUFIE26.js} +60 -14
- package/dist/{chunk-JFS4GKP7.js → chunk-XXPI4H4D.js} +2 -2
- package/dist/{chunk-CVZNSRXV.js → chunk-Y5526WCN.js} +84 -19
- package/dist/{chunk-CQHD6UKB.js → chunk-Y575INEC.js} +2 -1
- package/dist/{chunk-V2H57TFD.js → chunk-ZNZHDPS3.js} +80 -170
- package/dist/{commands-SAQEEE6V.js → commands-K4HSDML5.js} +8 -6
- package/dist/{conflicts-5JOP4GX2.js → conflicts-4SUWIPWP.js} +9 -10
- package/dist/{contribute-BQKRT5GN.js → contribute-HE4WCBRY.js} +7 -5
- package/dist/{countdown-25E5C7AR.js → countdown-TYQHVAIX.js} +305 -32
- package/dist/{dashboard-P65XHYCU.js → dashboard-6V6PCNYF.js} +1 -1
- package/dist/{dashboard-broadcast-GYK34QYL.js → dashboard-broadcast-PMVQ7PXU.js} +1 -1
- package/dist/{diff-6JSXBVSX.js → diff-3XUZM7ZT.js} +15 -6
- package/dist/{doctor-I3MTHS7F.js → doctor-KGUWU5SN.js} +106 -19
- package/dist/{engine-info-BBI5QO5Y.js → engine-info-VM4VPGQM.js} +2 -2
- package/dist/{ground-control-IDCXN5FK.js → ground-control-ZIDHEOPW.js} +7 -4
- package/dist/{guard-RJZEEKSL.js → guard-ZO4Z3LLB.js} +47 -9
- package/dist/{handoff-5AGE2D3T.js → handoff-LLT4CI6H.js} +4 -3
- package/dist/{hook-WNA42CXE.js → hook-UPZ3CPYS.js} +22 -20
- package/dist/index.js +51 -33
- package/dist/{init-FZ2UFPO7.js → init-ZHLVXEVT.js} +25 -18
- package/dist/install-XWOG64W3.js +42 -0
- package/dist/installs-2ROXPO6M.js +223 -0
- package/dist/{mission-control-CRMCRZUU.js → mission-control-IGOI3WHS.js} +2 -2
- package/dist/models-5BDXREWM.js +45 -0
- package/dist/paths-JTPV6SXH.js +107 -0
- package/dist/pi-DCMDOY65.js +248 -0
- package/dist/{plan-index-BNLUU6T5.js → plan-index-5QZJK4AG.js} +2 -3
- package/dist/{queue-JW4VR33H.js → queue-Z5VNNHM6.js} +10 -12
- package/dist/{run-X2WOONTB.js → run-QURAXAR2.js} +27 -33
- package/dist/{run-plan-4MOLLIES.js → run-plan-4MMHVCTS.js} +35 -23
- package/dist/{scan-K3T5RQLC.js → scan-7D3RMO34.js} +2 -1
- package/dist/{session-start-MV7A4263.js → session-start-NC2HE5X5.js} +20 -14
- package/dist/{sessions-UPFDWDMB.js → sessions-WWWLYPW6.js} +4 -4
- package/dist/{setup-global-VNADNTQ2.js → setup-global-WDMARD4Z.js} +12 -10
- package/dist/{status-SXA3OK5E.js → status-2WNJL7PP.js} +17 -13
- package/dist/update-YSVOYYK5.js +32 -0
- package/dist/update-all-5XLTCHPX.js +697 -0
- package/package.json +14 -4
- package/pi/agent-kit.ts +224 -0
- package/dist/chunk-4MR4QXMF.js +0 -52
- package/dist/chunk-7ABY6DYH.js +0 -89
- package/dist/chunk-C4LCOOL4.js +0 -71
- package/dist/chunk-DZCLMIAS.js +0 -391
- package/dist/chunk-HAFRAXGV.js +0 -17
- package/dist/chunk-MUTTNRX4.js +0 -53
- package/dist/install-CTLT3TSI.js +0 -38
- package/dist/update-RMAWXMCV.js +0 -304
|
@@ -10,6 +10,11 @@ import {
|
|
|
10
10
|
unansweredStop,
|
|
11
11
|
userEventLine
|
|
12
12
|
} from "./chunk-P7732A25.js";
|
|
13
|
+
import {
|
|
14
|
+
extractHandoffNamedPlans,
|
|
15
|
+
namedPlanCandidatePaths,
|
|
16
|
+
parsePlanFrontmatter
|
|
17
|
+
} from "./chunk-TTUFIE26.js";
|
|
13
18
|
import {
|
|
14
19
|
findOnPath
|
|
15
20
|
} from "./chunk-WGLPZXNU.js";
|
|
@@ -26,1090 +31,2122 @@ import {
|
|
|
26
31
|
shouldUseWelcomeColor,
|
|
27
32
|
withKoloristColor
|
|
28
33
|
} from "./chunk-QTON2GQX.js";
|
|
34
|
+
import {
|
|
35
|
+
loadContextConfig
|
|
36
|
+
} from "./chunk-PFEUZXVT.js";
|
|
37
|
+
import {
|
|
38
|
+
HANDOFF_REL
|
|
39
|
+
} from "./chunk-O7VMHCNN.js";
|
|
40
|
+
import {
|
|
41
|
+
fileExists
|
|
42
|
+
} from "./chunk-5B4DVO6C.js";
|
|
29
43
|
|
|
30
|
-
// src/plan-loop/
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
import { access as access2 } from "fs/promises";
|
|
34
|
-
import path2 from "path";
|
|
35
|
-
import { StringDecoder as StringDecoder3 } from "string_decoder";
|
|
36
|
-
|
|
37
|
-
// src/plan-loop/codex.ts
|
|
38
|
-
import { execFileSync } from "child_process";
|
|
39
|
-
import { access } from "fs/promises";
|
|
40
|
-
import path from "path";
|
|
44
|
+
// src/plan-loop/stream-render.ts
|
|
45
|
+
import { StringDecoder } from "string_decoder";
|
|
46
|
+
import { trueColor } from "kolorist";
|
|
41
47
|
|
|
42
|
-
// src/plan-loop/
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
48
|
+
// src/plan-loop/stream-events.ts
|
|
49
|
+
function isRecord(value) {
|
|
50
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
51
|
+
}
|
|
52
|
+
function asString(value) {
|
|
53
|
+
return typeof value === "string" ? value : null;
|
|
54
|
+
}
|
|
55
|
+
function asNumber(value) {
|
|
56
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
57
|
+
}
|
|
58
|
+
function oneLine(text) {
|
|
59
|
+
return text.replace(/\s+/g, " ").trim();
|
|
60
|
+
}
|
|
61
|
+
var SUMMARY_KEYS = [
|
|
62
|
+
"command",
|
|
63
|
+
"file_path",
|
|
64
|
+
"path",
|
|
65
|
+
"pattern",
|
|
66
|
+
"query",
|
|
67
|
+
"url",
|
|
68
|
+
"description",
|
|
69
|
+
"prompt",
|
|
70
|
+
"content"
|
|
71
|
+
];
|
|
72
|
+
function summarizeToolInput(input) {
|
|
73
|
+
if (typeof input === "string") return oneLine(input);
|
|
74
|
+
if (!isRecord(input)) return input === void 0 ? "" : oneLine(JSON.stringify(input));
|
|
75
|
+
for (const key of SUMMARY_KEYS) {
|
|
76
|
+
const value = input[key];
|
|
77
|
+
if (typeof value === "string" && value.trim()) return oneLine(value);
|
|
64
78
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
return VENDOR_CLI_PINS[id].versionRe.exec(raw)?.[1] ?? null;
|
|
79
|
+
const keys = Object.keys(input);
|
|
80
|
+
if (keys.length === 0) return "";
|
|
81
|
+
return oneLine(JSON.stringify(input));
|
|
69
82
|
}
|
|
70
|
-
function
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
83
|
+
function firstLineOfContent(content) {
|
|
84
|
+
if (typeof content === "string") return firstNonEmptyLine(content);
|
|
85
|
+
if (Array.isArray(content)) {
|
|
86
|
+
for (const part of content) {
|
|
87
|
+
if (isRecord(part) && typeof part.text === "string") {
|
|
88
|
+
const line4 = firstNonEmptyLine(part.text);
|
|
89
|
+
if (line4) return line4;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return "";
|
|
76
93
|
}
|
|
77
|
-
return
|
|
94
|
+
if (isRecord(content)) return oneLine(JSON.stringify(content));
|
|
95
|
+
return "";
|
|
78
96
|
}
|
|
79
|
-
function
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (pin.min && compareVendorVersions(version, pin.min) < 0) {
|
|
84
|
-
return {
|
|
85
|
-
status: "too-old",
|
|
86
|
-
version,
|
|
87
|
-
message: `${pin.bin} ${version} is older than ${pin.min}, the oldest version the headless runner supports.`
|
|
88
|
-
};
|
|
97
|
+
function firstNonEmptyLine(text) {
|
|
98
|
+
for (const line4 of text.split(/\r?\n/)) {
|
|
99
|
+
const trimmed = line4.trim();
|
|
100
|
+
if (trimmed) return trimmed;
|
|
89
101
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
102
|
+
return "";
|
|
103
|
+
}
|
|
104
|
+
function parseAssistant(event) {
|
|
105
|
+
const message = event.message;
|
|
106
|
+
const content = isRecord(message) ? message.content : void 0;
|
|
107
|
+
if (typeof content === "string") return content ? [{ kind: "text", text: content }] : [];
|
|
108
|
+
if (!Array.isArray(content)) return [{ kind: "silent" }];
|
|
109
|
+
const out = [];
|
|
110
|
+
for (const part of content) {
|
|
111
|
+
if (!isRecord(part)) continue;
|
|
112
|
+
const type = asString(part.type);
|
|
113
|
+
if (type === "text" && typeof part.text === "string") {
|
|
114
|
+
if (part.text) out.push({ kind: "text", text: part.text });
|
|
115
|
+
} else if (type === "tool_use" || type === "server_tool_use") {
|
|
116
|
+
out.push({
|
|
117
|
+
kind: "tool_use",
|
|
118
|
+
name: asString(part.name) ?? "tool",
|
|
119
|
+
summary: summarizeToolInput(part.input)
|
|
120
|
+
});
|
|
121
|
+
}
|
|
96
122
|
}
|
|
97
|
-
return {
|
|
123
|
+
return out.length > 0 ? out : [{ kind: "silent" }];
|
|
98
124
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
"
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
125
|
+
var HITL_REPLY_PREFIX = "HITL_REPLY:";
|
|
126
|
+
function parseUser(event) {
|
|
127
|
+
const message = event.message;
|
|
128
|
+
const content = isRecord(message) ? message.content : void 0;
|
|
129
|
+
if (typeof content === "string") {
|
|
130
|
+
if (event.isReplay === true && content.startsWith(HITL_REPLY_PREFIX)) {
|
|
131
|
+
return [{ kind: "hitl_reply", line: oneLine(content) }];
|
|
132
|
+
}
|
|
133
|
+
return [{ kind: "prompt", chars: content.length }];
|
|
134
|
+
}
|
|
135
|
+
if (!Array.isArray(content)) return [{ kind: "silent" }];
|
|
136
|
+
const out = [];
|
|
137
|
+
let promptChars = 0;
|
|
138
|
+
for (const part of content) {
|
|
139
|
+
if (!isRecord(part)) continue;
|
|
140
|
+
const type = asString(part.type);
|
|
141
|
+
if (type === "tool_result") {
|
|
142
|
+
out.push({
|
|
143
|
+
kind: "tool_result",
|
|
144
|
+
ok: part.is_error !== true,
|
|
145
|
+
line: firstLineOfContent(part.content)
|
|
146
|
+
});
|
|
147
|
+
} else if (type === "text" && typeof part.text === "string") {
|
|
148
|
+
if (event.isReplay === true && part.text.startsWith(HITL_REPLY_PREFIX)) {
|
|
149
|
+
out.push({ kind: "hitl_reply", line: oneLine(part.text) });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
promptChars += part.text.length;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (promptChars > 0) out.push({ kind: "prompt", chars: promptChars });
|
|
156
|
+
return out.length > 0 ? out : [{ kind: "silent" }];
|
|
116
157
|
}
|
|
117
|
-
function
|
|
118
|
-
const
|
|
119
|
-
if (
|
|
120
|
-
|
|
121
|
-
return args;
|
|
158
|
+
function hasUnknownCostBasis(event) {
|
|
159
|
+
const usage = event.modelUsage;
|
|
160
|
+
if (!isRecord(usage)) return false;
|
|
161
|
+
return Object.values(usage).some((entry) => isRecord(entry) && entry.costBasis === "unknown");
|
|
122
162
|
}
|
|
123
|
-
function
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
163
|
+
function parseResult(event) {
|
|
164
|
+
const isError = event.is_error === true;
|
|
165
|
+
const subtype = asString(event.subtype);
|
|
166
|
+
const cost = asNumber(event.total_cost_usd);
|
|
167
|
+
const unpriced = hasUnknownCostBasis(event);
|
|
168
|
+
return {
|
|
169
|
+
kind: "result",
|
|
170
|
+
ok: !isError,
|
|
171
|
+
status: subtype ?? (isError ? "error" : "success"),
|
|
172
|
+
...unpriced ? { costBasis: "unknown", reportedCostUsd: cost } : { costUsd: cost },
|
|
173
|
+
durationMs: asNumber(event.duration_ms),
|
|
174
|
+
apiMs: asNumber(event.duration_api_ms),
|
|
175
|
+
turns: asNumber(event.num_turns)
|
|
176
|
+
};
|
|
133
177
|
}
|
|
134
|
-
function
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
178
|
+
function parseSystem(event) {
|
|
179
|
+
const subtype = asString(event.subtype) ?? "";
|
|
180
|
+
if (!subtype.startsWith("hook_")) return { kind: "silent" };
|
|
181
|
+
const phase = subtype.slice("hook_".length);
|
|
182
|
+
const name = asString(event.hook_name) ?? asString(event.hook_event) ?? "hook";
|
|
183
|
+
const details = [];
|
|
184
|
+
const outcome = asString(event.outcome);
|
|
185
|
+
if (outcome) details.push(outcome);
|
|
186
|
+
const exitCode = asNumber(event.exit_code);
|
|
187
|
+
if (exitCode !== void 0) details.push(`exit ${exitCode}`);
|
|
188
|
+
return { kind: "hook", name, phase, detail: details.join(", ") };
|
|
144
189
|
}
|
|
145
|
-
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
190
|
+
function percent(value) {
|
|
191
|
+
const n = asNumber(value);
|
|
192
|
+
return n === void 0 ? null : `${Math.round(n * 100)}%`;
|
|
193
|
+
}
|
|
194
|
+
function parseRateLimit(event) {
|
|
195
|
+
const info = isRecord(event.rate_limit_info) ? event.rate_limit_info : event;
|
|
196
|
+
const status = asString(info.status) ?? "unknown";
|
|
197
|
+
const type = asString(info.rateLimitType);
|
|
198
|
+
const parts = [];
|
|
199
|
+
if (type) parts.push(type);
|
|
200
|
+
parts.push(status);
|
|
201
|
+
const windows = isRecord(info.unifiedWindows) ? info.unifiedWindows : null;
|
|
202
|
+
if (windows) {
|
|
203
|
+
for (const [name, window] of Object.entries(windows)) {
|
|
204
|
+
if (!isRecord(window)) continue;
|
|
205
|
+
const used = percent(window.utilization);
|
|
206
|
+
if (used) parts.push(`${name} ${used}`);
|
|
207
|
+
}
|
|
153
208
|
}
|
|
154
|
-
return {
|
|
155
|
-
|
|
156
|
-
${prompt}` };
|
|
209
|
+
return { kind: "rate_limit", line: parts.join(" \xB7 "), severe: status !== "allowed" };
|
|
157
210
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
switch (event.type) {
|
|
177
|
-
case "thread.started":
|
|
178
|
-
if (typeof event.thread_id === "string") {
|
|
179
|
-
threadId = event.thread_id;
|
|
180
|
-
onThread(threadId);
|
|
181
|
-
}
|
|
182
|
-
return [line({ type: "system", subtype: "init", session_id: threadId, model: "codex" })];
|
|
183
|
-
case "item.started":
|
|
184
|
-
if (itemType === "command_execution" && typeof item?.command === "string") {
|
|
185
|
-
return [
|
|
186
|
-
line({
|
|
187
|
-
type: "assistant",
|
|
188
|
-
message: {
|
|
189
|
-
content: [{ type: "tool_use", name: "shell", input: { command: item.command } }]
|
|
190
|
-
}
|
|
191
|
-
})
|
|
192
|
-
];
|
|
193
|
-
}
|
|
194
|
-
return [];
|
|
195
|
-
case "item.completed":
|
|
196
|
-
if (isMessage && typeof item?.text === "string") {
|
|
197
|
-
lastMessage = item.text;
|
|
198
|
-
return [
|
|
199
|
-
line({ type: "assistant", message: { content: [{ type: "text", text: item.text }] } })
|
|
200
|
-
];
|
|
201
|
-
}
|
|
202
|
-
if (item && itemType === "command_execution") {
|
|
203
|
-
const exit = typeof item.exit_code === "number" ? item.exit_code : null;
|
|
204
|
-
return [
|
|
205
|
-
line({
|
|
206
|
-
type: "user",
|
|
207
|
-
message: {
|
|
208
|
-
content: [
|
|
209
|
-
{
|
|
210
|
-
type: "tool_result",
|
|
211
|
-
content: typeof item.aggregated_output === "string" ? item.aggregated_output : "",
|
|
212
|
-
is_error: exit !== null && exit !== 0
|
|
213
|
-
}
|
|
214
|
-
]
|
|
215
|
-
}
|
|
216
|
-
})
|
|
217
|
-
];
|
|
218
|
-
}
|
|
219
|
-
return [];
|
|
220
|
-
case "turn.completed": {
|
|
221
|
-
const result = lastMessage;
|
|
222
|
-
lastMessage = "";
|
|
223
|
-
return [
|
|
224
|
-
line({
|
|
225
|
-
type: "result",
|
|
226
|
-
subtype: "success",
|
|
227
|
-
is_error: false,
|
|
228
|
-
result,
|
|
229
|
-
session_id: threadId,
|
|
230
|
-
...isRecord(event.usage) ? { usage: event.usage } : {}
|
|
231
|
-
})
|
|
232
|
-
];
|
|
233
|
-
}
|
|
234
|
-
case "turn.failed": {
|
|
235
|
-
const message = isRecord(event.error) && typeof event.error.message === "string" ? event.error.message : "codex turn failed";
|
|
236
|
-
lastMessage = "";
|
|
237
|
-
return [
|
|
238
|
-
line({
|
|
239
|
-
type: "result",
|
|
240
|
-
subtype: "error_during_execution",
|
|
241
|
-
is_error: true,
|
|
242
|
-
result: message,
|
|
243
|
-
errors: [message],
|
|
244
|
-
session_id: threadId
|
|
245
|
-
})
|
|
246
|
-
];
|
|
247
|
-
}
|
|
248
|
-
default:
|
|
249
|
-
return [];
|
|
250
|
-
}
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
var codexVersionCache = /* @__PURE__ */ new Map();
|
|
254
|
-
function readCodexVersion(bin) {
|
|
255
|
-
if (!codexVersionCache.has(bin)) {
|
|
256
|
-
let out = null;
|
|
257
|
-
try {
|
|
258
|
-
out = execFileSync(bin, ["--version"], {
|
|
259
|
-
encoding: "utf8",
|
|
260
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
261
|
-
timeout: 1e4
|
|
262
|
-
});
|
|
263
|
-
} catch {
|
|
264
|
-
out = null;
|
|
211
|
+
function parseCursorToolCall(event) {
|
|
212
|
+
const call = isRecord(event.tool_call) ? event.tool_call : null;
|
|
213
|
+
const entry = call ? Object.entries(call).find(([, v]) => isRecord(v)) : void 0;
|
|
214
|
+
const name = entry ? entry[0].replace(/ToolCall$/, "") : "tool";
|
|
215
|
+
const body = entry && isRecord(entry[1]) ? entry[1] : {};
|
|
216
|
+
const subtype = asString(event.subtype) ?? "";
|
|
217
|
+
if (subtype === "started") {
|
|
218
|
+
return { kind: "tool_use", name, summary: summarizeToolInput(body.args) };
|
|
219
|
+
}
|
|
220
|
+
if (subtype === "completed") {
|
|
221
|
+
const result = isRecord(body.result) ? body.result : null;
|
|
222
|
+
const failed = result !== null && ("error" in result || "failure" in result || "rejected" in result);
|
|
223
|
+
let line4 = "";
|
|
224
|
+
if (result) {
|
|
225
|
+
const payload = failed ? result.error ?? result.failure ?? result.rejected : result.success;
|
|
226
|
+
line4 = firstLineOfContent(
|
|
227
|
+
typeof payload === "string" ? payload : payload === void 0 ? result : payload
|
|
228
|
+
);
|
|
265
229
|
}
|
|
266
|
-
|
|
230
|
+
return { kind: "tool_result", ok: !failed, line: line4 };
|
|
267
231
|
}
|
|
268
|
-
return
|
|
232
|
+
return { kind: "silent" };
|
|
269
233
|
}
|
|
270
|
-
function
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
234
|
+
function parseStreamLine(line4) {
|
|
235
|
+
const trimmed = line4.trim();
|
|
236
|
+
if (!trimmed || !trimmed.startsWith("{")) return [{ kind: "unparsed" }];
|
|
237
|
+
let event;
|
|
238
|
+
try {
|
|
239
|
+
event = JSON.parse(trimmed);
|
|
240
|
+
} catch {
|
|
241
|
+
return [{ kind: "unparsed" }];
|
|
276
242
|
}
|
|
277
|
-
return
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
if (!prepared.ok) {
|
|
294
|
-
throw new Error(
|
|
295
|
-
`codex backend: ${prepared.missing} is missing in the workspace, so the tick's leading slash has no contract to point codex at. Install the kit (\`agent-kit install\`) and retry.`
|
|
296
|
-
);
|
|
297
|
-
}
|
|
298
|
-
log(
|
|
299
|
-
`codex tick: codex exec --json (no approvals, resume relay, ${auth.mode === "api-key" ? "API key" : "ChatGPT sign-in, opt-in"}).`
|
|
300
|
-
);
|
|
301
|
-
let threadId = null;
|
|
302
|
-
const translate = createCodexTranslator((id) => {
|
|
303
|
-
threadId = id;
|
|
304
|
-
});
|
|
305
|
-
const hitl = resolveHitlRunOptions(opts.hitl, { kind: "resume", backend: "codex" });
|
|
306
|
-
const common = {
|
|
307
|
-
cwd: opts.workspace,
|
|
308
|
-
env,
|
|
309
|
-
redact,
|
|
310
|
-
spawnFn: opts.spawnFn,
|
|
311
|
-
hitl,
|
|
312
|
-
render: opts.render,
|
|
313
|
-
onSpawn: opts.onSpawn,
|
|
314
|
-
backendId: "codex",
|
|
315
|
-
translate
|
|
316
|
-
};
|
|
317
|
-
const records = [];
|
|
318
|
-
const usage = new UsageTally();
|
|
319
|
-
let result;
|
|
320
|
-
try {
|
|
321
|
-
result = await spawnLogged(
|
|
322
|
-
"codex",
|
|
323
|
-
codexExecArgs({ workspace: opts.workspace, model: opts.model }),
|
|
324
|
-
opts.logPath,
|
|
325
|
-
{ ...common, stdinText: prepared.prompt }
|
|
326
|
-
);
|
|
327
|
-
if (result.hitl) records.push(result.hitl);
|
|
328
|
-
if (result.usage) usage.merge(result.usage);
|
|
329
|
-
for (let i = 0; result.resumeWith && i < CODEX_MAX_RESUMES; i += 1) {
|
|
330
|
-
const reply = result.resumeWith;
|
|
331
|
-
const thread = threadId;
|
|
332
|
-
if (!thread) {
|
|
333
|
-
const record = emptyHitlRecord();
|
|
334
|
-
record.stop = {
|
|
335
|
-
...unansweredStop("none", "child exited"),
|
|
336
|
-
message: "stopped: codex reported no thread id, so the reply could not be delivered"
|
|
337
|
-
};
|
|
338
|
-
records.push(record);
|
|
339
|
-
break;
|
|
340
|
-
}
|
|
341
|
-
result = await spawnLogged(
|
|
342
|
-
"codex",
|
|
343
|
-
codexResumeArgs({ threadId: thread, model: opts.model }),
|
|
344
|
-
opts.logPath,
|
|
345
|
-
{ ...common, stdinText: reply, appendLog: true }
|
|
346
|
-
);
|
|
347
|
-
if (result.hitl) records.push(result.hitl);
|
|
348
|
-
if (result.usage) usage.merge(result.usage);
|
|
349
|
-
}
|
|
350
|
-
} catch (err) {
|
|
351
|
-
throw new Error(`codex backend failed to start: ${redactSecrets(String(err), redact)}`);
|
|
352
|
-
}
|
|
353
|
-
return {
|
|
354
|
-
exitCode: result.exitCode,
|
|
355
|
-
hitl: mergeRecords(records),
|
|
356
|
-
usage,
|
|
357
|
-
...result.lastResult ? { lastResult: result.lastResult } : {}
|
|
358
|
-
};
|
|
243
|
+
if (!isRecord(event)) return [{ kind: "unparsed" }];
|
|
244
|
+
switch (asString(event.type)) {
|
|
245
|
+
case "assistant":
|
|
246
|
+
return parseAssistant(event);
|
|
247
|
+
case "user":
|
|
248
|
+
return parseUser(event);
|
|
249
|
+
case "result":
|
|
250
|
+
return [parseResult(event)];
|
|
251
|
+
case "system":
|
|
252
|
+
return [parseSystem(event)];
|
|
253
|
+
case "rate_limit_event":
|
|
254
|
+
return [parseRateLimit(event)];
|
|
255
|
+
case "tool_call":
|
|
256
|
+
return [parseCursorToolCall(event)];
|
|
257
|
+
default:
|
|
258
|
+
return [{ kind: "silent" }];
|
|
359
259
|
}
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
// src/plan-loop/cursor-acp.ts
|
|
363
|
-
import { createWriteStream } from "fs";
|
|
364
|
-
import { StringDecoder as StringDecoder2 } from "string_decoder";
|
|
260
|
+
}
|
|
365
261
|
|
|
366
262
|
// src/plan-loop/stream-render.ts
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
263
|
+
var PENDING_MAX_CHARS = 4 * 1024 * 1024;
|
|
264
|
+
var MIN_COLUMNS = 40;
|
|
265
|
+
function paint(hex, text, color) {
|
|
266
|
+
if (!color) return text;
|
|
267
|
+
return withKoloristColor(
|
|
268
|
+
() => trueColor(
|
|
269
|
+
Number.parseInt(hex.slice(1, 3), 16),
|
|
270
|
+
Number.parseInt(hex.slice(3, 5), 16),
|
|
271
|
+
Number.parseInt(hex.slice(5, 7), 16)
|
|
272
|
+
)(text)
|
|
273
|
+
);
|
|
376
274
|
}
|
|
377
|
-
function
|
|
378
|
-
|
|
275
|
+
function truncate(text, width) {
|
|
276
|
+
if (text.length <= width) return text;
|
|
277
|
+
return `${text.slice(0, Math.max(1, width - 1))}\u2026`;
|
|
379
278
|
}
|
|
380
|
-
function
|
|
381
|
-
|
|
279
|
+
function formatDuration(ms) {
|
|
280
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
281
|
+
const seconds = ms / 1e3;
|
|
282
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
|
283
|
+
const minutes = Math.floor(seconds / 60);
|
|
284
|
+
const rest = Math.round(seconds - minutes * 60);
|
|
285
|
+
return `${minutes}m ${rest}s`;
|
|
382
286
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
"file_path",
|
|
386
|
-
"path",
|
|
387
|
-
"pattern",
|
|
388
|
-
"query",
|
|
389
|
-
"url",
|
|
390
|
-
"description",
|
|
391
|
-
"prompt",
|
|
392
|
-
"content"
|
|
393
|
-
];
|
|
394
|
-
function summarizeToolInput(input) {
|
|
395
|
-
if (typeof input === "string") return oneLine(input);
|
|
396
|
-
if (!isRecord2(input)) return input === void 0 ? "" : oneLine(JSON.stringify(input));
|
|
397
|
-
for (const key of SUMMARY_KEYS) {
|
|
398
|
-
const value = input[key];
|
|
399
|
-
if (typeof value === "string" && value.trim()) return oneLine(value);
|
|
400
|
-
}
|
|
401
|
-
const keys = Object.keys(input);
|
|
402
|
-
if (keys.length === 0) return "";
|
|
403
|
-
return oneLine(JSON.stringify(input));
|
|
287
|
+
function formatCost(usd) {
|
|
288
|
+
return `$${usd.toFixed(usd < 0.1 ? 4 : 2)}`;
|
|
404
289
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
290
|
+
var RESULT_LINE_HEAD = `${SPACE_MARKS.star} result `;
|
|
291
|
+
var RESULT_COST_SESSION_TOTAL = "session total";
|
|
292
|
+
var RESULT_COST_UNKNOWN = "cost unknown";
|
|
293
|
+
function formatResultLine(event, opts = {}) {
|
|
294
|
+
const parts = [`${RESULT_LINE_HEAD}${event.status}`];
|
|
295
|
+
const total = opts.sessionTotal ? ` ${RESULT_COST_SESSION_TOTAL}` : "";
|
|
296
|
+
if (event.costBasis === "unknown") {
|
|
297
|
+
parts.push(
|
|
298
|
+
event.reportedCostUsd === void 0 ? RESULT_COST_UNKNOWN : `${RESULT_COST_UNKNOWN} (claude reported ${formatCost(event.reportedCostUsd)}${total})`
|
|
299
|
+
);
|
|
300
|
+
} else if (event.costUsd !== void 0) {
|
|
301
|
+
parts.push(`${formatCost(event.costUsd)}${total}`);
|
|
415
302
|
}
|
|
416
|
-
if (
|
|
417
|
-
|
|
303
|
+
if (event.durationMs !== void 0) parts.push(formatDuration(event.durationMs));
|
|
304
|
+
else if (event.apiMs !== void 0) parts.push(`${formatDuration(event.apiMs)} api`);
|
|
305
|
+
if (event.turns !== void 0) {
|
|
306
|
+
parts.push(`${event.turns} turn${event.turns === 1 ? "" : "s"}`);
|
|
307
|
+
}
|
|
308
|
+
return parts.join(` ${SPACE_MARKS.tick} `);
|
|
418
309
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
310
|
+
var ESC = String.fromCharCode(27);
|
|
311
|
+
var ANSI_RE = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
|
|
312
|
+
var USD_RE = "\\$(\\d+(?:\\.\\d+)?)";
|
|
313
|
+
var RESULT_LINE_RE = new RegExp(
|
|
314
|
+
`^${RESULT_LINE_HEAD}(\\S+)(?: ${SPACE_MARKS.tick} (?:${USD_RE}( ${RESULT_COST_SESSION_TOTAL})?|(${RESULT_COST_UNKNOWN})(?: \\(claude reported ${USD_RE}( ${RESULT_COST_SESSION_TOTAL})?\\))?))?(?: ${SPACE_MARKS.tick} .*)?$`
|
|
315
|
+
);
|
|
316
|
+
function parseResultLine(line4) {
|
|
317
|
+
const m = RESULT_LINE_RE.exec(line4.replace(ANSI_RE, "").replace(/\r$/, ""));
|
|
318
|
+
if (!m) return null;
|
|
319
|
+
const usd = (raw) => {
|
|
320
|
+
const value = raw === void 0 ? null : Number(raw);
|
|
321
|
+
return value !== null && Number.isFinite(value) ? value : null;
|
|
322
|
+
};
|
|
323
|
+
if (m[4] !== void 0) {
|
|
324
|
+
const reportedUsd = usd(m[5]);
|
|
325
|
+
return {
|
|
326
|
+
status: m[1] ?? "",
|
|
327
|
+
costUsd: null,
|
|
328
|
+
costBasis: "unknown",
|
|
329
|
+
reportedUsd,
|
|
330
|
+
sessionTotal: reportedUsd !== null && m[6] !== void 0
|
|
331
|
+
};
|
|
423
332
|
}
|
|
424
|
-
|
|
333
|
+
const costUsd = usd(m[2]);
|
|
334
|
+
return {
|
|
335
|
+
status: m[1] ?? "",
|
|
336
|
+
costUsd,
|
|
337
|
+
costBasis: null,
|
|
338
|
+
reportedUsd: costUsd,
|
|
339
|
+
sessionTotal: costUsd !== null && m[3] !== void 0
|
|
340
|
+
};
|
|
425
341
|
}
|
|
426
|
-
function
|
|
427
|
-
const
|
|
428
|
-
const
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
342
|
+
function renderStreamEvent(event, opts) {
|
|
343
|
+
const width = Math.max(MIN_COLUMNS, opts.columns);
|
|
344
|
+
const color = opts.color;
|
|
345
|
+
switch (event.kind) {
|
|
346
|
+
case "text":
|
|
347
|
+
return event.text;
|
|
348
|
+
case "tool_use": {
|
|
349
|
+
const head = `${SPACE_MARKS.diamond} ${event.name}`;
|
|
350
|
+
const summary = truncate(event.summary, width - head.length - 3);
|
|
351
|
+
return paint(HELMET_ACCENT, summary ? `${head} ${SPACE_MARKS.tick} ${summary}` : head, color);
|
|
352
|
+
}
|
|
353
|
+
case "tool_result": {
|
|
354
|
+
const label = event.ok ? "ok" : "error";
|
|
355
|
+
const head = ` ${SPACE_MARKS.tick} ${label}`;
|
|
356
|
+
const line4 = truncate(oneLine(event.line), width - head.length - 3);
|
|
357
|
+
const text = line4 ? `${head} ${SPACE_MARKS.tick} ${line4}` : head;
|
|
358
|
+
return paint(event.ok ? LABEL_MUTED : STATUS_ERR, text, color);
|
|
359
|
+
}
|
|
360
|
+
case "result":
|
|
361
|
+
return paint(
|
|
362
|
+
event.ok ? STATUS_OK : STATUS_ERR,
|
|
363
|
+
formatResultLine(event, { sessionTotal: opts.sessionTotal === true }),
|
|
364
|
+
color
|
|
365
|
+
);
|
|
366
|
+
case "hook": {
|
|
367
|
+
const detail = event.detail ? ` (${event.detail})` : "";
|
|
368
|
+
return paint(
|
|
369
|
+
LABEL_MUTED,
|
|
370
|
+
truncate(`${SPACE_MARKS.tick} hook ${event.name} ${event.phase}${detail}`, width),
|
|
371
|
+
color
|
|
372
|
+
);
|
|
443
373
|
}
|
|
374
|
+
case "rate_limit":
|
|
375
|
+
return paint(
|
|
376
|
+
event.severe ? STATUS_ERR : STATUS_WARN,
|
|
377
|
+
truncate(`! rate limit ${SPACE_MARKS.tick} ${event.line}`, width),
|
|
378
|
+
color
|
|
379
|
+
);
|
|
380
|
+
case "prompt":
|
|
381
|
+
return paint(
|
|
382
|
+
LABEL_MUTED,
|
|
383
|
+
`${SPACE_MARKS.tick} prompt sent ${SPACE_MARKS.tick} ${event.chars} chars`,
|
|
384
|
+
color
|
|
385
|
+
);
|
|
386
|
+
case "hitl_reply":
|
|
387
|
+
return paint(HELMET_ACCENT, truncate(`\u21A9 ${event.line}`, width), color);
|
|
388
|
+
default:
|
|
389
|
+
return null;
|
|
444
390
|
}
|
|
445
|
-
return out.length > 0 ? out : [{ kind: "silent" }];
|
|
446
391
|
}
|
|
447
|
-
var
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
392
|
+
var StreamRenderer = class {
|
|
393
|
+
pending = "";
|
|
394
|
+
dropped = false;
|
|
395
|
+
textOpen = false;
|
|
396
|
+
/** A costed result was already rendered: later costs are the session's running total. */
|
|
397
|
+
costSeen = false;
|
|
398
|
+
decoder = new StringDecoder("utf8");
|
|
399
|
+
write;
|
|
400
|
+
color;
|
|
401
|
+
columns;
|
|
402
|
+
constructor(opts = {}) {
|
|
403
|
+
this.write = opts.write ?? ((text) => process.stdout.write(text));
|
|
404
|
+
this.color = shouldUseWelcomeColor({
|
|
405
|
+
stdoutIsTTY: opts.isTTY ?? Boolean(process.stdout.isTTY),
|
|
406
|
+
env: opts.env
|
|
407
|
+
});
|
|
408
|
+
this.columns = opts.columns ?? process.stdout.columns ?? 80;
|
|
409
|
+
}
|
|
410
|
+
feed(chunk) {
|
|
411
|
+
try {
|
|
412
|
+
const text = typeof chunk === "string" ? chunk : this.decoder.write(chunk);
|
|
413
|
+
if (!text) return;
|
|
414
|
+
const combined = this.pending + text;
|
|
415
|
+
const lines = combined.split("\n");
|
|
416
|
+
this.pending = lines.pop() ?? "";
|
|
417
|
+
for (const line4 of lines) {
|
|
418
|
+
if (this.dropped) {
|
|
419
|
+
this.dropped = false;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
this.renderLine(line4);
|
|
423
|
+
}
|
|
424
|
+
if (this.pending.length > PENDING_MAX_CHARS) {
|
|
425
|
+
this.pending = "";
|
|
426
|
+
this.dropped = true;
|
|
427
|
+
}
|
|
428
|
+
} catch {
|
|
454
429
|
}
|
|
455
|
-
return [{ kind: "prompt", chars: content.length }];
|
|
456
430
|
}
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
431
|
+
end() {
|
|
432
|
+
try {
|
|
433
|
+
const rest = this.pending + this.decoder.end();
|
|
434
|
+
this.pending = "";
|
|
435
|
+
if (rest && !this.dropped) this.renderLine(rest);
|
|
436
|
+
this.dropped = false;
|
|
437
|
+
this.closeText();
|
|
438
|
+
} catch {
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
renderLine(line4) {
|
|
442
|
+
for (const event of parseStreamLine(line4)) {
|
|
443
|
+
const costed = event.kind === "result" && (event.costUsd !== void 0 || event.reportedCostUsd !== void 0);
|
|
444
|
+
const rendered = renderStreamEvent(event, {
|
|
445
|
+
color: this.color,
|
|
446
|
+
columns: this.columns,
|
|
447
|
+
sessionTotal: costed && this.costSeen
|
|
468
448
|
});
|
|
469
|
-
|
|
470
|
-
if (
|
|
471
|
-
|
|
449
|
+
if (costed) this.costSeen = true;
|
|
450
|
+
if (rendered === null) continue;
|
|
451
|
+
if (event.kind === "text") {
|
|
452
|
+
this.write(rendered);
|
|
453
|
+
this.textOpen = !rendered.endsWith("\n");
|
|
472
454
|
continue;
|
|
473
455
|
}
|
|
474
|
-
|
|
456
|
+
this.closeText();
|
|
457
|
+
this.write(`${rendered}
|
|
458
|
+
`);
|
|
475
459
|
}
|
|
476
460
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
ok: !isError,
|
|
486
|
-
status: subtype ?? (isError ? "error" : "success"),
|
|
487
|
-
costUsd: asNumber(event.total_cost_usd),
|
|
488
|
-
durationMs: asNumber(event.duration_ms),
|
|
489
|
-
apiMs: asNumber(event.duration_api_ms),
|
|
490
|
-
turns: asNumber(event.num_turns)
|
|
491
|
-
};
|
|
461
|
+
closeText() {
|
|
462
|
+
if (!this.textOpen) return;
|
|
463
|
+
this.textOpen = false;
|
|
464
|
+
this.write("\n");
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
function createStreamRenderer(opts = {}) {
|
|
468
|
+
return new StreamRenderer(opts);
|
|
492
469
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
470
|
+
|
|
471
|
+
// src/plan-loop/local-models.ts
|
|
472
|
+
import { execFile } from "child_process";
|
|
473
|
+
|
|
474
|
+
// src/plan-loop/backends.ts
|
|
475
|
+
import { execFileSync as execFileSync2, spawn } from "child_process";
|
|
476
|
+
import { createWriteStream as createWriteStream2 } from "fs";
|
|
477
|
+
import { access as access2 } from "fs/promises";
|
|
478
|
+
import path4 from "path";
|
|
479
|
+
import { StringDecoder as StringDecoder3 } from "string_decoder";
|
|
480
|
+
|
|
481
|
+
// src/plan-loop/codex.ts
|
|
482
|
+
import { execFileSync } from "child_process";
|
|
483
|
+
import { access } from "fs/promises";
|
|
484
|
+
import path from "path";
|
|
485
|
+
|
|
486
|
+
// src/plan-loop/vendor-cli-pins.ts
|
|
487
|
+
var VENDOR_CLI_PINS = {
|
|
488
|
+
claude: {
|
|
489
|
+
bin: "claude",
|
|
490
|
+
min: "2.1.259",
|
|
491
|
+
tested: "2.1.292",
|
|
492
|
+
testedOn: "2026-10-08 `claude --version` (Linux)",
|
|
493
|
+
versionRe: /(\d+\.\d+\.\d+)/
|
|
494
|
+
},
|
|
495
|
+
"cursor-agent": {
|
|
496
|
+
bin: "cursor-agent",
|
|
497
|
+
min: null,
|
|
498
|
+
tested: "2026.10.01",
|
|
499
|
+
testedOn: "2026-10-08 `cursor-agent --version` = 2026.10.01-e373342 (Linux)",
|
|
500
|
+
versionRe: /(\d{4}\.\d{2}\.\d{2})(?:-[0-9a-f]+)?/
|
|
501
|
+
},
|
|
502
|
+
codex: {
|
|
503
|
+
bin: "codex",
|
|
504
|
+
min: null,
|
|
505
|
+
tested: "0.160.1",
|
|
506
|
+
testedOn: "2026-10-08 `codex --version` = codex-cli 0.160.1 (Linux)",
|
|
507
|
+
versionRe: /(\d+\.\d+\.\d+)/
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
function parseVendorVersion(id, raw) {
|
|
511
|
+
if (!raw) return null;
|
|
512
|
+
return VENDOR_CLI_PINS[id].versionRe.exec(raw)?.[1] ?? null;
|
|
504
513
|
}
|
|
505
|
-
function
|
|
506
|
-
const
|
|
507
|
-
|
|
514
|
+
function compareVendorVersions(a, b) {
|
|
515
|
+
const pa = a.split(/\D+/).filter(Boolean).map(Number);
|
|
516
|
+
const pb = b.split(/\D+/).filter(Boolean).map(Number);
|
|
517
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
518
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
519
|
+
if (d !== 0) return d;
|
|
520
|
+
}
|
|
521
|
+
return 0;
|
|
508
522
|
}
|
|
509
|
-
function
|
|
510
|
-
const
|
|
511
|
-
const
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
523
|
+
function vendorVersionStatus(id, raw) {
|
|
524
|
+
const pin = VENDOR_CLI_PINS[id];
|
|
525
|
+
const version = parseVendorVersion(id, raw);
|
|
526
|
+
if (!version) return { status: "unknown", version: null };
|
|
527
|
+
if (pin.min && compareVendorVersions(version, pin.min) < 0) {
|
|
528
|
+
return {
|
|
529
|
+
status: "too-old",
|
|
530
|
+
version,
|
|
531
|
+
message: `${pin.bin} ${version} is older than ${pin.min}, the oldest version the headless runner supports.`
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
if (compareVendorVersions(version, pin.tested) > 0) {
|
|
535
|
+
return {
|
|
536
|
+
status: "newer-than-tested",
|
|
537
|
+
version,
|
|
538
|
+
message: `${pin.bin} ${version} is newer than ${pin.tested}, the last version the kit's headless contract was checked against; continuing (a changed output format is named here first).`
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
return { status: "supported", version };
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/plan-loop/codex.ts
|
|
545
|
+
var CODEX_CHATGPT_LOGIN_ENV = "AGENT_KIT_CODEX_CHATGPT_LOGIN";
|
|
546
|
+
var CODEX_MAX_RESUMES = 50;
|
|
547
|
+
function codexExecArgs(opts) {
|
|
548
|
+
const args = [
|
|
549
|
+
"exec",
|
|
550
|
+
"--json",
|
|
551
|
+
"--color",
|
|
552
|
+
"never",
|
|
553
|
+
"--cd",
|
|
554
|
+
opts.workspace,
|
|
555
|
+
"--dangerously-bypass-approvals-and-sandbox"
|
|
556
|
+
];
|
|
557
|
+
if (opts.model) args.push("--model", opts.model);
|
|
558
|
+
args.push("-");
|
|
559
|
+
return args;
|
|
560
|
+
}
|
|
561
|
+
function codexResumeArgs(opts) {
|
|
562
|
+
const args = ["exec", "resume", "--json", "--dangerously-bypass-approvals-and-sandbox"];
|
|
563
|
+
if (opts.model) args.push("--model", opts.model);
|
|
564
|
+
args.push(opts.threadId, "-");
|
|
565
|
+
return args;
|
|
566
|
+
}
|
|
567
|
+
function resolveCodexAuth(env) {
|
|
568
|
+
if (env[CODEX_CHATGPT_LOGIN_ENV] === "1") return { mode: "chatgpt-login", env };
|
|
569
|
+
const key = env.CODEX_API_KEY || env.OPENAI_API_KEY;
|
|
570
|
+
if (!key) {
|
|
571
|
+
return {
|
|
572
|
+
mode: "refused",
|
|
573
|
+
message: `codex backend: API-key mode needs OPENAI_API_KEY (or CODEX_API_KEY) in the environment. Using a ChatGPT sign-in is off by default until OpenAI clears it for third-party apps; set ${CODEX_CHATGPT_LOGIN_ENV}=1 to run on your own codex login.`
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
return { mode: "api-key", env: { ...env, CODEX_API_KEY: key } };
|
|
577
|
+
}
|
|
578
|
+
function codexSlashPointer(name) {
|
|
579
|
+
return [
|
|
580
|
+
`Read \`.cursor/commands/${name}.md\` now and follow that contract exactly \u2014 it is the source of truth for /${name}; this paragraph is only a thin adapter for the Codex CLI.`,
|
|
581
|
+
"",
|
|
582
|
+
"Adapter rules (Codex CLI, headless):",
|
|
583
|
+
"- Ask questions is unavailable here: print one line `HITL_GATE: <ask-id> | <label 1> | <label 2> | ...` immediately followed by the same labels as one numbered list, one list per message, then end your turn and WAIT for the answer (ask-id and labels: `.cursor/skills/core/hitl-gates/SKILL.md`). The answer arrives as your next prompt, `HITL_REPLY: <ask-id> | operator reply <n> | <label>`; cite that line as the Ask provenance.",
|
|
584
|
+
"- Skip or cancel means stop.",
|
|
585
|
+
"- Never `/git-prod` without an explicit operator yes.",
|
|
586
|
+
"- Do not clone Cursor hooks or invent behavior beyond the SoT file."
|
|
587
|
+
].join("\n");
|
|
588
|
+
}
|
|
589
|
+
async function codexPrompt(workspace, prompt, pointer = codexSlashPointer) {
|
|
590
|
+
const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
|
|
591
|
+
if (!m?.[1]) return { ok: true, prompt };
|
|
592
|
+
const rel = path.join(".cursor", "commands", `${m[1]}.md`);
|
|
593
|
+
try {
|
|
594
|
+
await access(path.join(workspace, rel));
|
|
595
|
+
} catch {
|
|
596
|
+
return { ok: false, missing: rel };
|
|
597
|
+
}
|
|
598
|
+
return { ok: true, prompt: `${pointer(m[1])}
|
|
599
|
+
|
|
600
|
+
${prompt}` };
|
|
601
|
+
}
|
|
602
|
+
var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
603
|
+
var line = (event) => JSON.stringify(event);
|
|
604
|
+
function createCodexTranslator(onThread) {
|
|
605
|
+
let lastMessage = "";
|
|
606
|
+
let threadId = "";
|
|
607
|
+
return (raw) => {
|
|
608
|
+
const text = raw.trim();
|
|
609
|
+
if (!text.startsWith("{")) return [];
|
|
610
|
+
let event;
|
|
611
|
+
try {
|
|
612
|
+
event = JSON.parse(text);
|
|
613
|
+
} catch {
|
|
614
|
+
return [];
|
|
615
|
+
}
|
|
616
|
+
if (!isRecord2(event)) return [];
|
|
617
|
+
const item = isRecord2(event.item) ? event.item : null;
|
|
618
|
+
const itemType = item ? item.type ?? item.item_type : void 0;
|
|
619
|
+
const isMessage = itemType === "agent_message" || itemType === "assistant_message";
|
|
620
|
+
switch (event.type) {
|
|
621
|
+
case "thread.started":
|
|
622
|
+
if (typeof event.thread_id === "string") {
|
|
623
|
+
threadId = event.thread_id;
|
|
624
|
+
onThread(threadId);
|
|
625
|
+
}
|
|
626
|
+
return [line({ type: "system", subtype: "init", session_id: threadId, model: "codex" })];
|
|
627
|
+
case "item.started":
|
|
628
|
+
if (itemType === "command_execution" && typeof item?.command === "string") {
|
|
629
|
+
return [
|
|
630
|
+
line({
|
|
631
|
+
type: "assistant",
|
|
632
|
+
message: {
|
|
633
|
+
content: [{ type: "tool_use", name: "shell", input: { command: item.command } }]
|
|
634
|
+
}
|
|
635
|
+
})
|
|
636
|
+
];
|
|
637
|
+
}
|
|
638
|
+
return [];
|
|
639
|
+
case "item.completed":
|
|
640
|
+
if (isMessage && typeof item?.text === "string") {
|
|
641
|
+
lastMessage = item.text;
|
|
642
|
+
return [
|
|
643
|
+
line({ type: "assistant", message: { content: [{ type: "text", text: item.text }] } })
|
|
644
|
+
];
|
|
645
|
+
}
|
|
646
|
+
if (item && itemType === "command_execution") {
|
|
647
|
+
const exit = typeof item.exit_code === "number" ? item.exit_code : null;
|
|
648
|
+
return [
|
|
649
|
+
line({
|
|
650
|
+
type: "user",
|
|
651
|
+
message: {
|
|
652
|
+
content: [
|
|
653
|
+
{
|
|
654
|
+
type: "tool_result",
|
|
655
|
+
content: typeof item.aggregated_output === "string" ? item.aggregated_output : "",
|
|
656
|
+
is_error: exit !== null && exit !== 0
|
|
657
|
+
}
|
|
658
|
+
]
|
|
659
|
+
}
|
|
660
|
+
})
|
|
661
|
+
];
|
|
662
|
+
}
|
|
663
|
+
return [];
|
|
664
|
+
case "turn.completed": {
|
|
665
|
+
const result = lastMessage;
|
|
666
|
+
lastMessage = "";
|
|
667
|
+
return [
|
|
668
|
+
line({
|
|
669
|
+
type: "result",
|
|
670
|
+
subtype: "success",
|
|
671
|
+
is_error: false,
|
|
672
|
+
result,
|
|
673
|
+
session_id: threadId,
|
|
674
|
+
...isRecord2(event.usage) ? { usage: event.usage } : {}
|
|
675
|
+
})
|
|
676
|
+
];
|
|
677
|
+
}
|
|
678
|
+
case "turn.failed": {
|
|
679
|
+
const message = isRecord2(event.error) && typeof event.error.message === "string" ? event.error.message : "codex turn failed";
|
|
680
|
+
lastMessage = "";
|
|
681
|
+
return [
|
|
682
|
+
line({
|
|
683
|
+
type: "result",
|
|
684
|
+
subtype: "error_during_execution",
|
|
685
|
+
is_error: true,
|
|
686
|
+
result: message,
|
|
687
|
+
errors: [message],
|
|
688
|
+
session_id: threadId
|
|
689
|
+
})
|
|
690
|
+
];
|
|
691
|
+
}
|
|
692
|
+
default:
|
|
693
|
+
return [];
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
var codexVersionCache = /* @__PURE__ */ new Map();
|
|
698
|
+
function readCodexVersion(bin) {
|
|
699
|
+
if (!codexVersionCache.has(bin)) {
|
|
700
|
+
let out = null;
|
|
701
|
+
try {
|
|
702
|
+
out = execFileSync(bin, ["--version"], {
|
|
703
|
+
encoding: "utf8",
|
|
704
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
705
|
+
timeout: 1e4
|
|
706
|
+
});
|
|
707
|
+
} catch {
|
|
708
|
+
out = null;
|
|
709
|
+
}
|
|
710
|
+
codexVersionCache.set(bin, out);
|
|
711
|
+
}
|
|
712
|
+
return codexVersionCache.get(bin) ?? null;
|
|
713
|
+
}
|
|
714
|
+
function mergeRecords(records) {
|
|
715
|
+
const merged = emptyHitlRecord();
|
|
716
|
+
for (const r of records) {
|
|
717
|
+
merged.replies.push(...r.replies);
|
|
718
|
+
merged.fallbackDetections += r.fallbackDetections;
|
|
719
|
+
if (r.stop) merged.stop = r.stop;
|
|
720
|
+
}
|
|
721
|
+
return merged;
|
|
722
|
+
}
|
|
723
|
+
var codexBackend = {
|
|
724
|
+
id: "codex",
|
|
725
|
+
async resolve() {
|
|
726
|
+
return whichBinary("codex");
|
|
727
|
+
},
|
|
728
|
+
async run(opts) {
|
|
729
|
+
const log = opts.log ?? ((text) => console.log(text));
|
|
730
|
+
const auth = resolveCodexAuth(mergeChildEnv(opts.env));
|
|
731
|
+
if (auth.mode === "refused") throw new Error(auth.message);
|
|
732
|
+
const env = auth.env;
|
|
733
|
+
const redact = claudeRedactions(env);
|
|
734
|
+
const pin = vendorVersionStatus("codex", (opts.versionFn ?? readCodexVersion)("codex"));
|
|
735
|
+
if (pin.status === "newer-than-tested" || pin.status === "too-old") log(pin.message);
|
|
736
|
+
const prepared = await codexPrompt(opts.workspace, opts.prompt);
|
|
737
|
+
if (!prepared.ok) {
|
|
738
|
+
throw new Error(
|
|
739
|
+
`codex backend: ${prepared.missing} is missing in the workspace, so the tick's leading slash has no contract to point codex at. Install the kit (\`agent-kit install\`) and retry.`
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
log(
|
|
743
|
+
`codex tick: codex exec --json (no approvals, resume relay, ${auth.mode === "api-key" ? "API key" : "ChatGPT sign-in, opt-in"}).`
|
|
744
|
+
);
|
|
745
|
+
let threadId = null;
|
|
746
|
+
const translate = createCodexTranslator((id) => {
|
|
747
|
+
threadId = id;
|
|
748
|
+
});
|
|
749
|
+
const hitl = resolveHitlRunOptions(opts.hitl, { kind: "resume", backend: "codex" });
|
|
750
|
+
const common = {
|
|
751
|
+
cwd: opts.workspace,
|
|
752
|
+
env,
|
|
753
|
+
redact,
|
|
754
|
+
spawnFn: opts.spawnFn,
|
|
755
|
+
hitl,
|
|
756
|
+
render: opts.render,
|
|
757
|
+
onSpawn: opts.onSpawn,
|
|
758
|
+
backendId: "codex",
|
|
759
|
+
translate
|
|
760
|
+
};
|
|
761
|
+
const records = [];
|
|
762
|
+
const usage = new UsageTally();
|
|
763
|
+
let result;
|
|
764
|
+
try {
|
|
765
|
+
result = await spawnLogged(
|
|
766
|
+
"codex",
|
|
767
|
+
codexExecArgs({ workspace: opts.workspace, model: opts.model }),
|
|
768
|
+
opts.logPath,
|
|
769
|
+
{ ...common, stdinText: prepared.prompt }
|
|
770
|
+
);
|
|
771
|
+
if (result.hitl) records.push(result.hitl);
|
|
772
|
+
if (result.usage) usage.merge(result.usage);
|
|
773
|
+
for (let i = 0; result.resumeWith && i < CODEX_MAX_RESUMES; i += 1) {
|
|
774
|
+
const reply = result.resumeWith;
|
|
775
|
+
const thread = threadId;
|
|
776
|
+
if (!thread) {
|
|
777
|
+
const record = emptyHitlRecord();
|
|
778
|
+
record.stop = {
|
|
779
|
+
...unansweredStop("none", "child exited"),
|
|
780
|
+
message: "stopped: codex reported no thread id, so the reply could not be delivered"
|
|
781
|
+
};
|
|
782
|
+
records.push(record);
|
|
783
|
+
break;
|
|
784
|
+
}
|
|
785
|
+
result = await spawnLogged(
|
|
786
|
+
"codex",
|
|
787
|
+
codexResumeArgs({ threadId: thread, model: opts.model }),
|
|
788
|
+
opts.logPath,
|
|
789
|
+
{ ...common, stdinText: reply, appendLog: true }
|
|
790
|
+
);
|
|
791
|
+
if (result.hitl) records.push(result.hitl);
|
|
792
|
+
if (result.usage) usage.merge(result.usage);
|
|
793
|
+
}
|
|
794
|
+
} catch (err) {
|
|
795
|
+
throw new Error(`codex backend failed to start: ${redactSecrets(String(err), redact)}`);
|
|
796
|
+
}
|
|
797
|
+
return {
|
|
798
|
+
exitCode: result.exitCode,
|
|
799
|
+
hitl: mergeRecords(records),
|
|
800
|
+
usage,
|
|
801
|
+
...result.lastResult ? { lastResult: result.lastResult } : {}
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
|
|
806
|
+
// src/plan-loop/cursor-acp.ts
|
|
807
|
+
import { createWriteStream } from "fs";
|
|
808
|
+
import { StringDecoder as StringDecoder2 } from "string_decoder";
|
|
809
|
+
var ACP_PROTOCOL_VERSION = 1;
|
|
810
|
+
var CURSOR_ASK_QUESTION_ID = "cursor-ask-question";
|
|
811
|
+
var ACP_EXIT_GRACE_MS = 1e3;
|
|
812
|
+
var ACP_KILL_GRACE_MS = 5e3;
|
|
813
|
+
var ACP_MAX_TURNS = 50;
|
|
814
|
+
function cursorAcpArgs() {
|
|
815
|
+
return ["acp"];
|
|
816
|
+
}
|
|
817
|
+
var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
818
|
+
function acpInitializeParams() {
|
|
819
|
+
return {
|
|
820
|
+
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
821
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
822
|
+
clientInfo: { name: "agent-kit", version: "1" }
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
function acpPermissionOutcome(params) {
|
|
826
|
+
const options = isRecord3(params) && Array.isArray(params.options) ? params.options : [];
|
|
827
|
+
const pick = options.find((o) => isRecord3(o) && (o.optionId === "allow-once" || o.kind === "allow_once")) ?? options.find(
|
|
828
|
+
(o) => isRecord3(o) && (typeof o.optionId === "string" && o.optionId.startsWith("allow") || typeof o.kind === "string" && o.kind.startsWith("allow"))
|
|
829
|
+
);
|
|
830
|
+
if (isRecord3(pick) && typeof pick.optionId === "string") {
|
|
831
|
+
return { outcome: { outcome: "selected", optionId: pick.optionId } };
|
|
832
|
+
}
|
|
833
|
+
return { outcome: { outcome: "cancelled" } };
|
|
834
|
+
}
|
|
835
|
+
function acpQuestions(params) {
|
|
836
|
+
const raw = isRecord3(params) && Array.isArray(params.questions) ? params.questions : [];
|
|
837
|
+
const out = [];
|
|
838
|
+
for (const q of raw) {
|
|
839
|
+
if (!isRecord3(q) || typeof q.id !== "string" || !Array.isArray(q.options)) continue;
|
|
840
|
+
const options = q.options.filter((o) => isRecord3(o) && typeof o.id === "string").map((o) => ({
|
|
841
|
+
id: o.id,
|
|
842
|
+
label: String(typeof o.label === "string" ? o.label : o.id).replace(/\|/g, "/").trim()
|
|
843
|
+
}));
|
|
844
|
+
if (options.length === 0) continue;
|
|
845
|
+
out.push({ id: q.id, prompt: typeof q.prompt === "string" ? q.prompt : "", options });
|
|
846
|
+
}
|
|
847
|
+
return out;
|
|
848
|
+
}
|
|
849
|
+
var line2 = (event) => `${JSON.stringify(event)}
|
|
850
|
+
`;
|
|
851
|
+
async function runCursorAcp(opts) {
|
|
852
|
+
const say = opts.log ?? ((text) => console.log(text));
|
|
853
|
+
const env = mergeChildEnv(opts.env);
|
|
854
|
+
const redact = claudeRedactions(env);
|
|
855
|
+
const hitl = resolveHitlRunOptions(opts.hitl, { kind: "none", backend: "cursor-acp" });
|
|
856
|
+
const render = opts.render ?? createStreamRenderer();
|
|
857
|
+
const spawnFn = opts.spawnFn ?? (await import("child_process")).spawn;
|
|
858
|
+
const record = emptyHitlRecord();
|
|
859
|
+
const abort = new AbortController();
|
|
860
|
+
if (opts.model) say("cursor-acp: --model is not sent over ACP; the agent's default model runs.");
|
|
861
|
+
say("cursor tick: cursor-agent acp (JSON-RPC stdio, HITL relay, tool permissions allow-once).");
|
|
862
|
+
const out = createWriteStream(opts.logPath, { flags: "w" });
|
|
863
|
+
let logError = null;
|
|
864
|
+
out.on("error", (err) => {
|
|
865
|
+
logError = err;
|
|
866
|
+
});
|
|
867
|
+
const logLine = (text) => out.write(`${redactSecrets(text, redact)}
|
|
868
|
+
`);
|
|
869
|
+
const child = spawnFn("cursor-agent", cursorAcpArgs(), {
|
|
870
|
+
cwd: opts.workspace,
|
|
871
|
+
env,
|
|
872
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
873
|
+
});
|
|
874
|
+
const pending = /* @__PURE__ */ new Map();
|
|
875
|
+
let closed = false;
|
|
876
|
+
let exitCode = null;
|
|
877
|
+
let spawnError = null;
|
|
878
|
+
let resolveClosed = () => {
|
|
879
|
+
};
|
|
880
|
+
const closedPromise = new Promise((resolve) => {
|
|
881
|
+
resolveClosed = resolve;
|
|
882
|
+
});
|
|
883
|
+
const gone = (code2) => {
|
|
884
|
+
if (closed) return;
|
|
885
|
+
closed = true;
|
|
886
|
+
exitCode = code2;
|
|
887
|
+
abort.abort();
|
|
888
|
+
for (const p of pending.values()) {
|
|
889
|
+
p.reject({ message: `cursor-agent acp exited (code ${code2 ?? "signal"})` });
|
|
890
|
+
}
|
|
891
|
+
pending.clear();
|
|
892
|
+
resolveClosed();
|
|
893
|
+
};
|
|
894
|
+
child.on("close", (code2) => gone(code2));
|
|
895
|
+
child.on("error", (err) => {
|
|
896
|
+
spawnError = new Error(redactSecrets(String(err), redact));
|
|
897
|
+
gone(null);
|
|
898
|
+
});
|
|
899
|
+
let nextId = 1;
|
|
900
|
+
let turnText = "";
|
|
901
|
+
let sessionId = null;
|
|
902
|
+
const send = (msg) => {
|
|
903
|
+
const text = JSON.stringify(msg);
|
|
904
|
+
logLine(text);
|
|
905
|
+
try {
|
|
906
|
+
child.stdin?.write(`${text}
|
|
907
|
+
`);
|
|
908
|
+
} catch {
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
912
|
+
if (closed) {
|
|
913
|
+
reject({ message: "cursor-agent acp is not running" });
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const id = nextId++;
|
|
917
|
+
pending.set(id, { resolve, reject });
|
|
918
|
+
send({ jsonrpc: "2.0", id, method, params });
|
|
919
|
+
});
|
|
920
|
+
const respond = (id, result) => send({ jsonrpc: "2.0", id, result });
|
|
921
|
+
const respondError = (id, code2, message) => send({ jsonrpc: "2.0", id, error: { code: code2, message } });
|
|
922
|
+
const ask = (gate) => askOperator(gate, {
|
|
923
|
+
isTTY: hitl.isTTY,
|
|
924
|
+
policy: hitl.policy,
|
|
925
|
+
readAnswer: hitl.readAnswer,
|
|
926
|
+
write: hitl.write,
|
|
927
|
+
signal: abort.signal,
|
|
928
|
+
onPromptStart: hitl.onPromptStart,
|
|
929
|
+
onPromptEnd: hitl.onPromptEnd,
|
|
930
|
+
checkIn: hitl.checkIn
|
|
931
|
+
});
|
|
932
|
+
const cancelSession = () => {
|
|
933
|
+
if (sessionId && !closed)
|
|
934
|
+
send({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId } });
|
|
935
|
+
};
|
|
936
|
+
const handleAskQuestion = async (id, params) => {
|
|
937
|
+
const answers = [];
|
|
938
|
+
for (const q of acpQuestions(params)) {
|
|
939
|
+
if (record.stop) break;
|
|
940
|
+
const gate = {
|
|
941
|
+
askId: CURSOR_ASK_QUESTION_ID,
|
|
942
|
+
labels: q.options.map((o) => o.label),
|
|
943
|
+
detection: "sentinel"
|
|
944
|
+
};
|
|
945
|
+
const outcome = await ask(gate);
|
|
946
|
+
if (outcome.kind === "stop") {
|
|
947
|
+
record.stop = outcome.stop;
|
|
948
|
+
break;
|
|
949
|
+
}
|
|
950
|
+
record.replies.push(outcome.stamp);
|
|
951
|
+
hitl.write(`\u2192 ${outcome.stamp.line}
|
|
952
|
+
`);
|
|
953
|
+
const n = /(?:operator reply|policy pre-answer) (\d+)/.exec(outcome.stamp.reply)?.[1];
|
|
954
|
+
const option = n ? q.options[Number(n) - 1] : void 0;
|
|
955
|
+
if (!option) {
|
|
956
|
+
hitl.write(
|
|
957
|
+
"cursor-acp: a free-text answer has no cursor/ask_question option; the question is answered as cancelled.\n"
|
|
958
|
+
);
|
|
959
|
+
respond(id, { outcome: { outcome: "cancelled" } });
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
answers.push({ questionId: q.id, selectedOptionIds: [option.id] });
|
|
963
|
+
}
|
|
964
|
+
if (record.stop) {
|
|
965
|
+
respond(id, { outcome: { outcome: "cancelled" } });
|
|
966
|
+
cancelSession();
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
respond(id, { outcome: { outcome: "answered", answers } });
|
|
970
|
+
};
|
|
971
|
+
const handleRequest = (msg) => {
|
|
972
|
+
const { id, method, params } = msg;
|
|
973
|
+
if (method === "session/request_permission") {
|
|
974
|
+
respond(id, acpPermissionOutcome(params));
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
if (method === "cursor/ask_question") {
|
|
978
|
+
void handleAskQuestion(id, params);
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
respondError(id, -32601, `agent-kit does not implement ${String(method)}`);
|
|
982
|
+
};
|
|
983
|
+
const handleNotification = (msg) => {
|
|
984
|
+
if (msg.method !== "session/update" || !isRecord3(msg.params)) return;
|
|
985
|
+
const update = isRecord3(msg.params.update) ? msg.params.update : null;
|
|
986
|
+
if (!update) return;
|
|
987
|
+
if (update.sessionUpdate === "agent_message_chunk") {
|
|
988
|
+
const content = isRecord3(update.content) ? update.content : null;
|
|
989
|
+
if (content?.type === "text" && typeof content.text === "string") turnText += content.text;
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
if (update.sessionUpdate === "tool_call") {
|
|
993
|
+
const title = typeof update.title === "string" ? update.title : "tool";
|
|
994
|
+
render.feed(
|
|
995
|
+
line2({
|
|
996
|
+
type: "assistant",
|
|
997
|
+
message: {
|
|
998
|
+
content: [
|
|
999
|
+
{
|
|
1000
|
+
type: "tool_use",
|
|
1001
|
+
name: typeof update.kind === "string" ? update.kind : "tool",
|
|
1002
|
+
input: { title }
|
|
1003
|
+
}
|
|
1004
|
+
]
|
|
1005
|
+
}
|
|
1006
|
+
})
|
|
1007
|
+
);
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
const take = (raw) => {
|
|
1011
|
+
const text = redactSecrets(raw.replace(/\r$/, ""), redact);
|
|
1012
|
+
if (!text.trim()) return;
|
|
1013
|
+
out.write(`${text}
|
|
1014
|
+
`);
|
|
1015
|
+
let msg;
|
|
1016
|
+
try {
|
|
1017
|
+
msg = JSON.parse(text);
|
|
1018
|
+
} catch {
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
if (!isRecord3(msg)) return;
|
|
1022
|
+
if (typeof msg.method === "string") {
|
|
1023
|
+
if (msg.id !== void 0 && msg.id !== null) handleRequest(msg);
|
|
1024
|
+
else handleNotification(msg);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
if (typeof msg.id === "number") {
|
|
1028
|
+
const p = pending.get(msg.id);
|
|
1029
|
+
if (!p) return;
|
|
1030
|
+
pending.delete(msg.id);
|
|
1031
|
+
if (isRecord3(msg.error)) {
|
|
1032
|
+
p.reject({
|
|
1033
|
+
message: typeof msg.error.message === "string" ? msg.error.message : "JSON-RPC error",
|
|
1034
|
+
...typeof msg.error.code === "number" ? { code: msg.error.code } : {}
|
|
1035
|
+
});
|
|
1036
|
+
} else p.resolve(msg.result);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
const decoder = new StringDecoder2("utf8");
|
|
1040
|
+
const splitter = new LineSplitter();
|
|
1041
|
+
child.stdout?.on("data", (chunk) => {
|
|
1042
|
+
splitter.feed(typeof chunk === "string" ? chunk : decoder.write(chunk), take);
|
|
1043
|
+
});
|
|
1044
|
+
const errBuffer = new RedactingStreamBuffer(redact);
|
|
1045
|
+
child.stderr?.on("data", (chunk) => {
|
|
1046
|
+
const text = redact.length ? errBuffer.push(chunk) : String(chunk);
|
|
1047
|
+
if (text) out.write(text);
|
|
1048
|
+
});
|
|
1049
|
+
child.stdin?.on("error", () => {
|
|
1050
|
+
});
|
|
1051
|
+
let stopped = false;
|
|
1052
|
+
const endChild = () => {
|
|
1053
|
+
if (stopped) return;
|
|
1054
|
+
stopped = true;
|
|
1055
|
+
try {
|
|
1056
|
+
child.stdin?.end();
|
|
1057
|
+
} catch {
|
|
522
1058
|
}
|
|
1059
|
+
const term = setTimeout(() => {
|
|
1060
|
+
if (closed) return;
|
|
1061
|
+
child.kill("SIGTERM");
|
|
1062
|
+
const kill = setTimeout(() => {
|
|
1063
|
+
if (!closed) child.kill("SIGKILL");
|
|
1064
|
+
}, ACP_KILL_GRACE_MS);
|
|
1065
|
+
kill.unref?.();
|
|
1066
|
+
}, ACP_EXIT_GRACE_MS);
|
|
1067
|
+
term.unref?.();
|
|
1068
|
+
};
|
|
1069
|
+
opts.onSpawn?.({
|
|
1070
|
+
backend: "cursor-acp",
|
|
1071
|
+
pid: child.pid,
|
|
1072
|
+
stop: (stop) => {
|
|
1073
|
+
if (closed || record.stop) return;
|
|
1074
|
+
record.stop = stop;
|
|
1075
|
+
cancelSession();
|
|
1076
|
+
abort.abort();
|
|
1077
|
+
endChild();
|
|
1078
|
+
}
|
|
1079
|
+
});
|
|
1080
|
+
let lastResult;
|
|
1081
|
+
const finishTurn = (text, isError, subtype, errors) => {
|
|
1082
|
+
render.feed(line2({ type: "assistant", message: { content: [{ type: "text", text }] } }));
|
|
1083
|
+
render.feed(
|
|
1084
|
+
line2({
|
|
1085
|
+
type: "result",
|
|
1086
|
+
subtype,
|
|
1087
|
+
is_error: isError,
|
|
1088
|
+
result: text,
|
|
1089
|
+
session_id: sessionId ?? "",
|
|
1090
|
+
...errors.length ? { errors } : {}
|
|
1091
|
+
})
|
|
1092
|
+
);
|
|
1093
|
+
lastResult = {
|
|
1094
|
+
resultText: text,
|
|
1095
|
+
assistantTexts: text ? [text] : [],
|
|
1096
|
+
isError,
|
|
1097
|
+
subtype,
|
|
1098
|
+
errors,
|
|
1099
|
+
backgroundTasks: 0
|
|
1100
|
+
};
|
|
1101
|
+
};
|
|
1102
|
+
const failed = (message, subtype = "error") => finishTurn(message, true, subtype, [message]);
|
|
1103
|
+
const session = async () => {
|
|
1104
|
+
const init = await request("initialize", acpInitializeParams());
|
|
1105
|
+
const methods = isRecord3(init) && Array.isArray(init.authMethods) ? init.authMethods : [];
|
|
1106
|
+
if (methods.some((m) => isRecord3(m) && m.id === "cursor_login")) {
|
|
1107
|
+
try {
|
|
1108
|
+
await request("authenticate", { methodId: "cursor_login" });
|
|
1109
|
+
} catch (err) {
|
|
1110
|
+
const message = err.message ?? String(err);
|
|
1111
|
+
throw {
|
|
1112
|
+
message: `Cursor sign-in needed: run \`cursor-agent login\` in a terminal (the kit never handles Cursor credentials). ${message}`
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
const created = await request("session/new", { cwd: opts.workspace, mcpServers: [] });
|
|
1117
|
+
if (!isRecord3(created) || typeof created.sessionId !== "string") {
|
|
1118
|
+
throw { message: "cursor-agent acp returned no sessionId" };
|
|
1119
|
+
}
|
|
1120
|
+
sessionId = created.sessionId;
|
|
1121
|
+
render.feed(
|
|
1122
|
+
line2({ type: "system", subtype: "init", session_id: sessionId, model: "cursor-acp" })
|
|
1123
|
+
);
|
|
1124
|
+
let prompt = opts.prompt;
|
|
1125
|
+
for (let turn = 0; turn < ACP_MAX_TURNS && !record.stop; turn += 1) {
|
|
1126
|
+
turnText = "";
|
|
1127
|
+
let stopReason = "end_turn";
|
|
1128
|
+
try {
|
|
1129
|
+
const res = await request("session/prompt", {
|
|
1130
|
+
sessionId,
|
|
1131
|
+
prompt: [{ type: "text", text: prompt }]
|
|
1132
|
+
});
|
|
1133
|
+
if (isRecord3(res) && typeof res.stopReason === "string") stopReason = res.stopReason;
|
|
1134
|
+
} catch (err) {
|
|
1135
|
+
failed(err.message ?? String(err));
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
const text = turnText;
|
|
1139
|
+
finishTurn(text, stopReason === "refusal", stopReason, []);
|
|
1140
|
+
if (record.stop || stopReason === "cancelled") return;
|
|
1141
|
+
const gate = detectHitlGate(text, []);
|
|
1142
|
+
if (!gate) return;
|
|
1143
|
+
if (gate.detection === "fallback") record.fallbackDetections += 1;
|
|
1144
|
+
const outcome = await ask(gate);
|
|
1145
|
+
if (outcome.kind === "stop") {
|
|
1146
|
+
record.stop = outcome.stop;
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
record.replies.push(outcome.stamp);
|
|
1150
|
+
hitl.write(`\u2192 ${outcome.stamp.line}
|
|
1151
|
+
`);
|
|
1152
|
+
prompt = outcome.stamp.line;
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
await session().catch((err) => {
|
|
1156
|
+
failed(err.message ?? String(err));
|
|
1157
|
+
});
|
|
1158
|
+
const failure = spawnError;
|
|
1159
|
+
if (failure) {
|
|
1160
|
+
out.end();
|
|
1161
|
+
throw new Error(`cursor-acp backend failed to start: ${failure.message}`);
|
|
523
1162
|
}
|
|
524
|
-
|
|
1163
|
+
const endedByClient = !closed;
|
|
1164
|
+
endChild();
|
|
1165
|
+
await closedPromise;
|
|
1166
|
+
const rest = splitter.end();
|
|
1167
|
+
if (rest.trim()) take(rest);
|
|
1168
|
+
const errRest = errBuffer.flush();
|
|
1169
|
+
if (errRest) out.write(errRest);
|
|
1170
|
+
render.end();
|
|
1171
|
+
await new Promise((resolve) => out.end(() => resolve()));
|
|
1172
|
+
if (logError) throw new Error(`cursor-acp backend: ${redactSecrets(String(logError), redact)}`);
|
|
1173
|
+
const code = lastResult?.isError ? 1 : endedByClient ? 0 : exitCode ?? 1;
|
|
1174
|
+
return { exitCode: code, hitl: record, ...lastResult ? { lastResult } : {} };
|
|
1175
|
+
}
|
|
1176
|
+
var cursorAcpBackend = {
|
|
1177
|
+
id: "cursor-acp",
|
|
1178
|
+
async resolve() {
|
|
1179
|
+
return whichBinary("cursor-agent");
|
|
1180
|
+
},
|
|
1181
|
+
run: runCursorAcp
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
// src/plan-loop/local.ts
|
|
1185
|
+
import { randomUUID } from "crypto";
|
|
1186
|
+
import { mkdir, mkdtemp, rm, writeFile } from "fs/promises";
|
|
1187
|
+
import { tmpdir } from "os";
|
|
1188
|
+
import path3 from "path";
|
|
1189
|
+
|
|
1190
|
+
// src/plan-loop/detect.ts
|
|
1191
|
+
var DETECT_ORDER = ["cursor-agent", "claude"];
|
|
1192
|
+
var EXPLICIT_ONLY_BACKENDS = [
|
|
1193
|
+
"codex",
|
|
1194
|
+
"cursor-acp",
|
|
1195
|
+
"openrouter",
|
|
1196
|
+
"local"
|
|
1197
|
+
];
|
|
1198
|
+
var INSTALL_HINTS = {
|
|
1199
|
+
"cursor-agent": "Install the Cursor Agent CLI and ensure `cursor-agent` is on PATH (https://cursor.com/docs/cli).",
|
|
1200
|
+
claude: "Install Claude Code and ensure `claude` is on PATH (https://code.claude.com/docs/en/quickstart).",
|
|
1201
|
+
"cursor-acp": "Install the Cursor Agent CLI and ensure `cursor-agent` is on PATH (https://cursor.com/docs/cli/acp); sign in with `cursor-agent login`.",
|
|
1202
|
+
codex: "Install the Codex CLI and ensure `codex` is on PATH (https://developers.openai.com/codex/cli).",
|
|
1203
|
+
openrouter: "Install Ori and ensure `ori` is on PATH, then sign in with `ori login` (OpenRouter credentials). The kit never falls back to a first-party `claude` here: that would bill Anthropic instead of OpenRouter.",
|
|
1204
|
+
local: "Install pi (the coding agent Omarchy opens for local models) and ensure `pi` is on PATH, then pick a model from `agent-kit models` with `--model <source>:<id>`. The kit never falls back to a paid engine here."
|
|
1205
|
+
};
|
|
1206
|
+
var BACKEND_BIN = {
|
|
1207
|
+
"cursor-agent": "cursor-agent",
|
|
1208
|
+
claude: "claude",
|
|
1209
|
+
codex: "codex",
|
|
1210
|
+
"cursor-acp": "cursor-agent",
|
|
1211
|
+
openrouter: "ori",
|
|
1212
|
+
local: "pi"
|
|
1213
|
+
};
|
|
1214
|
+
function isBackendId(id) {
|
|
1215
|
+
return id === "cursor-agent" || id === "claude" || id === "codex" || id === "cursor-acp" || id === "openrouter" || id === "local";
|
|
525
1216
|
}
|
|
526
|
-
function
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
1217
|
+
function isRequestedBackend(id) {
|
|
1218
|
+
return id === "auto" || isBackendId(id);
|
|
1219
|
+
}
|
|
1220
|
+
function listDetectBackendIds() {
|
|
1221
|
+
return ["auto", ...DETECT_ORDER, ...EXPLICIT_ONLY_BACKENDS];
|
|
1222
|
+
}
|
|
1223
|
+
async function detectAgentBackend(requested, whichFn = whichBinary) {
|
|
1224
|
+
const id = requested.trim().toLowerCase();
|
|
1225
|
+
if (id === "glm" || id.startsWith("glm-") || id === "glm4") {
|
|
1226
|
+
return {
|
|
1227
|
+
ok: false,
|
|
1228
|
+
message: "No documented GLM CLI binary is registered. Refusing a stub that would claim to work. Use --backend auto, cursor-agent, or claude."
|
|
1229
|
+
};
|
|
534
1230
|
}
|
|
535
|
-
if (
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
);
|
|
1231
|
+
if (!isRequestedBackend(id)) {
|
|
1232
|
+
return {
|
|
1233
|
+
ok: false,
|
|
1234
|
+
message: `Unknown backend '${requested}'. Supported: ${listDetectBackendIds().join(", ")}.`
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
if (id === "auto") {
|
|
1238
|
+
for (const candidate of DETECT_ORDER) {
|
|
1239
|
+
const bin2 = await whichFn(candidate);
|
|
1240
|
+
if (bin2) return { ok: true, id: candidate, bin: bin2 };
|
|
544
1241
|
}
|
|
545
|
-
return {
|
|
1242
|
+
return {
|
|
1243
|
+
ok: false,
|
|
1244
|
+
message: [
|
|
1245
|
+
"No agent CLI found on PATH (tried: cursor-agent, claude).",
|
|
1246
|
+
INSTALL_HINTS["cursor-agent"],
|
|
1247
|
+
INSTALL_HINTS.claude
|
|
1248
|
+
].join(" ")
|
|
1249
|
+
};
|
|
546
1250
|
}
|
|
547
|
-
|
|
1251
|
+
const bin = await whichFn(BACKEND_BIN[id]);
|
|
1252
|
+
if (!bin) {
|
|
1253
|
+
return { ok: false, message: `${BACKEND_BIN[id]} not found on PATH. ${INSTALL_HINTS[id]}` };
|
|
1254
|
+
}
|
|
1255
|
+
return { ok: true, id, bin };
|
|
548
1256
|
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
1257
|
+
|
|
1258
|
+
// src/plan-loop/plan-state.ts
|
|
1259
|
+
import { readdir, readFile } from "fs/promises";
|
|
1260
|
+
import path2 from "path";
|
|
1261
|
+
function countPendingTodos(raw) {
|
|
1262
|
+
return parsePlanFrontmatter(raw).todos.filter(
|
|
1263
|
+
(t) => (t.status === "pending" || t.status === "in_progress") && t.id !== "dogfood-poc"
|
|
1264
|
+
).length;
|
|
1265
|
+
}
|
|
1266
|
+
async function findActivePlanFile(plansDir) {
|
|
1267
|
+
if (!await fileExists(plansDir)) return null;
|
|
1268
|
+
const files = (await readdir(plansDir)).filter((f) => f.endsWith(".plan.md")).sort();
|
|
1269
|
+
return files[0] ? path2.join(plansDir, files[0]) : null;
|
|
1270
|
+
}
|
|
1271
|
+
async function readPlan(planPath) {
|
|
1272
|
+
return readFile(planPath, "utf8");
|
|
1273
|
+
}
|
|
1274
|
+
var QUEUE_CURSOR_RE = /^- \*\*Queue cursor:\*\*\s*(.+)$/m;
|
|
1275
|
+
var QUEUE_STATUS_RE = /^- \*\*Queue status:\*\*\s*(.+)$/m;
|
|
1276
|
+
var QUEUE_DONE_STATUSES = /* @__PURE__ */ new Set(["exhausted", "completed", "done"]);
|
|
1277
|
+
function readRunQueueState(handoff) {
|
|
1278
|
+
const queue = extractHandoffNamedPlans(handoff).runQueue;
|
|
1279
|
+
let cursorIndex = null;
|
|
1280
|
+
let cursorPlan = null;
|
|
1281
|
+
const cursorRaw = QUEUE_CURSOR_RE.exec(handoff)?.[1]?.trim() ?? "";
|
|
1282
|
+
const indexMatch = /^(\d+)\b/.exec(cursorRaw);
|
|
1283
|
+
if (indexMatch?.[1]) cursorIndex = Number(indexMatch[1]);
|
|
1284
|
+
const currentMatch = /current:\s*`?([^`()]+?)`?\s*\)/i.exec(cursorRaw);
|
|
1285
|
+
if (currentMatch?.[1]) {
|
|
1286
|
+
const base = currentMatch[1].trim().split("/").pop() ?? "";
|
|
1287
|
+
if (/\.plan\.md$/i.test(base)) cursorPlan = base;
|
|
557
1288
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
case "system":
|
|
567
|
-
return [parseSystem(event)];
|
|
568
|
-
case "rate_limit_event":
|
|
569
|
-
return [parseRateLimit(event)];
|
|
570
|
-
case "tool_call":
|
|
571
|
-
return [parseCursorToolCall(event)];
|
|
572
|
-
default:
|
|
573
|
-
return [{ kind: "silent" }];
|
|
1289
|
+
const status = QUEUE_STATUS_RE.exec(handoff)?.[1]?.trim().split(/\s+/)[0]?.replace(/[`*]/g, "");
|
|
1290
|
+
const queueStatus = status ? status : null;
|
|
1291
|
+
const finished = queueStatus !== null && QUEUE_DONE_STATUSES.has(queueStatus.toLowerCase());
|
|
1292
|
+
let cursor = null;
|
|
1293
|
+
if (cursorIndex !== null && cursorIndex >= 0 && cursorIndex < queue.length) {
|
|
1294
|
+
cursor = cursorIndex;
|
|
1295
|
+
} else if (cursorPlan && queue.includes(cursorPlan)) {
|
|
1296
|
+
cursor = queue.indexOf(cursorPlan);
|
|
574
1297
|
}
|
|
1298
|
+
const current = cursor !== null ? queue[cursor] ?? null : cursorPlan;
|
|
1299
|
+
return { queue, cursor, current, status: queueStatus, finished };
|
|
575
1300
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
)(text)
|
|
588
|
-
);
|
|
1301
|
+
function defaultPlanStateIo() {
|
|
1302
|
+
return {
|
|
1303
|
+
readFile: async (file) => {
|
|
1304
|
+
try {
|
|
1305
|
+
return await readFile(file, "utf8");
|
|
1306
|
+
} catch {
|
|
1307
|
+
return null;
|
|
1308
|
+
}
|
|
1309
|
+
},
|
|
1310
|
+
findActivePlan: findActivePlanFile
|
|
1311
|
+
};
|
|
589
1312
|
}
|
|
590
|
-
function
|
|
591
|
-
|
|
592
|
-
|
|
1313
|
+
async function resolveActivePlanFromHandoff(root, handoff, io = defaultPlanStateIo()) {
|
|
1314
|
+
const queue = readRunQueueState(handoff);
|
|
1315
|
+
const base = (queue.queue.length > 0 && !queue.finished ? queue.current : null) ?? extractHandoffNamedPlans(handoff).active;
|
|
1316
|
+
if (!base) return io.findActivePlan(path2.join(root, ".cursor", "plans"));
|
|
1317
|
+
for (const candidate of namedPlanCandidatePaths(root, base)) {
|
|
1318
|
+
if (await io.readFile(candidate) !== null) return candidate;
|
|
1319
|
+
}
|
|
1320
|
+
return null;
|
|
593
1321
|
}
|
|
594
|
-
function
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
|
598
|
-
const minutes = Math.floor(seconds / 60);
|
|
599
|
-
const rest = Math.round(seconds - minutes * 60);
|
|
600
|
-
return `${minutes}m ${rest}s`;
|
|
1322
|
+
async function resolveActivePlanPath(root, io = defaultPlanStateIo()) {
|
|
1323
|
+
const handoff = await io.readFile(path2.join(root, HANDOFF_REL)) ?? "";
|
|
1324
|
+
return resolveActivePlanFromHandoff(root, handoff, io);
|
|
601
1325
|
}
|
|
602
|
-
|
|
603
|
-
|
|
1326
|
+
|
|
1327
|
+
// src/plan-loop/model-roles.ts
|
|
1328
|
+
var ROLE_CAPABILITIES = Object.freeze({
|
|
1329
|
+
claude: { workerModel: true, subworkerModel: true, reviewer: true },
|
|
1330
|
+
"cursor-agent": { workerModel: true, subworkerModel: false, reviewer: true },
|
|
1331
|
+
codex: { workerModel: true, subworkerModel: false, reviewer: false },
|
|
1332
|
+
openrouter: { workerModel: true, subworkerModel: false, reviewer: false },
|
|
1333
|
+
"cursor-acp": { workerModel: false, subworkerModel: false, reviewer: false },
|
|
1334
|
+
local: { workerModel: true, subworkerModel: false, reviewer: false }
|
|
1335
|
+
});
|
|
1336
|
+
var ROLE_MODEL_ID = /^[A-Za-z0-9._:/+=,[\]-]{1,128}$/;
|
|
1337
|
+
var ROLE_WORKER_TYPE_KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
1338
|
+
var SUBWORKER_AUTO = "auto";
|
|
1339
|
+
var REVIEWER_SCOPES = ["off", "tick", "plan"];
|
|
1340
|
+
var REVIEWER_BACKENDS = ["auto", "claude", "cursor-agent"];
|
|
1341
|
+
var CLAUDE_SUBAGENT_MODEL_ENV = "CLAUDE_CODE_SUBAGENT_MODEL";
|
|
1342
|
+
function isPlainObject(v) {
|
|
1343
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
604
1344
|
}
|
|
605
|
-
function
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
const line3 = truncate(oneLine(event.line), width - head.length - 3);
|
|
620
|
-
const text = line3 ? `${head} ${SPACE_MARKS.tick} ${line3}` : head;
|
|
621
|
-
return paint(event.ok ? LABEL_MUTED : STATUS_ERR, text, color);
|
|
1345
|
+
function modelField(v, where) {
|
|
1346
|
+
if (v === void 0 || v === null || v === "") return {};
|
|
1347
|
+
if (typeof v !== "string" || !ROLE_MODEL_ID.test(v.trim())) {
|
|
1348
|
+
return { error: `${where} must be a model id (letters, digits, . _ : / + = , [ ] -)` };
|
|
1349
|
+
}
|
|
1350
|
+
return { value: v.trim() };
|
|
1351
|
+
}
|
|
1352
|
+
function parseModelRoles(raw) {
|
|
1353
|
+
if (raw === void 0 || raw === null) return { ok: true, roles: {} };
|
|
1354
|
+
if (!isPlainObject(raw)) return { ok: false, error: "roles must be an object" };
|
|
1355
|
+
const roles = {};
|
|
1356
|
+
for (const key of Object.keys(raw)) {
|
|
1357
|
+
if (key !== "worker" && key !== "subworker" && key !== "reviewer") {
|
|
1358
|
+
return { ok: false, error: `unknown roles key: ${key}` };
|
|
622
1359
|
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
if (
|
|
629
|
-
|
|
1360
|
+
}
|
|
1361
|
+
if (raw.worker !== void 0 && raw.worker !== null) {
|
|
1362
|
+
const w = raw.worker;
|
|
1363
|
+
if (!isPlainObject(w)) return { ok: false, error: "roles.worker must be an object" };
|
|
1364
|
+
for (const key of Object.keys(w)) {
|
|
1365
|
+
if (key !== "backend" && key !== "model") {
|
|
1366
|
+
return { ok: false, error: `unknown roles.worker key: ${key}` };
|
|
630
1367
|
}
|
|
631
|
-
return paint(event.ok ? STATUS_OK : STATUS_ERR, parts.join(` ${SPACE_MARKS.tick} `), color);
|
|
632
1368
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
1369
|
+
const worker = {};
|
|
1370
|
+
if (w.backend !== void 0 && w.backend !== null && w.backend !== "") {
|
|
1371
|
+
const b = typeof w.backend === "string" ? w.backend.trim().toLowerCase() : "";
|
|
1372
|
+
if (!isRequestedBackend(b)) {
|
|
1373
|
+
return {
|
|
1374
|
+
ok: false,
|
|
1375
|
+
error: `roles.worker.backend must be auto or a kit backend id (got ${JSON.stringify(w.backend)})`
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
worker.backend = b;
|
|
640
1379
|
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
color
|
|
646
|
-
);
|
|
647
|
-
case "prompt":
|
|
648
|
-
return paint(
|
|
649
|
-
LABEL_MUTED,
|
|
650
|
-
`${SPACE_MARKS.tick} prompt sent ${SPACE_MARKS.tick} ${event.chars} chars`,
|
|
651
|
-
color
|
|
652
|
-
);
|
|
653
|
-
case "hitl_reply":
|
|
654
|
-
return paint(HELMET_ACCENT, truncate(`\u21A9 ${event.line}`, width), color);
|
|
655
|
-
default:
|
|
656
|
-
return null;
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
var StreamRenderer = class {
|
|
660
|
-
pending = "";
|
|
661
|
-
dropped = false;
|
|
662
|
-
textOpen = false;
|
|
663
|
-
decoder = new StringDecoder("utf8");
|
|
664
|
-
write;
|
|
665
|
-
color;
|
|
666
|
-
columns;
|
|
667
|
-
constructor(opts = {}) {
|
|
668
|
-
this.write = opts.write ?? ((text) => process.stdout.write(text));
|
|
669
|
-
this.color = shouldUseWelcomeColor({
|
|
670
|
-
stdoutIsTTY: opts.isTTY ?? Boolean(process.stdout.isTTY),
|
|
671
|
-
env: opts.env
|
|
672
|
-
});
|
|
673
|
-
this.columns = opts.columns ?? process.stdout.columns ?? 80;
|
|
1380
|
+
const m = modelField(w.model, "roles.worker.model");
|
|
1381
|
+
if (m.error) return { ok: false, error: m.error };
|
|
1382
|
+
if (m.value) worker.model = m.value;
|
|
1383
|
+
roles.worker = worker;
|
|
674
1384
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
this.pending = lines.pop() ?? "";
|
|
682
|
-
for (const line3 of lines) {
|
|
683
|
-
if (this.dropped) {
|
|
684
|
-
this.dropped = false;
|
|
685
|
-
continue;
|
|
686
|
-
}
|
|
687
|
-
this.renderLine(line3);
|
|
1385
|
+
if (raw.subworker !== void 0 && raw.subworker !== null) {
|
|
1386
|
+
const s = raw.subworker;
|
|
1387
|
+
if (!isPlainObject(s)) return { ok: false, error: "roles.subworker must be an object" };
|
|
1388
|
+
for (const key of Object.keys(s)) {
|
|
1389
|
+
if (key !== "model" && key !== "byWorkerType") {
|
|
1390
|
+
return { ok: false, error: `unknown roles.subworker key: ${key}` };
|
|
688
1391
|
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
1392
|
+
}
|
|
1393
|
+
const sub = {};
|
|
1394
|
+
const m = modelField(s.model, "roles.subworker.model");
|
|
1395
|
+
if (m.error) return { ok: false, error: m.error };
|
|
1396
|
+
if (m.value) sub.model = m.value;
|
|
1397
|
+
if (s.byWorkerType !== void 0 && s.byWorkerType !== null) {
|
|
1398
|
+
if (!isPlainObject(s.byWorkerType)) {
|
|
1399
|
+
return { ok: false, error: "roles.subworker.byWorkerType must be an object" };
|
|
692
1400
|
}
|
|
693
|
-
|
|
1401
|
+
const map = {};
|
|
1402
|
+
for (const [type, value] of Object.entries(s.byWorkerType)) {
|
|
1403
|
+
if (!ROLE_WORKER_TYPE_KEY.test(type)) {
|
|
1404
|
+
return {
|
|
1405
|
+
ok: false,
|
|
1406
|
+
error: `roles.subworker.byWorkerType key ${type} is not a worker_type`
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
const mv = modelField(value, `roles.subworker.byWorkerType.${type}`);
|
|
1410
|
+
if (mv.error) return { ok: false, error: mv.error };
|
|
1411
|
+
if (mv.value) map[type] = mv.value;
|
|
1412
|
+
}
|
|
1413
|
+
sub.byWorkerType = map;
|
|
694
1414
|
}
|
|
1415
|
+
roles.subworker = sub;
|
|
695
1416
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1417
|
+
if (raw.reviewer !== void 0 && raw.reviewer !== null) {
|
|
1418
|
+
const r = raw.reviewer;
|
|
1419
|
+
if (!isPlainObject(r)) return { ok: false, error: "roles.reviewer must be an object" };
|
|
1420
|
+
const reviewer = {};
|
|
1421
|
+
for (const key of Object.keys(r)) {
|
|
1422
|
+
if (!["enabled", "scope", "backend", "model", "advisorModel"].includes(key)) {
|
|
1423
|
+
return { ok: false, error: `unknown roles.reviewer key: ${key}` };
|
|
1424
|
+
}
|
|
704
1425
|
}
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
const rendered = renderStreamEvent(event, { color: this.color, columns: this.columns });
|
|
709
|
-
if (rendered === null) continue;
|
|
710
|
-
if (event.kind === "text") {
|
|
711
|
-
this.write(rendered);
|
|
712
|
-
this.textOpen = !rendered.endsWith("\n");
|
|
713
|
-
continue;
|
|
1426
|
+
if (r.enabled !== void 0 && r.enabled !== null) {
|
|
1427
|
+
if (typeof r.enabled !== "boolean") {
|
|
1428
|
+
return { ok: false, error: "roles.reviewer.enabled must be boolean" };
|
|
714
1429
|
}
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
1430
|
+
reviewer.enabled = r.enabled;
|
|
1431
|
+
}
|
|
1432
|
+
if (r.scope !== void 0 && r.scope !== null) {
|
|
1433
|
+
if (typeof r.scope !== "string" || !REVIEWER_SCOPES.includes(r.scope)) {
|
|
1434
|
+
return { ok: false, error: "roles.reviewer.scope must be off, tick, or plan" };
|
|
1435
|
+
}
|
|
1436
|
+
reviewer.scope = r.scope;
|
|
1437
|
+
}
|
|
1438
|
+
if (r.backend !== void 0 && r.backend !== null) {
|
|
1439
|
+
if (typeof r.backend !== "string" || !REVIEWER_BACKENDS.includes(r.backend)) {
|
|
1440
|
+
return { ok: false, error: "roles.reviewer.backend must be auto, claude, or cursor-agent" };
|
|
1441
|
+
}
|
|
1442
|
+
reviewer.backend = r.backend;
|
|
1443
|
+
}
|
|
1444
|
+
for (const key of ["model", "advisorModel"]) {
|
|
1445
|
+
const mv = modelField(r[key], `roles.reviewer.${key}`);
|
|
1446
|
+
if (mv.error) return { ok: false, error: mv.error };
|
|
1447
|
+
if (mv.value) reviewer[key] = mv.value;
|
|
718
1448
|
}
|
|
1449
|
+
roles.reviewer = reviewer;
|
|
719
1450
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
1451
|
+
return { ok: true, roles };
|
|
1452
|
+
}
|
|
1453
|
+
function frontmatterBlock(planText) {
|
|
1454
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(planText);
|
|
1455
|
+
return m?.[1] ?? null;
|
|
1456
|
+
}
|
|
1457
|
+
function unquote(v) {
|
|
1458
|
+
const t = v.trim();
|
|
1459
|
+
if (t.length >= 2 && (t[0] === '"' || t[0] === "'") && t[t.length - 1] === t[0]) {
|
|
1460
|
+
return t.slice(1, -1).trim();
|
|
724
1461
|
}
|
|
725
|
-
|
|
726
|
-
function createStreamRenderer(opts = {}) {
|
|
727
|
-
return new StreamRenderer(opts);
|
|
1462
|
+
return t;
|
|
728
1463
|
}
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
1464
|
+
function readPlanRoleOverrides(planText) {
|
|
1465
|
+
const block = frontmatterBlock(planText);
|
|
1466
|
+
if (!block) return {};
|
|
1467
|
+
const out = {};
|
|
1468
|
+
const top = (key) => {
|
|
1469
|
+
const m = new RegExp(`^${key}:[ \\t]*(.+)$`, "m").exec(block);
|
|
1470
|
+
const v = m?.[1] ? unquote(m[1]) : "";
|
|
1471
|
+
return v ? v : void 0;
|
|
1472
|
+
};
|
|
1473
|
+
const wb = top("worker_backend");
|
|
1474
|
+
if (wb) out.workerBackend = wb;
|
|
1475
|
+
const wm = top("worker_model");
|
|
1476
|
+
if (wm) out.workerModel = wm;
|
|
1477
|
+
const sm = top("subworker_model");
|
|
1478
|
+
if (sm) out.subworkerModel = sm;
|
|
1479
|
+
const items = block.split(/^\s*- id:/m).slice(1);
|
|
1480
|
+
for (const item of items) {
|
|
1481
|
+
const status = /^\s*status:\s*(\S+)/m.exec(item)?.[1];
|
|
1482
|
+
if (status !== "pending" && status !== "in_progress") continue;
|
|
1483
|
+
if (unquote(item.split("\n")[0] ?? "") === "dogfood-poc") continue;
|
|
1484
|
+
const type = /^\s*worker_type:\s*(.+)$/m.exec(item)?.[1];
|
|
1485
|
+
if (type) out.nextWorkerType = unquote(type);
|
|
1486
|
+
break;
|
|
1487
|
+
}
|
|
1488
|
+
return out;
|
|
738
1489
|
}
|
|
739
|
-
var
|
|
740
|
-
function
|
|
1490
|
+
var RANK = { flag: 3, plan: 2, config: 1, default: 0 };
|
|
1491
|
+
function resolveWorkerRole(input) {
|
|
1492
|
+
const warnings = [];
|
|
1493
|
+
const layers = [
|
|
1494
|
+
{
|
|
1495
|
+
source: "flag",
|
|
1496
|
+
backend: input.flagBackend?.trim() || void 0,
|
|
1497
|
+
model: input.flagModel?.trim() || void 0
|
|
1498
|
+
},
|
|
1499
|
+
{ source: "plan", backend: input.plan?.workerBackend, model: input.plan?.workerModel },
|
|
1500
|
+
{ source: "config", backend: input.roles?.worker?.backend, model: input.roles?.worker?.model },
|
|
1501
|
+
{ source: "default", backend: input.defaultBackend }
|
|
1502
|
+
];
|
|
1503
|
+
const bLayer = layers.find((l) => l.backend) ?? {
|
|
1504
|
+
source: "default",
|
|
1505
|
+
backend: input.defaultBackend
|
|
1506
|
+
};
|
|
1507
|
+
const backend = bLayer.backend.trim().toLowerCase();
|
|
1508
|
+
let model;
|
|
1509
|
+
let modelSource;
|
|
1510
|
+
for (const l of layers) {
|
|
1511
|
+
if (!l.model) continue;
|
|
1512
|
+
if (RANK[l.source] < RANK[bLayer.source]) {
|
|
1513
|
+
warnings.push(
|
|
1514
|
+
`${l.source} model ${l.model} ignored: the backend ${backend} came from the ${bLayer.source} layer, and a model only applies to its own backend or a lower layer's`
|
|
1515
|
+
);
|
|
1516
|
+
break;
|
|
1517
|
+
}
|
|
1518
|
+
model = l.model;
|
|
1519
|
+
modelSource = l.source;
|
|
1520
|
+
break;
|
|
1521
|
+
}
|
|
1522
|
+
if (model && modelSource !== "flag" && isBackendId(backend) && !ROLE_CAPABILITIES[backend].workerModel) {
|
|
1523
|
+
warnings.push(
|
|
1524
|
+
`${modelSource} model ${model} ignored: ${backend} cannot select a model (docs/model-roles-capability-matrix.md)`
|
|
1525
|
+
);
|
|
1526
|
+
model = void 0;
|
|
1527
|
+
modelSource = void 0;
|
|
1528
|
+
}
|
|
741
1529
|
return {
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
1530
|
+
backend,
|
|
1531
|
+
...model ? { model, modelSource } : {},
|
|
1532
|
+
backendSource: bLayer.source,
|
|
1533
|
+
warnings
|
|
745
1534
|
};
|
|
746
1535
|
}
|
|
747
|
-
function
|
|
748
|
-
const
|
|
749
|
-
const
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
if (
|
|
753
|
-
|
|
1536
|
+
function resolveSubworkerModel(input) {
|
|
1537
|
+
const sub = input.roles?.subworker;
|
|
1538
|
+
const type = input.plan?.nextWorkerType;
|
|
1539
|
+
let model;
|
|
1540
|
+
let source;
|
|
1541
|
+
if (input.plan?.subworkerModel) {
|
|
1542
|
+
model = input.plan.subworkerModel;
|
|
1543
|
+
source = "plan";
|
|
1544
|
+
} else if (type && sub?.byWorkerType?.[type]) {
|
|
1545
|
+
model = sub.byWorkerType[type];
|
|
1546
|
+
source = "worker_type";
|
|
1547
|
+
} else if (sub?.model) {
|
|
1548
|
+
model = sub.model;
|
|
1549
|
+
source = "config";
|
|
754
1550
|
}
|
|
755
|
-
|
|
1551
|
+
if (!model) return {};
|
|
1552
|
+
if (model === SUBWORKER_AUTO) {
|
|
1553
|
+
return {
|
|
1554
|
+
warning: "subworker model auto is reserved and not implemented yet (auto tier routing); no subworker model set"
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
if (!ROLE_MODEL_ID.test(model)) {
|
|
1558
|
+
return {
|
|
1559
|
+
warning: `subworker model ${JSON.stringify(model)} is not a model id; no subworker model set`
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
if (!ROLE_CAPABILITIES[input.backend].subworkerModel) {
|
|
1563
|
+
const how = input.backend === "cursor-agent" ? "Cursor subagents follow the worker model (model: inherit)" : "subagents keep the backend default";
|
|
1564
|
+
return {
|
|
1565
|
+
warning: `subworker model ${model} is not supported on ${input.backend}; ${how} (docs/model-roles-capability-matrix.md)`
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
return { model, source };
|
|
756
1569
|
}
|
|
757
|
-
function
|
|
758
|
-
const
|
|
759
|
-
const
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
1570
|
+
function describeResolvedRoles(input) {
|
|
1571
|
+
const model = input.model ? `${input.model} (${input.modelSource ?? "flag"})` : "backend default";
|
|
1572
|
+
const sub = input.subworker?.model ? `, subworker ${input.subworker.model} (${input.subworker.source})` : "";
|
|
1573
|
+
return `roles: worker ${input.backendId} (${input.backendSource}), model ${model}${sub}`;
|
|
1574
|
+
}
|
|
1575
|
+
function resolveReviewerRole(roles, externalPlanReview) {
|
|
1576
|
+
const r = roles?.reviewer;
|
|
1577
|
+
const legacyOn = isPlainObject(externalPlanReview) && externalPlanReview.enabled === true;
|
|
1578
|
+
const fields = {
|
|
1579
|
+
...r?.backend ? { backend: r.backend } : {},
|
|
1580
|
+
...r?.model ? { model: r.model } : {},
|
|
1581
|
+
...r?.advisorModel ? { advisorModel: r.advisorModel } : {}
|
|
1582
|
+
};
|
|
1583
|
+
if (r?.enabled === false || r?.scope === "off") {
|
|
1584
|
+
return { scope: "off", source: "roles", ...fields };
|
|
1585
|
+
}
|
|
1586
|
+
const on = r?.enabled === true || legacyOn;
|
|
1587
|
+
const source = r?.enabled === true ? "roles" : legacyOn ? "externalPlanReview" : "default";
|
|
1588
|
+
if (!on) return { scope: "off", source, ...fields };
|
|
1589
|
+
return { scope: r?.scope ?? "plan", source, ...fields };
|
|
1590
|
+
}
|
|
1591
|
+
function normalizeReviewModelId(raw) {
|
|
1592
|
+
const id = (raw ?? "").toLowerCase().replace(/\s+/g, "").replace(/\[.*$/, "");
|
|
1593
|
+
if (id === "" || id === "auto" || id === "cursor-auto" || id === "cursorauto" || id === "default")
|
|
1594
|
+
return "auto";
|
|
1595
|
+
return id;
|
|
1596
|
+
}
|
|
1597
|
+
var FAMILY_PATTERNS = [
|
|
1598
|
+
[
|
|
1599
|
+
"haiku",
|
|
1600
|
+
/^(haiku|claude-haiku|claude-3-haiku.*|claude-3\.5-haiku.*|claude-3-5-haiku.*|claude-haiku-.*|claude-4-haiku.*|claude-4\.5-haiku.*)$/
|
|
1601
|
+
],
|
|
1602
|
+
[
|
|
1603
|
+
"opus",
|
|
1604
|
+
/^(opus|claude-opus|claude-3-opus.*|claude-opus-.*|claude-4-opus.*|claude-4\.5-opus.*)$/
|
|
1605
|
+
],
|
|
1606
|
+
[
|
|
1607
|
+
"sonnet",
|
|
1608
|
+
/^(sonnet|claude-sonnet|claude-3-sonnet.*|claude-3\.5-sonnet.*|claude-3-5-sonnet.*|claude-3-7-sonnet.*|claude-sonnet-.*|claude-4-sonnet.*|claude-4\.5-sonnet.*)$/
|
|
1609
|
+
],
|
|
1610
|
+
["fable", /^(fable|claude-fable|claude-fable-.*)$/],
|
|
1611
|
+
["composer", /^(composer|composer-.*|cursor-composer.*)$/],
|
|
1612
|
+
["grok", /^(grok|grok-.*)$/]
|
|
1613
|
+
];
|
|
1614
|
+
function reviewModelFamily(raw) {
|
|
1615
|
+
const id = normalizeReviewModelId(raw);
|
|
1616
|
+
for (const [family, pattern] of FAMILY_PATTERNS) if (pattern.test(id)) return family;
|
|
1617
|
+
return id;
|
|
1618
|
+
}
|
|
1619
|
+
function isFamilyAlias(id, family) {
|
|
1620
|
+
return id === family || id === `claude-${family}` || id === `cursor-${family}`;
|
|
1621
|
+
}
|
|
1622
|
+
function reviewModelRelation(implementer, reviewer) {
|
|
1623
|
+
const a = normalizeReviewModelId(implementer);
|
|
1624
|
+
const b = normalizeReviewModelId(reviewer);
|
|
1625
|
+
if (a === b) return "identical";
|
|
1626
|
+
const fa = reviewModelFamily(a);
|
|
1627
|
+
const fb = reviewModelFamily(b);
|
|
1628
|
+
if (fa !== fb) return "different";
|
|
1629
|
+
if (isFamilyAlias(a, fa) || isFamilyAlias(b, fb)) return "identical";
|
|
1630
|
+
return "same-family";
|
|
1631
|
+
}
|
|
1632
|
+
function describeIdenticalReviewModel(implementer, reviewer) {
|
|
1633
|
+
return `reviewer model ${reviewer} is the implementer model (${implementer}): identical-model review is refused, Auto/Auto and a family alias against an id of that family included. This is not a silent self-review; set roles.reviewer.model to a different model`;
|
|
1634
|
+
}
|
|
1635
|
+
function describeSameFamilyReviewModel(implementer, reviewer) {
|
|
1636
|
+
return `reviewer model ${reviewer} and implementer model ${implementer} are the same family (${reviewModelFamily(reviewer)}): the review runs, as a second read by a different model of one family`;
|
|
1637
|
+
}
|
|
1638
|
+
function resolveReviewJobRole(input) {
|
|
1639
|
+
const flagBackend = input.flagBackend?.trim() ?? "";
|
|
1640
|
+
const flagModel = input.flagModel?.trim() ?? "";
|
|
1641
|
+
const reviewer = input.roles?.reviewer;
|
|
1642
|
+
const backend = flagBackend || reviewer?.backend || "auto";
|
|
1643
|
+
const backendSource = flagBackend ? "flag" : reviewer?.backend ? "config" : "default";
|
|
1644
|
+
const model = flagModel || (flagBackend ? "" : reviewer?.model ?? "");
|
|
1645
|
+
const out = {
|
|
1646
|
+
backend,
|
|
1647
|
+
backendSource,
|
|
1648
|
+
...model ? { model, modelSource: flagModel ? "flag" : "config" } : {}
|
|
1649
|
+
};
|
|
1650
|
+
const implementer = input.roles?.worker?.model;
|
|
1651
|
+
if (model && implementer) {
|
|
1652
|
+
const relation = reviewModelRelation(implementer, model);
|
|
1653
|
+
if (relation === "identical") out.refusal = describeIdenticalReviewModel(implementer, model);
|
|
1654
|
+
else if (relation === "same-family") {
|
|
1655
|
+
out.warning = describeSameFamilyReviewModel(implementer, model);
|
|
1656
|
+
}
|
|
768
1657
|
}
|
|
769
1658
|
return out;
|
|
770
1659
|
}
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
const
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
const abort = new AbortController();
|
|
782
|
-
if (opts.model) say("cursor-acp: --model is not sent over ACP; the agent's default model runs.");
|
|
783
|
-
say("cursor tick: cursor-agent acp (JSON-RPC stdio, HITL relay, tool permissions allow-once).");
|
|
784
|
-
const out = createWriteStream(opts.logPath, { flags: "w" });
|
|
785
|
-
let logError = null;
|
|
786
|
-
out.on("error", (err) => {
|
|
787
|
-
logError = err;
|
|
788
|
-
});
|
|
789
|
-
const logLine = (text) => out.write(`${redactSecrets(text, redact)}
|
|
790
|
-
`);
|
|
791
|
-
const child = spawnFn("cursor-agent", cursorAcpArgs(), {
|
|
792
|
-
cwd: opts.workspace,
|
|
793
|
-
env,
|
|
794
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
795
|
-
});
|
|
796
|
-
const pending = /* @__PURE__ */ new Map();
|
|
797
|
-
let closed = false;
|
|
798
|
-
let exitCode = null;
|
|
799
|
-
let spawnError = null;
|
|
800
|
-
let resolveClosed = () => {
|
|
801
|
-
};
|
|
802
|
-
const closedPromise = new Promise((resolve) => {
|
|
803
|
-
resolveClosed = resolve;
|
|
804
|
-
});
|
|
805
|
-
const gone = (code2) => {
|
|
806
|
-
if (closed) return;
|
|
807
|
-
closed = true;
|
|
808
|
-
exitCode = code2;
|
|
809
|
-
abort.abort();
|
|
810
|
-
for (const p of pending.values()) {
|
|
811
|
-
p.reject({ message: `cursor-agent acp exited (code ${code2 ?? "signal"})` });
|
|
1660
|
+
function checkPlanRoleOverrides(plan) {
|
|
1661
|
+
if (plan.workerBackend && !isRequestedBackend(plan.workerBackend.toLowerCase())) {
|
|
1662
|
+
return `plan frontmatter worker_backend must be auto or a kit backend id (got ${JSON.stringify(plan.workerBackend)})`;
|
|
1663
|
+
}
|
|
1664
|
+
for (const [key, value] of [
|
|
1665
|
+
["worker_model", plan.workerModel],
|
|
1666
|
+
["subworker_model", plan.subworkerModel]
|
|
1667
|
+
]) {
|
|
1668
|
+
if (value && !ROLE_MODEL_ID.test(value)) {
|
|
1669
|
+
return `plan frontmatter ${key} must be a model id (got ${JSON.stringify(value)})`;
|
|
812
1670
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
try {
|
|
828
|
-
child.stdin?.write(`${text}
|
|
829
|
-
`);
|
|
830
|
-
} catch {
|
|
1671
|
+
}
|
|
1672
|
+
return null;
|
|
1673
|
+
}
|
|
1674
|
+
async function loadRolesContext(root, usePlan) {
|
|
1675
|
+
const config = await loadContextConfig(root);
|
|
1676
|
+
const parsed = parseModelRoles(config?.roles);
|
|
1677
|
+
if (!parsed.ok) return { ok: false, error: `.cursor/context/config.json: ${parsed.error}` };
|
|
1678
|
+
let plan = {};
|
|
1679
|
+
if (usePlan) {
|
|
1680
|
+
const planPath = await resolveActivePlanPath(root);
|
|
1681
|
+
if (planPath) {
|
|
1682
|
+
plan = readPlanRoleOverrides(await readPlan(planPath).catch(() => ""));
|
|
1683
|
+
const problem = checkPlanRoleOverrides(plan);
|
|
1684
|
+
if (problem) return { ok: false, error: `${planPath}: ${problem}` };
|
|
831
1685
|
}
|
|
1686
|
+
}
|
|
1687
|
+
return {
|
|
1688
|
+
ok: true,
|
|
1689
|
+
roles: parsed.roles,
|
|
1690
|
+
plan,
|
|
1691
|
+
reviewer: resolveReviewerRole(parsed.roles, config?.externalPlanReview)
|
|
832
1692
|
};
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// src/plan-loop/local.ts
|
|
1696
|
+
var LOCAL_PROVIDER = "agent-kit-local";
|
|
1697
|
+
var LOCAL_PLACEHOLDER_KEY = "agent-kit-local-no-key";
|
|
1698
|
+
var LOCAL_DEFAULT_CONTEXT_WINDOW = 32768;
|
|
1699
|
+
var LOCAL_DEFAULT_MAX_TOKENS = 8192;
|
|
1700
|
+
var OMARCHY_START_TIMEOUT_MS = 10 * 6e4;
|
|
1701
|
+
var OMARCHY_OVERLAY_TIMEOUT_MS = 3e4;
|
|
1702
|
+
var OMARCHY_STATUS_TIMEOUT_MS = 1e4;
|
|
1703
|
+
var LOADING_HEARTBEAT_MS = 5e3;
|
|
1704
|
+
var STATUS_POLL_MS = 2e3;
|
|
1705
|
+
var OMARCHY_RECIPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1706
|
+
var modelsHint = "List the models on this machine with `agent-kit models`.";
|
|
1707
|
+
function parseLocalModelId(raw) {
|
|
1708
|
+
const id = (raw ?? "").trim();
|
|
1709
|
+
const sources = LOCAL_MODEL_SOURCES.join(", ");
|
|
1710
|
+
if (!id) {
|
|
1711
|
+
return {
|
|
1712
|
+
ok: false,
|
|
1713
|
+
message: `local backend: --model <source>:<id> is required (sources: ${sources}). ${modelsHint}`
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
const colon = id.indexOf(":");
|
|
1717
|
+
const source = colon > 0 ? id.slice(0, colon) : "";
|
|
1718
|
+
const sourceId = colon > 0 ? id.slice(colon + 1) : "";
|
|
1719
|
+
if (!LOCAL_MODEL_SOURCES.includes(source) || !sourceId) {
|
|
1720
|
+
return {
|
|
1721
|
+
ok: false,
|
|
1722
|
+
message: `local backend: model ${JSON.stringify(id)} is not <source>:<id> with a source among ${sources}. ${modelsHint}`
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
if (!ROLE_MODEL_ID.test(id)) {
|
|
1726
|
+
return {
|
|
1727
|
+
ok: false,
|
|
1728
|
+
message: `local backend: model ${JSON.stringify(id)} has characters the kit does not pass to a model (allowed: letters, digits and . _ : / + = , [ ] -, at most 128). Give the model a plain name in its server, then pick it from \`agent-kit models\`.`
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
if (source === "omarchy" && !OMARCHY_RECIPE.test(sourceId)) {
|
|
1732
|
+
return {
|
|
1733
|
+
ok: false,
|
|
1734
|
+
message: `local backend: ${JSON.stringify(id)} is not an Omarchy recipe on this machine (a model shared by another host is out of scope). ${modelsHint}`
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
return { ok: true, id, source, sourceId };
|
|
1738
|
+
}
|
|
1739
|
+
function findRunnableLocalModel(id, report) {
|
|
1740
|
+
const model = report.models.find((m) => m.id === id);
|
|
1741
|
+
if (!model) {
|
|
1742
|
+
const listed = report.models.map((m) => m.id);
|
|
1743
|
+
return {
|
|
1744
|
+
ok: false,
|
|
1745
|
+
message: `local backend: ${id} is not listed on this machine (${listed.length > 0 ? `listed: ${listed.join(", ")}` : "no local text models found"}). ${modelsHint} The kit does not fall back to another engine.`
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
if (!model.runnable) {
|
|
1749
|
+
return {
|
|
1750
|
+
ok: false,
|
|
1751
|
+
message: `local backend: ${id} is not runnable (${model.reason ?? model.state}). ${modelsHint} The kit does not fall back to another engine.`
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
return { ok: true, model };
|
|
1755
|
+
}
|
|
1756
|
+
function localProviderSource(model, sourceId) {
|
|
1757
|
+
const config = {
|
|
1758
|
+
name: "Agent Kit local model",
|
|
1759
|
+
baseUrl: model.endpoint,
|
|
1760
|
+
apiKey: LOCAL_PLACEHOLDER_KEY,
|
|
1761
|
+
api: "openai-completions",
|
|
1762
|
+
models: [
|
|
1763
|
+
{
|
|
1764
|
+
type: "chat",
|
|
1765
|
+
id: sourceId,
|
|
1766
|
+
name: model.label,
|
|
1767
|
+
reasoning: false,
|
|
1768
|
+
input: ["text"],
|
|
1769
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
1770
|
+
contextWindow: model.contextWindow ?? LOCAL_DEFAULT_CONTEXT_WINDOW,
|
|
1771
|
+
maxTokens: LOCAL_DEFAULT_MAX_TOKENS
|
|
1772
|
+
}
|
|
1773
|
+
]
|
|
857
1774
|
};
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
1775
|
+
return [
|
|
1776
|
+
"// Generated by agent-kit for one local-model tick (ADR 2026-11-28_local-model-backend-pi point 6); removed when the tick ends.",
|
|
1777
|
+
`const config = ${JSON.stringify(config, null, 2)};`,
|
|
1778
|
+
"export default function (pi) {",
|
|
1779
|
+
` pi.registerProvider(${JSON.stringify(LOCAL_PROVIDER)}, config);`,
|
|
1780
|
+
"}",
|
|
1781
|
+
""
|
|
1782
|
+
].join("\n");
|
|
1783
|
+
}
|
|
1784
|
+
function execFailure(what, run, timeoutMs) {
|
|
1785
|
+
if (run.reason === "missing") return `${what}: omarchy-models not on PATH`;
|
|
1786
|
+
if (run.reason === "timeout")
|
|
1787
|
+
return `${what}: no answer within ${Math.round(timeoutMs / 1e3)} s`;
|
|
1788
|
+
return `${what} failed${run.detail ? `: ${run.detail}` : ""}`;
|
|
1789
|
+
}
|
|
1790
|
+
async function startOmarchyRecipe(bin, model, recipe, deps, progress) {
|
|
1791
|
+
const exec = deps.execFn ?? defaultExecFn;
|
|
1792
|
+
const now = deps.now ?? Date.now;
|
|
1793
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1794
|
+
const timeoutMs = deps.startTimeoutMs ?? OMARCHY_START_TIMEOUT_MS;
|
|
1795
|
+
const t0 = now();
|
|
1796
|
+
const report = (phase, detail) => progress({
|
|
1797
|
+
kind: "model_loading",
|
|
1798
|
+
model: model.id,
|
|
1799
|
+
phase,
|
|
1800
|
+
elapsedMs: now() - t0,
|
|
1801
|
+
...detail ? { detail } : {}
|
|
1802
|
+
});
|
|
1803
|
+
report("starting");
|
|
1804
|
+
const heartbeat = setInterval(() => report("loading"), deps.heartbeatMs ?? LOADING_HEARTBEAT_MS);
|
|
1805
|
+
heartbeat.unref?.();
|
|
1806
|
+
try {
|
|
1807
|
+
const started = await exec(bin, ["start", recipe], timeoutMs);
|
|
1808
|
+
if (!started.ok)
|
|
1809
|
+
throw new Error(execFailure(`omarchy-models start ${recipe}`, started, timeoutMs));
|
|
1810
|
+
for (; ; ) {
|
|
1811
|
+
const status = await exec(bin, ["status", "--json"], OMARCHY_STATUS_TIMEOUT_MS);
|
|
1812
|
+
if (status.ok) {
|
|
1813
|
+
let state;
|
|
1814
|
+
try {
|
|
1815
|
+
state = parseOmarchyStatus(JSON.parse(status.stdout)).models.find(
|
|
1816
|
+
(m) => m.id === model.id
|
|
1817
|
+
)?.state;
|
|
1818
|
+
} catch {
|
|
1819
|
+
state = void 0;
|
|
1820
|
+
}
|
|
1821
|
+
if (state === "running") break;
|
|
1822
|
+
if (state === "not-fit") throw new Error(`${model.id} does not fit this machine now`);
|
|
871
1823
|
}
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
`
|
|
875
|
-
const n = /(?:operator reply|policy pre-answer) (\d+)/.exec(outcome.stamp.reply)?.[1];
|
|
876
|
-
const option = n ? q.options[Number(n) - 1] : void 0;
|
|
877
|
-
if (!option) {
|
|
878
|
-
hitl.write(
|
|
879
|
-
"cursor-acp: a free-text answer has no cursor/ask_question option; the question is answered as cancelled.\n"
|
|
1824
|
+
if (now() - t0 >= timeoutMs) {
|
|
1825
|
+
throw new Error(
|
|
1826
|
+
`${model.id} did not report running within ${Math.round(timeoutMs / 1e3)} s`
|
|
880
1827
|
);
|
|
881
|
-
respond(id, { outcome: { outcome: "cancelled" } });
|
|
882
|
-
return;
|
|
883
1828
|
}
|
|
884
|
-
|
|
885
|
-
}
|
|
886
|
-
if (record.stop) {
|
|
887
|
-
respond(id, { outcome: { outcome: "cancelled" } });
|
|
888
|
-
cancelSession();
|
|
889
|
-
return;
|
|
890
|
-
}
|
|
891
|
-
respond(id, { outcome: { outcome: "answered", answers } });
|
|
892
|
-
};
|
|
893
|
-
const handleRequest = (msg) => {
|
|
894
|
-
const { id, method, params } = msg;
|
|
895
|
-
if (method === "session/request_permission") {
|
|
896
|
-
respond(id, acpPermissionOutcome(params));
|
|
897
|
-
return;
|
|
1829
|
+
await sleep(deps.pollMs ?? STATUS_POLL_MS);
|
|
898
1830
|
}
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
1831
|
+
report("ready");
|
|
1832
|
+
} catch (err) {
|
|
1833
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1834
|
+
report("failed", detail);
|
|
1835
|
+
throw new Error(`local backend: ${detail}. The kit does not fall back to another engine.`);
|
|
1836
|
+
} finally {
|
|
1837
|
+
clearInterval(heartbeat);
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
async function prepareLocalProvider(model, parsed, deps = {}, progress = () => {
|
|
1841
|
+
}) {
|
|
1842
|
+
if (!isLoopbackUrl(model.endpoint)) {
|
|
1843
|
+
throw new Error(`local backend: ${model.id} is not served from a loopback address`);
|
|
1844
|
+
}
|
|
1845
|
+
if (parsed.source === "omarchy") {
|
|
1846
|
+
const bin = await (deps.whichFn ?? whichBinary)("omarchy-models");
|
|
1847
|
+
if (!bin) throw new Error("local backend: omarchy-models not on PATH");
|
|
1848
|
+
if (model.state === "stopped") {
|
|
1849
|
+
await startOmarchyRecipe(bin, model, parsed.sourceId, deps, progress);
|
|
902
1850
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
if (update.sessionUpdate === "agent_message_chunk") {
|
|
910
|
-
const content = isRecord3(update.content) ? update.content : null;
|
|
911
|
-
if (content?.type === "text" && typeof content.text === "string") turnText += content.text;
|
|
912
|
-
return;
|
|
1851
|
+
const exec = deps.execFn ?? defaultExecFn;
|
|
1852
|
+
const run = await exec(bin, ["overlay", "pi", parsed.sourceId], OMARCHY_OVERLAY_TIMEOUT_MS);
|
|
1853
|
+
if (!run.ok) {
|
|
1854
|
+
throw new Error(
|
|
1855
|
+
`local backend: ${execFailure(`omarchy-models overlay pi ${parsed.sourceId}`, run, OMARCHY_OVERLAY_TIMEOUT_MS)}`
|
|
1856
|
+
);
|
|
913
1857
|
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
message: {
|
|
920
|
-
content: [
|
|
921
|
-
{
|
|
922
|
-
type: "tool_use",
|
|
923
|
-
name: typeof update.kind === "string" ? update.kind : "tool",
|
|
924
|
-
input: { title }
|
|
925
|
-
}
|
|
926
|
-
]
|
|
927
|
-
}
|
|
928
|
-
})
|
|
1858
|
+
const lines = run.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
1859
|
+
const [extension, provider, piModel] = lines;
|
|
1860
|
+
if (lines.length !== 3 || !extension || !provider || !piModel || !path3.isAbsolute(extension)) {
|
|
1861
|
+
throw new Error(
|
|
1862
|
+
`local backend: omarchy-models overlay pi ${parsed.sourceId} did not print an extension path, a provider and a model (got ${lines.length} line(s))`
|
|
929
1863
|
);
|
|
930
1864
|
}
|
|
1865
|
+
return withTempDir(deps, async () => ({ extensions: [extension], provider, model: piModel }));
|
|
1866
|
+
}
|
|
1867
|
+
return withTempDir(deps, async (dir) => {
|
|
1868
|
+
const file = path3.join(dir, "provider.ts");
|
|
1869
|
+
await writeFile(file, localProviderSource(model, parsed.sourceId), { mode: 384 });
|
|
1870
|
+
return { extensions: [file], provider: LOCAL_PROVIDER, model: parsed.sourceId };
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
async function withTempDir(deps, fill) {
|
|
1874
|
+
const dir = await mkdtemp(path3.join(deps.tmpRoot ?? tmpdir(), "agent-kit-local-"));
|
|
1875
|
+
try {
|
|
1876
|
+
const agentDir = path3.join(dir, "pi-agent");
|
|
1877
|
+
await mkdir(agentDir, { mode: 448 });
|
|
1878
|
+
return { ...await fill(dir), tempDir: dir, agentDir };
|
|
1879
|
+
} catch (err) {
|
|
1880
|
+
await rm(dir, { recursive: true, force: true });
|
|
1881
|
+
throw err;
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
async function cleanupLocalProvider(setup) {
|
|
1885
|
+
if (!setup.tempDir) return;
|
|
1886
|
+
await rm(setup.tempDir, { recursive: true, force: true }).catch(() => void 0);
|
|
1887
|
+
}
|
|
1888
|
+
function localPiArgs(setup) {
|
|
1889
|
+
return [
|
|
1890
|
+
"--mode",
|
|
1891
|
+
"rpc",
|
|
1892
|
+
"--no-session",
|
|
1893
|
+
"--offline",
|
|
1894
|
+
"--no-extensions",
|
|
1895
|
+
...setup.extensions.flatMap((file) => ["--extension", file]),
|
|
1896
|
+
"--no-skills",
|
|
1897
|
+
"--no-prompt-templates",
|
|
1898
|
+
"--no-approve",
|
|
1899
|
+
"--provider",
|
|
1900
|
+
setup.provider,
|
|
1901
|
+
"--model",
|
|
1902
|
+
setup.model
|
|
1903
|
+
];
|
|
1904
|
+
}
|
|
1905
|
+
function localChildEnv(overrides, agentDir) {
|
|
1906
|
+
return {
|
|
1907
|
+
...mergeChildEnv(overrides),
|
|
1908
|
+
PI_OFFLINE: "1",
|
|
1909
|
+
PI_SKIP_VERSION_CHECK: "1",
|
|
1910
|
+
PI_TELEMETRY: "0",
|
|
1911
|
+
...agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}
|
|
931
1912
|
};
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
1913
|
+
}
|
|
1914
|
+
function piRpcPromptLine(text) {
|
|
1915
|
+
return `${JSON.stringify({ type: "prompt", message: text })}
|
|
1916
|
+
`;
|
|
1917
|
+
}
|
|
1918
|
+
function piSlashPointer(name) {
|
|
1919
|
+
return [
|
|
1920
|
+
`Read \`.cursor/commands/${name}.md\` now and follow that contract exactly \u2014 it is the source of truth for /${name}; this paragraph is only a thin adapter for pi (local model, headless).`,
|
|
1921
|
+
"",
|
|
1922
|
+
"Adapter rules (pi, headless):",
|
|
1923
|
+
"- Ask questions is unavailable here: print one line `HITL_GATE: <ask-id> | <label 1> | <label 2> | ...` immediately followed by the same labels as one numbered list, one list per message, then end your turn and WAIT for the answer (ask-id and labels: `.cursor/skills/core/hitl-gates/SKILL.md`). The answer arrives as your next prompt, `HITL_REPLY: <ask-id> | operator reply <n> | <label>`; cite that line as the Ask provenance.",
|
|
1924
|
+
"- Skip or cancel means stop.",
|
|
1925
|
+
"- Never `/git-prod` without an explicit operator yes.",
|
|
1926
|
+
"- Do not clone Cursor hooks or invent behavior beyond the SoT file."
|
|
1927
|
+
].join("\n");
|
|
1928
|
+
}
|
|
1929
|
+
var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1930
|
+
var line3 = (event) => JSON.stringify(event);
|
|
1931
|
+
var num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
|
|
1932
|
+
function messageText(content) {
|
|
1933
|
+
if (typeof content === "string") return content;
|
|
1934
|
+
if (!Array.isArray(content)) return "";
|
|
1935
|
+
return content.filter((c) => isRecord4(c) && c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
|
|
1936
|
+
}
|
|
1937
|
+
function createPiTranslator(opts) {
|
|
1938
|
+
const sessionId = opts.sessionId ?? `pi-${randomUUID()}`;
|
|
1939
|
+
let started = false;
|
|
1940
|
+
let lastText = "";
|
|
1941
|
+
let lastError = null;
|
|
1942
|
+
let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
1943
|
+
const result = (error) => {
|
|
1944
|
+
const out = line3({
|
|
1945
|
+
type: "result",
|
|
1946
|
+
subtype: error ? "error_during_execution" : "success",
|
|
1947
|
+
is_error: error !== null,
|
|
1948
|
+
result: lastText,
|
|
1949
|
+
session_id: sessionId,
|
|
1950
|
+
usage: {
|
|
1951
|
+
input_tokens: usage.input,
|
|
1952
|
+
output_tokens: usage.output,
|
|
1953
|
+
cache_read_input_tokens: usage.cacheRead,
|
|
1954
|
+
cache_creation_input_tokens: usage.cacheWrite
|
|
1955
|
+
},
|
|
1956
|
+
...error ? { errors: [error] } : {}
|
|
1957
|
+
});
|
|
1958
|
+
lastText = "";
|
|
1959
|
+
lastError = null;
|
|
1960
|
+
usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
1961
|
+
return out;
|
|
960
1962
|
};
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
const errBuffer = new RedactingStreamBuffer(redact);
|
|
967
|
-
child.stderr?.on("data", (chunk) => {
|
|
968
|
-
const text = redact.length ? errBuffer.push(chunk) : String(chunk);
|
|
969
|
-
if (text) out.write(text);
|
|
970
|
-
});
|
|
971
|
-
child.stdin?.on("error", () => {
|
|
972
|
-
});
|
|
973
|
-
let stopped = false;
|
|
974
|
-
const endChild = () => {
|
|
975
|
-
if (stopped) return;
|
|
976
|
-
stopped = true;
|
|
1963
|
+
return (raw) => {
|
|
1964
|
+
const text = raw.trim();
|
|
1965
|
+
if (!text) return [];
|
|
1966
|
+
if (!text.startsWith("{")) return [raw];
|
|
1967
|
+
let event;
|
|
977
1968
|
try {
|
|
978
|
-
|
|
1969
|
+
event = JSON.parse(text);
|
|
979
1970
|
} catch {
|
|
1971
|
+
return [raw];
|
|
980
1972
|
}
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
if (
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1973
|
+
if (!isRecord4(event)) return [];
|
|
1974
|
+
switch (event.type) {
|
|
1975
|
+
case "response": {
|
|
1976
|
+
if (event.command !== "prompt") return [];
|
|
1977
|
+
if (event.success === false) {
|
|
1978
|
+
const why = typeof event.error === "string" ? event.error : "rejected";
|
|
1979
|
+
return [result(`pi refused the prompt: ${why}`)];
|
|
1980
|
+
}
|
|
1981
|
+
const data = isRecord4(event.data) ? event.data : null;
|
|
1982
|
+
if (data?.disposition === "handled") {
|
|
1983
|
+
return [result("pi handled the prompt without running the model")];
|
|
1984
|
+
}
|
|
1985
|
+
return [];
|
|
1986
|
+
}
|
|
1987
|
+
case "agent_start":
|
|
1988
|
+
if (started) return [];
|
|
1989
|
+
started = true;
|
|
1990
|
+
return [
|
|
1991
|
+
line3({ type: "system", subtype: "init", session_id: sessionId, model: opts.model })
|
|
1992
|
+
];
|
|
1993
|
+
case "message_end": {
|
|
1994
|
+
const message = isRecord4(event.message) ? event.message : null;
|
|
1995
|
+
if (!message) return [];
|
|
1996
|
+
if (message.role === "user") {
|
|
1997
|
+
const said2 = messageText(message.content);
|
|
1998
|
+
if (!said2) return [];
|
|
1999
|
+
return [
|
|
2000
|
+
line3({
|
|
2001
|
+
type: "user",
|
|
2002
|
+
isReplay: true,
|
|
2003
|
+
message: { role: "user", content: [{ type: "text", text: said2 }] }
|
|
2004
|
+
})
|
|
2005
|
+
];
|
|
2006
|
+
}
|
|
2007
|
+
if (message.role !== "assistant") return [];
|
|
2008
|
+
const u = isRecord4(message.usage) ? message.usage : {};
|
|
2009
|
+
usage.input += num(u.input);
|
|
2010
|
+
usage.output += num(u.output);
|
|
2011
|
+
usage.cacheRead += num(u.cacheRead);
|
|
2012
|
+
usage.cacheWrite += num(u.cacheWrite);
|
|
2013
|
+
const stop = message.stopReason;
|
|
2014
|
+
if (stop === "error" || stop === "aborted") {
|
|
2015
|
+
lastError = typeof message.errorMessage === "string" && message.errorMessage ? message.errorMessage : `model turn ended with ${stop}`;
|
|
2016
|
+
} else {
|
|
2017
|
+
lastError = null;
|
|
2018
|
+
}
|
|
2019
|
+
const blocks = [];
|
|
2020
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
2021
|
+
for (const part of content) {
|
|
2022
|
+
if (!isRecord4(part)) continue;
|
|
2023
|
+
if (part.type === "text" && typeof part.text === "string" && part.text) {
|
|
2024
|
+
blocks.push({ type: "text", text: part.text });
|
|
2025
|
+
} else if (part.type === "toolCall" && typeof part.name === "string") {
|
|
2026
|
+
blocks.push({
|
|
2027
|
+
type: "tool_use",
|
|
2028
|
+
id: typeof part.id === "string" ? part.id : "",
|
|
2029
|
+
name: part.name,
|
|
2030
|
+
input: isRecord4(part.arguments) ? part.arguments : {}
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
const said = messageText(content);
|
|
2035
|
+
if (said) lastText = said;
|
|
2036
|
+
if (blocks.length === 0) return [];
|
|
2037
|
+
return [line3({ type: "assistant", message: { role: "assistant", content: blocks } })];
|
|
2038
|
+
}
|
|
2039
|
+
case "tool_execution_end": {
|
|
2040
|
+
const res = isRecord4(event.result) ? event.result : {};
|
|
2041
|
+
return [
|
|
2042
|
+
line3({
|
|
2043
|
+
type: "user",
|
|
2044
|
+
message: {
|
|
2045
|
+
role: "user",
|
|
2046
|
+
content: [
|
|
2047
|
+
{
|
|
2048
|
+
type: "tool_result",
|
|
2049
|
+
tool_use_id: typeof event.toolCallId === "string" ? event.toolCallId : "",
|
|
2050
|
+
content: messageText(res.content),
|
|
2051
|
+
is_error: event.isError === true
|
|
2052
|
+
}
|
|
2053
|
+
]
|
|
2054
|
+
}
|
|
2055
|
+
})
|
|
2056
|
+
];
|
|
2057
|
+
}
|
|
2058
|
+
case "auto_retry_end":
|
|
2059
|
+
if (event.success === false) {
|
|
2060
|
+
lastError = typeof event.finalError === "string" && event.finalError ? event.finalError : "model request failed after retries";
|
|
2061
|
+
}
|
|
2062
|
+
return [];
|
|
2063
|
+
case "agent_settled":
|
|
2064
|
+
return [result(event.aborted === true ? lastError ?? "pi run aborted" : lastError)];
|
|
2065
|
+
default:
|
|
2066
|
+
return [];
|
|
1000
2067
|
}
|
|
1001
|
-
});
|
|
1002
|
-
let lastResult;
|
|
1003
|
-
const finishTurn = (text, isError, subtype, errors) => {
|
|
1004
|
-
render.feed(line2({ type: "assistant", message: { content: [{ type: "text", text }] } }));
|
|
1005
|
-
render.feed(
|
|
1006
|
-
line2({
|
|
1007
|
-
type: "result",
|
|
1008
|
-
subtype,
|
|
1009
|
-
is_error: isError,
|
|
1010
|
-
result: text,
|
|
1011
|
-
session_id: sessionId ?? "",
|
|
1012
|
-
...errors.length ? { errors } : {}
|
|
1013
|
-
})
|
|
1014
|
-
);
|
|
1015
|
-
lastResult = {
|
|
1016
|
-
resultText: text,
|
|
1017
|
-
assistantTexts: text ? [text] : [],
|
|
1018
|
-
isError,
|
|
1019
|
-
subtype,
|
|
1020
|
-
errors,
|
|
1021
|
-
backgroundTasks: 0
|
|
1022
|
-
};
|
|
1023
2068
|
};
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
2069
|
+
}
|
|
2070
|
+
function describeProgress(p) {
|
|
2071
|
+
const s = Math.round(p.elapsedMs / 1e3);
|
|
2072
|
+
switch (p.phase) {
|
|
2073
|
+
case "starting":
|
|
2074
|
+
return `local: starting ${p.model} (omarchy-models start); the tick runs once it is loaded.`;
|
|
2075
|
+
case "loading":
|
|
2076
|
+
return `local: ${p.model} still loading (${s} s).`;
|
|
2077
|
+
case "ready":
|
|
2078
|
+
return `local: ${p.model} is running (${s} s).`;
|
|
2079
|
+
default:
|
|
2080
|
+
return `local: ${p.model} did not start${p.detail ? `: ${p.detail}` : ""}.`;
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
function createLocalBackend(deps = {}) {
|
|
2084
|
+
return {
|
|
2085
|
+
id: "local",
|
|
2086
|
+
async resolve() {
|
|
2087
|
+
return (deps.whichFn ?? whichBinary)("pi");
|
|
2088
|
+
},
|
|
2089
|
+
async run(opts) {
|
|
2090
|
+
const log = opts.log ?? ((text) => console.log(text));
|
|
2091
|
+
const parsed = parseLocalModelId(opts.model);
|
|
2092
|
+
if (!parsed.ok) throw new Error(parsed.message);
|
|
2093
|
+
const report = await (deps.discover ?? (() => discoverLocalModels({
|
|
2094
|
+
...deps.whichFn ? { whichFn: deps.whichFn } : {},
|
|
2095
|
+
...deps.execFn ? { execFn: deps.execFn } : {}
|
|
2096
|
+
})))();
|
|
2097
|
+
const found = findRunnableLocalModel(parsed.id, report);
|
|
2098
|
+
if (!found.ok) throw new Error(found.message);
|
|
2099
|
+
const prepared = await codexPrompt(opts.workspace, opts.prompt, piSlashPointer);
|
|
2100
|
+
if (!prepared.ok) {
|
|
2101
|
+
throw new Error(
|
|
2102
|
+
`local backend: ${prepared.missing} is missing in the workspace, so the tick's leading slash has no contract to point pi at. Install the kit (\`agent-kit install\`) and retry.`
|
|
2103
|
+
);
|
|
1036
2104
|
}
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
sessionId = created.sessionId;
|
|
1043
|
-
render.feed(
|
|
1044
|
-
line2({ type: "system", subtype: "init", session_id: sessionId, model: "cursor-acp" })
|
|
1045
|
-
);
|
|
1046
|
-
let prompt = opts.prompt;
|
|
1047
|
-
for (let turn = 0; turn < ACP_MAX_TURNS && !record.stop; turn += 1) {
|
|
1048
|
-
turnText = "";
|
|
1049
|
-
let stopReason = "end_turn";
|
|
2105
|
+
const progress = (p) => {
|
|
2106
|
+
log(describeProgress(p));
|
|
2107
|
+
opts.onProgress?.(p);
|
|
2108
|
+
};
|
|
2109
|
+
const setup = await prepareLocalProvider(found.model, parsed, deps, progress);
|
|
1050
2110
|
try {
|
|
1051
|
-
const
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
2111
|
+
const env = localChildEnv(opts.env, setup.agentDir);
|
|
2112
|
+
const redact = claudeRedactions(env);
|
|
2113
|
+
log(
|
|
2114
|
+
`local tick: pi --mode rpc on ${parsed.id} (provider ${setup.provider}, model ${setup.model}; only the kit's provider extension, temporary pi agent dir, no session file, offline, stdin relay).`
|
|
2115
|
+
);
|
|
2116
|
+
try {
|
|
2117
|
+
return await spawnLogged("pi", localPiArgs(setup), opts.logPath, {
|
|
2118
|
+
cwd: opts.workspace,
|
|
2119
|
+
env,
|
|
2120
|
+
redact,
|
|
2121
|
+
spawnFn: opts.spawnFn,
|
|
2122
|
+
hitl: resolveHitlRunOptions(opts.hitl, {
|
|
2123
|
+
kind: "stdin-stream-json",
|
|
2124
|
+
firstPrompt: prepared.prompt,
|
|
2125
|
+
encode: piRpcPromptLine
|
|
2126
|
+
}),
|
|
2127
|
+
render: opts.render,
|
|
2128
|
+
onSpawn: opts.onSpawn,
|
|
2129
|
+
backendId: "local",
|
|
2130
|
+
translate: createPiTranslator({ model: parsed.id })
|
|
2131
|
+
});
|
|
2132
|
+
} catch (err) {
|
|
2133
|
+
throw new Error(`local backend failed to start: ${redactSecrets(String(err), redact)}`);
|
|
2134
|
+
}
|
|
2135
|
+
} finally {
|
|
2136
|
+
await cleanupLocalProvider(setup);
|
|
1070
2137
|
}
|
|
1071
|
-
record.replies.push(outcome.stamp);
|
|
1072
|
-
hitl.write(`\u2192 ${outcome.stamp.line}
|
|
1073
|
-
`);
|
|
1074
|
-
prompt = outcome.stamp.line;
|
|
1075
2138
|
}
|
|
1076
2139
|
};
|
|
1077
|
-
await session().catch((err) => {
|
|
1078
|
-
failed(err.message ?? String(err));
|
|
1079
|
-
});
|
|
1080
|
-
const failure = spawnError;
|
|
1081
|
-
if (failure) {
|
|
1082
|
-
out.end();
|
|
1083
|
-
throw new Error(`cursor-acp backend failed to start: ${failure.message}`);
|
|
1084
|
-
}
|
|
1085
|
-
const endedByClient = !closed;
|
|
1086
|
-
endChild();
|
|
1087
|
-
await closedPromise;
|
|
1088
|
-
const rest = splitter.end();
|
|
1089
|
-
if (rest.trim()) take(rest);
|
|
1090
|
-
const errRest = errBuffer.flush();
|
|
1091
|
-
if (errRest) out.write(errRest);
|
|
1092
|
-
render.end();
|
|
1093
|
-
await new Promise((resolve) => out.end(() => resolve()));
|
|
1094
|
-
if (logError) throw new Error(`cursor-acp backend: ${redactSecrets(String(logError), redact)}`);
|
|
1095
|
-
const code = lastResult?.isError ? 1 : endedByClient ? 0 : exitCode ?? 1;
|
|
1096
|
-
return { exitCode: code, hitl: record, ...lastResult ? { lastResult } : {} };
|
|
1097
2140
|
}
|
|
1098
|
-
var
|
|
1099
|
-
id: "cursor-acp",
|
|
1100
|
-
async resolve() {
|
|
1101
|
-
return whichBinary("cursor-agent");
|
|
1102
|
-
},
|
|
1103
|
-
run: runCursorAcp
|
|
1104
|
-
};
|
|
2141
|
+
var localBackend = createLocalBackend();
|
|
1105
2142
|
|
|
1106
2143
|
// src/plan-loop/backends.ts
|
|
1107
2144
|
function createLineTranslator(translate) {
|
|
1108
2145
|
const decoder = new StringDecoder3("utf8");
|
|
1109
2146
|
const lines = new LineSplitter();
|
|
1110
|
-
const run = (
|
|
2147
|
+
const run = (line4, out) => {
|
|
1111
2148
|
try {
|
|
1112
|
-
out.push(...translate(
|
|
2149
|
+
out.push(...translate(line4));
|
|
1113
2150
|
} catch {
|
|
1114
2151
|
}
|
|
1115
2152
|
};
|
|
@@ -1117,13 +2154,13 @@ function createLineTranslator(translate) {
|
|
|
1117
2154
|
push(chunk) {
|
|
1118
2155
|
const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
|
|
1119
2156
|
const out = [];
|
|
1120
|
-
lines.feed(text, (
|
|
2157
|
+
lines.feed(text, (line4) => run(line4, out));
|
|
1121
2158
|
return out.length ? `${out.join("\n")}
|
|
1122
2159
|
` : "";
|
|
1123
2160
|
},
|
|
1124
2161
|
end() {
|
|
1125
2162
|
const out = [];
|
|
1126
|
-
lines.feed(decoder.end(), (
|
|
2163
|
+
lines.feed(decoder.end(), (line4) => run(line4, out));
|
|
1127
2164
|
const rest = lines.end();
|
|
1128
2165
|
if (rest.trim()) run(rest, out);
|
|
1129
2166
|
return out.length ? `${out.join("\n")}
|
|
@@ -1441,14 +2478,15 @@ function createRelay(hitl, child, redactedError) {
|
|
|
1441
2478
|
resolveClosed = resolve;
|
|
1442
2479
|
});
|
|
1443
2480
|
const stdin = child.stdin;
|
|
2481
|
+
const encode = hitl.transport.kind === "stdin-stream-json" ? hitl.transport.encode ?? userEventLine : userEventLine;
|
|
1444
2482
|
if (hitl.transport.kind === "stdin-stream-json") {
|
|
1445
2483
|
if (!stdin) {
|
|
1446
|
-
startError = new Error("
|
|
2484
|
+
startError = new Error("agent child has no writable stdin (stdin relay transport)");
|
|
1447
2485
|
} else {
|
|
1448
2486
|
stdin.on("error", () => {
|
|
1449
2487
|
});
|
|
1450
2488
|
try {
|
|
1451
|
-
stdin.write(
|
|
2489
|
+
stdin.write(encode(hitl.transport.firstPrompt));
|
|
1452
2490
|
} catch (err) {
|
|
1453
2491
|
startError = redactedError(err);
|
|
1454
2492
|
}
|
|
@@ -1526,7 +2564,7 @@ function createRelay(hitl, child, redactedError) {
|
|
|
1526
2564
|
record.replies.push(outcome.stamp);
|
|
1527
2565
|
hitl.write(`\u2192 ${outcome.stamp.line}
|
|
1528
2566
|
`);
|
|
1529
|
-
stdin.write(
|
|
2567
|
+
stdin.write(encode(outcome.stamp.line));
|
|
1530
2568
|
},
|
|
1531
2569
|
(err) => {
|
|
1532
2570
|
record.stop = unansweredStop(gate.askId, "child exited");
|
|
@@ -1714,9 +2752,9 @@ function claudeReviewArgs(opts = {}) {
|
|
|
1714
2752
|
async function missingClaudeAdapter(workspace, prompt) {
|
|
1715
2753
|
const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
|
|
1716
2754
|
if (!m?.[1]) return null;
|
|
1717
|
-
const rel =
|
|
2755
|
+
const rel = path4.join(".claude", "commands", `${m[1]}.md`);
|
|
1718
2756
|
try {
|
|
1719
|
-
await access2(
|
|
2757
|
+
await access2(path4.join(workspace, rel));
|
|
1720
2758
|
return null;
|
|
1721
2759
|
} catch {
|
|
1722
2760
|
return rel;
|
|
@@ -1728,7 +2766,7 @@ var claudeBackend = {
|
|
|
1728
2766
|
return whichBinary("claude");
|
|
1729
2767
|
},
|
|
1730
2768
|
async run(opts) {
|
|
1731
|
-
const log = opts.log ?? ((
|
|
2769
|
+
const log = opts.log ?? ((line4) => console.log(line4));
|
|
1732
2770
|
const env = claudeChildEnv(opts.env);
|
|
1733
2771
|
const redact = claudeRedactions(env);
|
|
1734
2772
|
const version = checkClaudeVersion("claude", opts.versionFn);
|
|
@@ -1781,7 +2819,7 @@ var openrouterBackend = {
|
|
|
1781
2819
|
return whichBinary("ori");
|
|
1782
2820
|
},
|
|
1783
2821
|
async run(opts) {
|
|
1784
|
-
const log = opts.log ?? ((
|
|
2822
|
+
const log = opts.log ?? ((line4) => console.log(line4));
|
|
1785
2823
|
const env = claudeChildEnv(opts.env);
|
|
1786
2824
|
const redact = claudeRedactions(env);
|
|
1787
2825
|
const adapter = await missingClaudeAdapter(opts.workspace, opts.prompt);
|
|
@@ -1831,7 +2869,8 @@ function backends() {
|
|
|
1831
2869
|
claude: claudeBackend,
|
|
1832
2870
|
codex: codexBackend,
|
|
1833
2871
|
"cursor-acp": cursorAcpBackend,
|
|
1834
|
-
openrouter: openrouterBackend
|
|
2872
|
+
openrouter: openrouterBackend,
|
|
2873
|
+
local: localBackend
|
|
1835
2874
|
};
|
|
1836
2875
|
}
|
|
1837
2876
|
function getBackend(id) {
|
|
@@ -1843,21 +2882,373 @@ function getBackend(id) {
|
|
|
1843
2882
|
return backend;
|
|
1844
2883
|
}
|
|
1845
2884
|
|
|
2885
|
+
// src/plan-loop/local-models.ts
|
|
2886
|
+
var LOCAL_MODELS_SCHEMA_VERSION = 1;
|
|
2887
|
+
var DEFAULT_SOURCE_TIMEOUT_MS = 1500;
|
|
2888
|
+
var LOCAL_MODEL_SOURCES = [
|
|
2889
|
+
"omarchy",
|
|
2890
|
+
"ollama",
|
|
2891
|
+
"lmstudio",
|
|
2892
|
+
"llamacpp"
|
|
2893
|
+
];
|
|
2894
|
+
var OLLAMA_BASE = "http://127.0.0.1:11434";
|
|
2895
|
+
var LMSTUDIO_BASE = "http://127.0.0.1:1234";
|
|
2896
|
+
var LLAMACPP_BASE = "http://127.0.0.1:8080";
|
|
2897
|
+
var defaultExecFn = (file, args, timeoutMs) => new Promise((resolve) => {
|
|
2898
|
+
try {
|
|
2899
|
+
execFile(
|
|
2900
|
+
file,
|
|
2901
|
+
args,
|
|
2902
|
+
{ encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024, windowsHide: true },
|
|
2903
|
+
(error, stdout) => {
|
|
2904
|
+
if (!error) {
|
|
2905
|
+
resolve({ ok: true, stdout: String(stdout ?? "") });
|
|
2906
|
+
return;
|
|
2907
|
+
}
|
|
2908
|
+
const err = error;
|
|
2909
|
+
if (err.code === "ENOENT") resolve({ ok: false, reason: "missing" });
|
|
2910
|
+
else if (err.killed) resolve({ ok: false, reason: "timeout" });
|
|
2911
|
+
else resolve({ ok: false, reason: "failed", detail: firstLine(err.message) });
|
|
2912
|
+
}
|
|
2913
|
+
);
|
|
2914
|
+
} catch (err) {
|
|
2915
|
+
resolve({ ok: false, reason: "failed", detail: firstLine(String(err)) });
|
|
2916
|
+
}
|
|
2917
|
+
});
|
|
2918
|
+
var defaultFetchFn = (url, init) => fetch(url, init);
|
|
2919
|
+
function firstLine(text) {
|
|
2920
|
+
return (text.split("\n")[0] ?? "").trim().slice(0, 200);
|
|
2921
|
+
}
|
|
2922
|
+
function isLoopbackUrl(raw) {
|
|
2923
|
+
let url;
|
|
2924
|
+
try {
|
|
2925
|
+
url = new URL(raw);
|
|
2926
|
+
} catch {
|
|
2927
|
+
return false;
|
|
2928
|
+
}
|
|
2929
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return false;
|
|
2930
|
+
const host = url.hostname.toLowerCase();
|
|
2931
|
+
return host === "localhost" || host === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(host);
|
|
2932
|
+
}
|
|
2933
|
+
function hostPort(url) {
|
|
2934
|
+
try {
|
|
2935
|
+
return new URL(url).host;
|
|
2936
|
+
} catch {
|
|
2937
|
+
return url;
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
function errorCode(err) {
|
|
2941
|
+
const e = err;
|
|
2942
|
+
if (e && typeof e.cause?.code === "string") return e.cause.code;
|
|
2943
|
+
if (e && typeof e.code === "string") return e.code;
|
|
2944
|
+
return void 0;
|
|
2945
|
+
}
|
|
2946
|
+
async function getLoopbackJson(url, fetchFn, timeoutMs) {
|
|
2947
|
+
if (!isLoopbackUrl(url)) return { ok: false, note: `not a loopback address: ${url}` };
|
|
2948
|
+
const controller = new AbortController();
|
|
2949
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2950
|
+
try {
|
|
2951
|
+
const res = await fetchFn(url, {
|
|
2952
|
+
signal: controller.signal,
|
|
2953
|
+
redirect: "manual",
|
|
2954
|
+
headers: { accept: "application/json" }
|
|
2955
|
+
});
|
|
2956
|
+
if (res.status >= 300 && res.status < 400) {
|
|
2957
|
+
return { ok: false, note: `redirect refused (HTTP ${res.status} from ${hostPort(url)})` };
|
|
2958
|
+
}
|
|
2959
|
+
if (res.status !== 200) return { ok: false, note: `HTTP ${res.status} from ${hostPort(url)}` };
|
|
2960
|
+
const body = await res.text();
|
|
2961
|
+
try {
|
|
2962
|
+
return { ok: true, value: JSON.parse(body) };
|
|
2963
|
+
} catch {
|
|
2964
|
+
return { ok: false, note: `malformed JSON from ${hostPort(url)}` };
|
|
2965
|
+
}
|
|
2966
|
+
} catch (err) {
|
|
2967
|
+
if (controller.signal.aborted) {
|
|
2968
|
+
return { ok: false, note: `no answer within ${timeoutMs} ms (${hostPort(url)})` };
|
|
2969
|
+
}
|
|
2970
|
+
const code = errorCode(err);
|
|
2971
|
+
if (code === "ECONNREFUSED")
|
|
2972
|
+
return { ok: false, note: `connection refused (${hostPort(url)})` };
|
|
2973
|
+
return {
|
|
2974
|
+
ok: false,
|
|
2975
|
+
note: `request failed (${hostPort(url)}${code ? `, ${code}` : ""})`
|
|
2976
|
+
};
|
|
2977
|
+
} finally {
|
|
2978
|
+
clearTimeout(timer);
|
|
2979
|
+
controller.abort();
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
function isRecord5(v) {
|
|
2983
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2984
|
+
}
|
|
2985
|
+
function str(v) {
|
|
2986
|
+
return typeof v === "string" && v.trim() !== "" ? v.trim() : void 0;
|
|
2987
|
+
}
|
|
2988
|
+
function positiveInt(v) {
|
|
2989
|
+
return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : void 0;
|
|
2990
|
+
}
|
|
2991
|
+
function joinNotes(notes) {
|
|
2992
|
+
return notes.length > 0 ? notes.join("; ") : void 0;
|
|
2993
|
+
}
|
|
2994
|
+
function plural(n, word) {
|
|
2995
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
2996
|
+
}
|
|
2997
|
+
function parseOmarchyStatus(value) {
|
|
2998
|
+
const source = "omarchy";
|
|
2999
|
+
if (!isRecord5(value) || !isRecord5(value.models)) {
|
|
3000
|
+
return {
|
|
3001
|
+
status: { source, ok: false, note: "unexpected JSON shape (no models object)" },
|
|
3002
|
+
models: []
|
|
3003
|
+
};
|
|
3004
|
+
}
|
|
3005
|
+
const models = [];
|
|
3006
|
+
let nonLoopback = 0;
|
|
3007
|
+
let noEndpoint = 0;
|
|
3008
|
+
for (const [key, raw] of Object.entries(value.models)) {
|
|
3009
|
+
if (!isRecord5(raw) || raw.kind !== "text") continue;
|
|
3010
|
+
const recipe = str(raw.recipe) ?? str(key);
|
|
3011
|
+
if (!recipe) continue;
|
|
3012
|
+
const endpoint = str(raw.endpoint);
|
|
3013
|
+
if (!endpoint) {
|
|
3014
|
+
noEndpoint += 1;
|
|
3015
|
+
continue;
|
|
3016
|
+
}
|
|
3017
|
+
if (!isLoopbackUrl(endpoint)) {
|
|
3018
|
+
nonLoopback += 1;
|
|
3019
|
+
continue;
|
|
3020
|
+
}
|
|
3021
|
+
const running = raw.unit === "active" && raw.sub_state === "running";
|
|
3022
|
+
const state = running ? "running" : raw.fits === false ? "not-fit" : "stopped";
|
|
3023
|
+
const reason = state === "not-fit" ? str(raw.fit_reason) ?? "does not fit" : void 0;
|
|
3024
|
+
const model = {
|
|
3025
|
+
id: `${source}:${recipe}`,
|
|
3026
|
+
label: str(raw.name) ?? recipe,
|
|
3027
|
+
source,
|
|
3028
|
+
endpoint: endpoint.replace(/\/+$/, ""),
|
|
3029
|
+
state
|
|
3030
|
+
};
|
|
3031
|
+
const ctx = positiveInt(raw.ctx);
|
|
3032
|
+
if (ctx) model.contextWindow = ctx;
|
|
3033
|
+
const vendor = str(raw.vendor);
|
|
3034
|
+
if (vendor) model.vendor = vendor;
|
|
3035
|
+
if (reason) model.reason = reason;
|
|
3036
|
+
models.push(model);
|
|
3037
|
+
}
|
|
3038
|
+
const notes = [];
|
|
3039
|
+
if (nonLoopback > 0) notes.push(`skipped ${plural(nonLoopback, "non-loopback model")}`);
|
|
3040
|
+
if (noEndpoint > 0) notes.push(`skipped ${plural(noEndpoint, "model")} without an endpoint`);
|
|
3041
|
+
const note = joinNotes(notes);
|
|
3042
|
+
return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
|
|
3043
|
+
}
|
|
3044
|
+
function isOllamaCloudModel(entry, name) {
|
|
3045
|
+
return name.endsWith(":cloud") || name.endsWith("-cloud") || str(entry.remote_host) !== void 0;
|
|
3046
|
+
}
|
|
3047
|
+
function parseOllamaTags(value) {
|
|
3048
|
+
const source = "ollama";
|
|
3049
|
+
if (!isRecord5(value) || !Array.isArray(value.models)) {
|
|
3050
|
+
return {
|
|
3051
|
+
status: { source, ok: false, note: "unexpected JSON shape (no models array)" },
|
|
3052
|
+
models: []
|
|
3053
|
+
};
|
|
3054
|
+
}
|
|
3055
|
+
const models = [];
|
|
3056
|
+
let cloud = 0;
|
|
3057
|
+
let notText = 0;
|
|
3058
|
+
for (const raw of value.models) {
|
|
3059
|
+
if (!isRecord5(raw)) continue;
|
|
3060
|
+
const name = str(raw.name) ?? str(raw.model);
|
|
3061
|
+
if (!name) continue;
|
|
3062
|
+
if (isOllamaCloudModel(raw, name)) {
|
|
3063
|
+
cloud += 1;
|
|
3064
|
+
continue;
|
|
3065
|
+
}
|
|
3066
|
+
if (Array.isArray(raw.capabilities) && !raw.capabilities.includes("completion")) {
|
|
3067
|
+
notText += 1;
|
|
3068
|
+
continue;
|
|
3069
|
+
}
|
|
3070
|
+
const model = {
|
|
3071
|
+
id: `${source}:${name}`,
|
|
3072
|
+
label: name,
|
|
3073
|
+
source,
|
|
3074
|
+
endpoint: `${OLLAMA_BASE}/v1`,
|
|
3075
|
+
state: "running"
|
|
3076
|
+
};
|
|
3077
|
+
const details = isRecord5(raw.details) ? raw.details : void 0;
|
|
3078
|
+
const family = details ? str(details.family) : void 0;
|
|
3079
|
+
if (family) model.vendor = family;
|
|
3080
|
+
models.push(model);
|
|
3081
|
+
}
|
|
3082
|
+
const notes = [];
|
|
3083
|
+
if (cloud > 0) notes.push(`skipped ${plural(cloud, "cloud model")}`);
|
|
3084
|
+
if (notText > 0) notes.push(`skipped ${plural(notText, "non-text model")}`);
|
|
3085
|
+
const note = joinNotes(notes);
|
|
3086
|
+
return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
|
|
3087
|
+
}
|
|
3088
|
+
function parseOpenAiModels(source, base, value) {
|
|
3089
|
+
if (!isRecord5(value) || !Array.isArray(value.data)) {
|
|
3090
|
+
return {
|
|
3091
|
+
status: { source, ok: false, note: "unexpected JSON shape (no data array)" },
|
|
3092
|
+
models: []
|
|
3093
|
+
};
|
|
3094
|
+
}
|
|
3095
|
+
const models = [];
|
|
3096
|
+
for (const raw of value.data) {
|
|
3097
|
+
if (!isRecord5(raw)) continue;
|
|
3098
|
+
const id = str(raw.id);
|
|
3099
|
+
if (!id) continue;
|
|
3100
|
+
const model = {
|
|
3101
|
+
id: `${source}:${id}`,
|
|
3102
|
+
label: id,
|
|
3103
|
+
source,
|
|
3104
|
+
endpoint: `${base}/v1`,
|
|
3105
|
+
state: "running"
|
|
3106
|
+
};
|
|
3107
|
+
const owner = str(raw.owned_by);
|
|
3108
|
+
if (owner && owner !== "organization_owner" && owner !== "llamacpp") model.vendor = owner;
|
|
3109
|
+
models.push(model);
|
|
3110
|
+
}
|
|
3111
|
+
return { status: { source, ok: true }, models };
|
|
3112
|
+
}
|
|
3113
|
+
async function probeOmarchy(deps) {
|
|
3114
|
+
const source = "omarchy";
|
|
3115
|
+
const bin = await deps.whichFn("omarchy-models");
|
|
3116
|
+
if (!bin)
|
|
3117
|
+
return { status: { source, ok: false, note: "omarchy-models not on PATH" }, models: [] };
|
|
3118
|
+
const run = await deps.execFn(bin, ["status", "--json"], deps.timeoutMs);
|
|
3119
|
+
if (!run.ok) {
|
|
3120
|
+
const note = run.reason === "missing" ? "omarchy-models not on PATH" : run.reason === "timeout" ? `omarchy-models status gave no answer within ${deps.timeoutMs} ms` : `omarchy-models status failed${run.detail ? `: ${run.detail}` : ""}`;
|
|
3121
|
+
return { status: { source, ok: false, note }, models: [] };
|
|
3122
|
+
}
|
|
3123
|
+
let value;
|
|
3124
|
+
try {
|
|
3125
|
+
value = JSON.parse(run.stdout);
|
|
3126
|
+
} catch {
|
|
3127
|
+
return {
|
|
3128
|
+
status: { source, ok: false, note: "malformed JSON from omarchy-models status" },
|
|
3129
|
+
models: []
|
|
3130
|
+
};
|
|
3131
|
+
}
|
|
3132
|
+
return parseOmarchyStatus(value);
|
|
3133
|
+
}
|
|
3134
|
+
async function probeHttp(source, deps) {
|
|
3135
|
+
const url = source === "ollama" ? `${OLLAMA_BASE}/api/tags` : `${source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE}/v1/models`;
|
|
3136
|
+
const got = await getLoopbackJson(url, deps.fetchFn, deps.timeoutMs);
|
|
3137
|
+
if (!got.ok) return { status: { source, ok: false, note: got.note }, models: [] };
|
|
3138
|
+
if (source === "ollama") return parseOllamaTags(got.value);
|
|
3139
|
+
return parseOpenAiModels(
|
|
3140
|
+
source,
|
|
3141
|
+
source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE,
|
|
3142
|
+
got.value
|
|
3143
|
+
);
|
|
3144
|
+
}
|
|
3145
|
+
async function safely(source, run) {
|
|
3146
|
+
try {
|
|
3147
|
+
return await run();
|
|
3148
|
+
} catch (err) {
|
|
3149
|
+
return {
|
|
3150
|
+
status: { source, ok: false, note: `probe failed: ${firstLine(String(err))}` },
|
|
3151
|
+
models: []
|
|
3152
|
+
};
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
async function discoverLocalModels(deps = {}) {
|
|
3156
|
+
const full = {
|
|
3157
|
+
whichFn: deps.whichFn ?? whichBinary,
|
|
3158
|
+
execFn: deps.execFn ?? defaultExecFn,
|
|
3159
|
+
fetchFn: deps.fetchFn ?? defaultFetchFn,
|
|
3160
|
+
timeoutMs: deps.timeoutMs ?? DEFAULT_SOURCE_TIMEOUT_MS
|
|
3161
|
+
};
|
|
3162
|
+
const [piPath, ...outcomes] = await Promise.all([
|
|
3163
|
+
full.whichFn("pi").catch(() => null),
|
|
3164
|
+
safely("omarchy", () => probeOmarchy(full)),
|
|
3165
|
+
safely("ollama", () => probeHttp("ollama", full)),
|
|
3166
|
+
safely("lmstudio", () => probeHttp("lmstudio", full)),
|
|
3167
|
+
safely("llamacpp", () => probeHttp("llamacpp", full))
|
|
3168
|
+
]);
|
|
3169
|
+
const piFound = Boolean(piPath);
|
|
3170
|
+
const models = outcomes.flatMap(
|
|
3171
|
+
(o) => o.models.map((m) => {
|
|
3172
|
+
const runnable = piFound && m.state !== "not-fit";
|
|
3173
|
+
const { id, label, source, endpoint, state, ...optional } = m;
|
|
3174
|
+
const out = { id, label, source, endpoint, state, runnable, ...optional };
|
|
3175
|
+
if (!runnable && !out.reason) out.reason = "pi not on PATH";
|
|
3176
|
+
return out;
|
|
3177
|
+
})
|
|
3178
|
+
);
|
|
3179
|
+
return {
|
|
3180
|
+
schemaVersion: LOCAL_MODELS_SCHEMA_VERSION,
|
|
3181
|
+
models,
|
|
3182
|
+
sources: outcomes.map((o) => o.status),
|
|
3183
|
+
pi: { found: piFound }
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
function renderLocalModels(report) {
|
|
3187
|
+
const lines = [];
|
|
3188
|
+
if (report.models.length === 0) {
|
|
3189
|
+
lines.push("No local text models found.");
|
|
3190
|
+
} else {
|
|
3191
|
+
const rows = report.models.map((m) => [
|
|
3192
|
+
m.id,
|
|
3193
|
+
m.state,
|
|
3194
|
+
m.runnable ? "yes" : "no",
|
|
3195
|
+
m.endpoint,
|
|
3196
|
+
m.reason ?? ""
|
|
3197
|
+
]);
|
|
3198
|
+
const header = ["ID", "STATE", "RUNNABLE", "ENDPOINT", "NOTE"];
|
|
3199
|
+
const widths = header.map(
|
|
3200
|
+
(h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
|
|
3201
|
+
);
|
|
3202
|
+
const fmt = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
3203
|
+
lines.push(fmt(header), ...rows.map(fmt));
|
|
3204
|
+
}
|
|
3205
|
+
lines.push("");
|
|
3206
|
+
for (const s of report.sources) {
|
|
3207
|
+
lines.push(`${s.source}: ${s.ok ? "ok" : "unavailable"}${s.note ? ` (${s.note})` : ""}`);
|
|
3208
|
+
}
|
|
3209
|
+
lines.push(`pi: ${report.pi.found ? "found" : "not on PATH (no model is runnable)"}`);
|
|
3210
|
+
return lines.join("\n");
|
|
3211
|
+
}
|
|
3212
|
+
|
|
1846
3213
|
export {
|
|
1847
3214
|
codexBackend,
|
|
1848
3215
|
parseStreamLine,
|
|
3216
|
+
parseResultLine,
|
|
1849
3217
|
renderStreamEvent,
|
|
1850
3218
|
createStreamRenderer,
|
|
1851
3219
|
cursorAcpBackend,
|
|
3220
|
+
discoverLocalModels,
|
|
3221
|
+
renderLocalModels,
|
|
3222
|
+
INSTALL_HINTS,
|
|
3223
|
+
listDetectBackendIds,
|
|
3224
|
+
detectAgentBackend,
|
|
3225
|
+
countPendingTodos,
|
|
3226
|
+
findActivePlanFile,
|
|
3227
|
+
readPlan,
|
|
3228
|
+
readRunQueueState,
|
|
3229
|
+
resolveActivePlanFromHandoff,
|
|
3230
|
+
resolveActivePlanPath,
|
|
3231
|
+
CLAUDE_SUBAGENT_MODEL_ENV,
|
|
3232
|
+
readPlanRoleOverrides,
|
|
3233
|
+
resolveWorkerRole,
|
|
3234
|
+
resolveSubworkerModel,
|
|
3235
|
+
describeResolvedRoles,
|
|
3236
|
+
reviewModelRelation,
|
|
3237
|
+
describeIdenticalReviewModel,
|
|
3238
|
+
describeSameFamilyReviewModel,
|
|
3239
|
+
resolveReviewJobRole,
|
|
3240
|
+
loadRolesContext,
|
|
3241
|
+
parseLocalModelId,
|
|
3242
|
+
localBackend,
|
|
1852
3243
|
resolveHitlRunOptions,
|
|
1853
3244
|
redactSecrets,
|
|
1854
3245
|
RedactingStreamBuffer,
|
|
3246
|
+
CLAUDE_NESTED_SESSION_KEYS,
|
|
1855
3247
|
claudeChildEnv,
|
|
1856
3248
|
CLAUDE_MAX_TURNS_ENV,
|
|
1857
3249
|
CLAUDE_MAX_BUDGET_USD_ENV,
|
|
1858
3250
|
claudeRunCaps,
|
|
1859
3251
|
claudeRedactions,
|
|
1860
|
-
whichBinary,
|
|
1861
3252
|
spawnLogged,
|
|
1862
3253
|
cursorAgentHeadlessArgs,
|
|
1863
3254
|
cursorAgentReviewArgs,
|