@codelia/cli 0.1.86 → 0.1.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-VNP4GLGX.js +66 -0
- package/dist/chunk-BFVVMMRM.js +202 -0
- package/dist/chunk-PG452V5E.js +45 -0
- package/dist/chunk-QYWLK4HY.js +156 -0
- package/dist/chunk-S7OVJIGV.js +1052 -0
- package/dist/index.cjs +3243 -1564
- package/dist/index.js +48 -1575
- package/dist/launch-OTCP4VZR.js +9 -0
- package/dist/launcher-TKAK6K4J.js +19 -0
- package/dist/mcp-GB4CGP6K.js +699 -0
- package/dist/prompt-mode-BYUIUSIO.js +705 -0
- package/dist/session-2EB4JKFW.js +52 -0
- package/dist/update-SEBHPMUD.js +124 -0
- package/package.json +10 -10
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveRuntimeEnvForTui
|
|
3
|
+
} from "./chunk-BFVVMMRM.js";
|
|
4
|
+
import "./chunk-PG452V5E.js";
|
|
5
|
+
import "./chunk-QYWLK4HY.js";
|
|
6
|
+
import "./chunk-S7OVJIGV.js";
|
|
7
|
+
|
|
8
|
+
// src/prompt-mode.ts
|
|
9
|
+
import { spawn } from "child_process";
|
|
10
|
+
|
|
11
|
+
// src/atif.ts
|
|
12
|
+
import { mkdir, rename, writeFile } from "fs/promises";
|
|
13
|
+
import path from "path";
|
|
14
|
+
import { readRunLogLines } from "@codelia/storage";
|
|
15
|
+
var asRecord = (value) => typeof value === "object" && value !== null ? value : null;
|
|
16
|
+
var asString = (value) => typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
17
|
+
var stringifyContent = (value) => {
|
|
18
|
+
if (typeof value === "string") return value;
|
|
19
|
+
if (value == null) return "";
|
|
20
|
+
try {
|
|
21
|
+
return JSON.stringify(value);
|
|
22
|
+
} catch {
|
|
23
|
+
return String(value);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var normalizeTimestamp = (value) => {
|
|
27
|
+
const raw = asString(value);
|
|
28
|
+
if (!raw) return void 0;
|
|
29
|
+
const date = new Date(raw);
|
|
30
|
+
if (Number.isNaN(date.getTime())) return raw;
|
|
31
|
+
return date.toISOString();
|
|
32
|
+
};
|
|
33
|
+
var extractInputText = (input) => {
|
|
34
|
+
const direct = asRecord(input);
|
|
35
|
+
if (!direct) return asString(input);
|
|
36
|
+
if (direct.type === "text") return asString(direct.text);
|
|
37
|
+
return stringifyContent(direct);
|
|
38
|
+
};
|
|
39
|
+
var extractModelName = (record) => {
|
|
40
|
+
const model = asRecord(record?.model);
|
|
41
|
+
return asString(model?.name) ?? asString(model?.id);
|
|
42
|
+
};
|
|
43
|
+
var extractSessionId = (header, runStart, fallbackRunId) => asString(header?.session_id) ?? asString(runStart?.session_id) ?? asString(asRecord(runStart?.output)?.session_id) ?? fallbackRunId;
|
|
44
|
+
var createStepIdAllocator = () => {
|
|
45
|
+
let next = 1;
|
|
46
|
+
return () => next++;
|
|
47
|
+
};
|
|
48
|
+
var pushTextStep = (steps, nextStepId, source, message, timestamp, extra) => {
|
|
49
|
+
if (!message?.trim()) return;
|
|
50
|
+
steps.push({
|
|
51
|
+
step_id: nextStepId(),
|
|
52
|
+
...timestamp ? { timestamp } : {},
|
|
53
|
+
source,
|
|
54
|
+
message,
|
|
55
|
+
...extra ? { extra } : {}
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
var getOrCreateToolStep = (steps, nextStepId, callId, timestamp) => {
|
|
59
|
+
const existing = steps.find(
|
|
60
|
+
(step2) => step2.tool_calls?.some((call) => call.tool_call_id === callId)
|
|
61
|
+
);
|
|
62
|
+
if (existing) return existing;
|
|
63
|
+
const step = {
|
|
64
|
+
step_id: nextStepId(),
|
|
65
|
+
...timestamp ? { timestamp } : {},
|
|
66
|
+
source: "agent",
|
|
67
|
+
message: "",
|
|
68
|
+
tool_calls: []
|
|
69
|
+
};
|
|
70
|
+
steps.push(step);
|
|
71
|
+
return step;
|
|
72
|
+
};
|
|
73
|
+
var extractUsageMetrics = (records) => {
|
|
74
|
+
return records.map((record) => asRecord(asRecord(record.output)?.usage)).filter((usage) => !!usage).reduce(
|
|
75
|
+
(acc, usage) => {
|
|
76
|
+
acc.total_prompt_tokens += Number(usage.input_tokens ?? 0);
|
|
77
|
+
acc.total_completion_tokens += Number(usage.output_tokens ?? 0);
|
|
78
|
+
acc.total_cached_tokens += Number(
|
|
79
|
+
usage.input_cached_tokens ?? asRecord(usage.input_tokens_details)?.cached_tokens ?? 0
|
|
80
|
+
);
|
|
81
|
+
return acc;
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
total_prompt_tokens: 0,
|
|
85
|
+
total_completion_tokens: 0,
|
|
86
|
+
total_cached_tokens: 0
|
|
87
|
+
}
|
|
88
|
+
);
|
|
89
|
+
};
|
|
90
|
+
var sessionRecordsToAtif = (records, runId) => {
|
|
91
|
+
const header = records.find((record) => record.type === "header");
|
|
92
|
+
const runStart = records.find((record) => record.type === "run.start");
|
|
93
|
+
const modelName = extractModelName(header);
|
|
94
|
+
const nextStepId = createStepIdAllocator();
|
|
95
|
+
const steps = [];
|
|
96
|
+
pushTextStep(
|
|
97
|
+
steps,
|
|
98
|
+
nextStepId,
|
|
99
|
+
"user",
|
|
100
|
+
extractInputText(asRecord(runStart?.input)),
|
|
101
|
+
normalizeTimestamp(runStart?.ts),
|
|
102
|
+
{ source_record: "run.start" }
|
|
103
|
+
);
|
|
104
|
+
for (const record of records) {
|
|
105
|
+
if (record.type !== "agent.event") continue;
|
|
106
|
+
const event = asRecord(record.event);
|
|
107
|
+
if (!event) continue;
|
|
108
|
+
const timestamp = normalizeTimestamp(record.ts);
|
|
109
|
+
const eventType = asString(event.type);
|
|
110
|
+
if (eventType === "text") {
|
|
111
|
+
pushTextStep(
|
|
112
|
+
steps,
|
|
113
|
+
nextStepId,
|
|
114
|
+
"agent",
|
|
115
|
+
asString(event.content),
|
|
116
|
+
timestamp,
|
|
117
|
+
{ source_record: "agent.event.text" }
|
|
118
|
+
);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (eventType === "reasoning") {
|
|
122
|
+
const content = asString(event.content);
|
|
123
|
+
if (!content) continue;
|
|
124
|
+
steps.push({
|
|
125
|
+
step_id: nextStepId(),
|
|
126
|
+
...timestamp ? { timestamp } : {},
|
|
127
|
+
source: "agent",
|
|
128
|
+
message: "",
|
|
129
|
+
reasoning_content: content,
|
|
130
|
+
extra: { source_record: "agent.event.reasoning" }
|
|
131
|
+
});
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (eventType === "tool_call") {
|
|
135
|
+
const callId = asString(event.tool_call_id) ?? `tool_call_${String(steps.length + 1)}`;
|
|
136
|
+
const step = getOrCreateToolStep(steps, nextStepId, callId, timestamp);
|
|
137
|
+
step.tool_calls ??= [];
|
|
138
|
+
step.tool_calls.push({
|
|
139
|
+
tool_call_id: callId,
|
|
140
|
+
function_name: asString(event.tool) ?? "unknown",
|
|
141
|
+
arguments: asRecord(event.args) ?? {}
|
|
142
|
+
});
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (eventType === "tool_result") {
|
|
146
|
+
const callId = asString(event.tool_call_id);
|
|
147
|
+
const step = callId ? getOrCreateToolStep(steps, nextStepId, callId, timestamp) : {
|
|
148
|
+
step_id: nextStepId(),
|
|
149
|
+
...timestamp ? { timestamp } : {},
|
|
150
|
+
source: "agent",
|
|
151
|
+
message: ""
|
|
152
|
+
};
|
|
153
|
+
if (!callId) steps.push(step);
|
|
154
|
+
step.observation ??= { results: [] };
|
|
155
|
+
step.observation.results.push({
|
|
156
|
+
...callId ? { source_call_id: callId } : {},
|
|
157
|
+
content: stringifyContent(event.result)
|
|
158
|
+
});
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (eventType === "final") {
|
|
162
|
+
pushTextStep(
|
|
163
|
+
steps,
|
|
164
|
+
nextStepId,
|
|
165
|
+
"agent",
|
|
166
|
+
asString(event.content),
|
|
167
|
+
timestamp,
|
|
168
|
+
{ source_record: "agent.event.final" }
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (steps.length === 0) {
|
|
173
|
+
steps.push({
|
|
174
|
+
step_id: nextStepId(),
|
|
175
|
+
source: "user",
|
|
176
|
+
message: "(no prompt captured)",
|
|
177
|
+
extra: { source_record: "fallback" }
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const compactUsage = records.filter((record) => record.type === "llm.usage");
|
|
181
|
+
const compactSequences = new Set(compactUsage.map((record) => record.seq));
|
|
182
|
+
const usage = extractUsageMetrics([
|
|
183
|
+
...compactUsage,
|
|
184
|
+
...records.filter(
|
|
185
|
+
(record) => record.type === "llm.response" && !compactSequences.has(record.seq)
|
|
186
|
+
)
|
|
187
|
+
]);
|
|
188
|
+
return {
|
|
189
|
+
schema_version: "ATIF-v1.6",
|
|
190
|
+
session_id: extractSessionId(header, runStart, runId),
|
|
191
|
+
agent: {
|
|
192
|
+
name: "codelia",
|
|
193
|
+
version: "unknown",
|
|
194
|
+
...modelName ? { model_name: modelName } : {}
|
|
195
|
+
},
|
|
196
|
+
steps,
|
|
197
|
+
final_metrics: {
|
|
198
|
+
...usage,
|
|
199
|
+
total_steps: steps.length
|
|
200
|
+
},
|
|
201
|
+
extra: {
|
|
202
|
+
run_id: runId,
|
|
203
|
+
source: "codelia-session-jsonl",
|
|
204
|
+
conversion: "session-records-to-atif-v1.6"
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
var parseSessionJsonl = (raw) => {
|
|
209
|
+
const out = [];
|
|
210
|
+
for (const line of raw.split("\n")) {
|
|
211
|
+
if (!line.trim()) continue;
|
|
212
|
+
try {
|
|
213
|
+
out.push(JSON.parse(line));
|
|
214
|
+
} catch {
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
};
|
|
219
|
+
var readSessionJsonl = async (filePath) => {
|
|
220
|
+
const lines = [];
|
|
221
|
+
for await (const line of readRunLogLines(filePath)) lines.push(line);
|
|
222
|
+
return parseSessionJsonl(lines.join("\n"));
|
|
223
|
+
};
|
|
224
|
+
var writeAtifFromSessionJsonl = async ({
|
|
225
|
+
sessionLogPath,
|
|
226
|
+
runId,
|
|
227
|
+
outPath,
|
|
228
|
+
extra
|
|
229
|
+
}) => {
|
|
230
|
+
const records = await readSessionJsonl(sessionLogPath);
|
|
231
|
+
const trajectory = sessionRecordsToAtif(records, runId);
|
|
232
|
+
if (extra) trajectory.extra = { ...extra, ...trajectory.extra };
|
|
233
|
+
await mkdir(path.dirname(outPath), { recursive: true });
|
|
234
|
+
const tempPath = `${outPath}.tmp-${process.pid}-${Date.now()}`;
|
|
235
|
+
await writeFile(tempPath, `${JSON.stringify(trajectory, null, 2)}
|
|
236
|
+
`, "utf8");
|
|
237
|
+
await rename(tempPath, outPath);
|
|
238
|
+
return trajectory;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
// src/prompt-mode.ts
|
|
242
|
+
var parseShellLikeArgs = (value) => {
|
|
243
|
+
const out = [];
|
|
244
|
+
let current = "";
|
|
245
|
+
let quote = null;
|
|
246
|
+
let escaping = false;
|
|
247
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
248
|
+
const ch = value[i];
|
|
249
|
+
if (escaping) {
|
|
250
|
+
current += ch;
|
|
251
|
+
escaping = false;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (ch === "\\" && quote !== "single") {
|
|
255
|
+
escaping = true;
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (quote === "single") {
|
|
259
|
+
if (ch === "'") {
|
|
260
|
+
quote = null;
|
|
261
|
+
} else {
|
|
262
|
+
current += ch;
|
|
263
|
+
}
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (quote === "double") {
|
|
267
|
+
if (ch === '"') {
|
|
268
|
+
quote = null;
|
|
269
|
+
} else {
|
|
270
|
+
current += ch;
|
|
271
|
+
}
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (ch === "'") {
|
|
275
|
+
quote = "single";
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (ch === '"') {
|
|
279
|
+
quote = "double";
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (/\s/.test(ch)) {
|
|
283
|
+
if (current.length > 0) {
|
|
284
|
+
out.push(current);
|
|
285
|
+
current = "";
|
|
286
|
+
}
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
current += ch;
|
|
290
|
+
}
|
|
291
|
+
if (current.length > 0) {
|
|
292
|
+
out.push(current);
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
};
|
|
296
|
+
var toLine = (value) => `${JSON.stringify(value)}
|
|
297
|
+
`;
|
|
298
|
+
var envTruthy = (value) => {
|
|
299
|
+
if (!value) return false;
|
|
300
|
+
const normalized = value.trim().toLowerCase();
|
|
301
|
+
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
|
|
302
|
+
};
|
|
303
|
+
var toSingleLine = (value, maxChars = 240) => {
|
|
304
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
305
|
+
if (normalized.length <= maxChars) return normalized;
|
|
306
|
+
return `${normalized.slice(0, maxChars)}...`;
|
|
307
|
+
};
|
|
308
|
+
var summarizeProgressEvent = (event) => {
|
|
309
|
+
const type = typeof event.type === "string" ? event.type : "";
|
|
310
|
+
switch (type) {
|
|
311
|
+
case "text": {
|
|
312
|
+
const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
|
|
313
|
+
return content ? `[text] ${content}` : "[text]";
|
|
314
|
+
}
|
|
315
|
+
case "reasoning": {
|
|
316
|
+
const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
|
|
317
|
+
return content ? `[reasoning] ${content}` : "[reasoning]";
|
|
318
|
+
}
|
|
319
|
+
case "step_start": {
|
|
320
|
+
const title = typeof event.title === "string" ? toSingleLine(event.title) : "";
|
|
321
|
+
const stepNumber = typeof event.step_number === "number" ? `#${String(event.step_number)} ` : "";
|
|
322
|
+
return `[step_start] ${stepNumber}${title || "unnamed step"}`;
|
|
323
|
+
}
|
|
324
|
+
case "step_complete": {
|
|
325
|
+
const status = typeof event.status === "string" ? event.status : "unknown";
|
|
326
|
+
const duration = typeof event.duration_ms === "number" ? ` ${String(event.duration_ms)}ms` : "";
|
|
327
|
+
return `[step_complete] ${status}${duration}`;
|
|
328
|
+
}
|
|
329
|
+
case "tool_call": {
|
|
330
|
+
const tool = typeof event.tool === "string" ? event.tool : "unknown";
|
|
331
|
+
return `[tool_call] ${tool}`;
|
|
332
|
+
}
|
|
333
|
+
case "tool_result": {
|
|
334
|
+
const tool = typeof event.tool === "string" ? event.tool : "unknown";
|
|
335
|
+
const isError = event.is_error === true ? "error" : "ok";
|
|
336
|
+
return `[tool_result] ${tool} (${isError})`;
|
|
337
|
+
}
|
|
338
|
+
case "permission.preview": {
|
|
339
|
+
const tool = typeof event.tool === "string" ? event.tool : "unknown";
|
|
340
|
+
return `[permission.preview] ${tool}`;
|
|
341
|
+
}
|
|
342
|
+
case "permission.ready": {
|
|
343
|
+
const tool = typeof event.tool === "string" ? event.tool : "unknown";
|
|
344
|
+
return `[permission.ready] ${tool}`;
|
|
345
|
+
}
|
|
346
|
+
case "compaction_start":
|
|
347
|
+
return "[compaction_start]";
|
|
348
|
+
case "compaction_complete": {
|
|
349
|
+
const compacted = typeof event.compacted === "boolean" ? ` compacted=${String(event.compacted)}` : "";
|
|
350
|
+
return `[compaction_complete]${compacted}`;
|
|
351
|
+
}
|
|
352
|
+
case "hidden_user_message":
|
|
353
|
+
return "[hidden_user_message]";
|
|
354
|
+
default:
|
|
355
|
+
return type ? `[${type}]` : null;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
var isRpcResponse = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "id" in value && !value.method;
|
|
359
|
+
var isRpcNotification = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "method" in value && !value.id;
|
|
360
|
+
var asRecord2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
361
|
+
var harborUiResponse = (value, runId, allowShell) => {
|
|
362
|
+
const request = asRecord2(value);
|
|
363
|
+
if (request?.jsonrpc !== "2.0" || typeof request.id !== "string" || !/^ui_[1-9]\d*$/u.test(request.id))
|
|
364
|
+
return void 0;
|
|
365
|
+
const response = { jsonrpc: "2.0", id: request.id };
|
|
366
|
+
switch (request.method) {
|
|
367
|
+
case "ui.confirm.request":
|
|
368
|
+
return { ...response, result: { ok: false } };
|
|
369
|
+
case "ui.prompt.request":
|
|
370
|
+
return { ...response, result: { value: null } };
|
|
371
|
+
case "ui.pick.request": {
|
|
372
|
+
const params = asRecord2(request.params);
|
|
373
|
+
const choices = allowShell && runId !== null && params?.run_id === runId && params.approval === true && params.title === "Approve shell?" && (params.multi === void 0 || params.multi === false) && Array.isArray(params.items) ? params.items : [];
|
|
374
|
+
const once = choices.map((item) => asRecord2(item)?.id).filter(
|
|
375
|
+
(id) => typeof id === "string" && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\/allow_once$/u.test(id)
|
|
376
|
+
);
|
|
377
|
+
return { ...response, result: { ids: once.length === 1 ? once : [] } };
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
var writePromptModeAtif = async ({
|
|
382
|
+
atifOut,
|
|
383
|
+
sessionLogPath,
|
|
384
|
+
runId,
|
|
385
|
+
sandboxModeRequested,
|
|
386
|
+
sandboxModeReported
|
|
387
|
+
}) => {
|
|
388
|
+
if (!atifOut) {
|
|
389
|
+
return "skipped";
|
|
390
|
+
}
|
|
391
|
+
if (!sessionLogPath || !runId) {
|
|
392
|
+
throw new Error("CODELIA_ATIF_OUT was set but session log path is missing");
|
|
393
|
+
}
|
|
394
|
+
await writeAtifFromSessionJsonl({
|
|
395
|
+
sessionLogPath,
|
|
396
|
+
runId,
|
|
397
|
+
outPath: atifOut,
|
|
398
|
+
...sandboxModeRequested ? {
|
|
399
|
+
extra: {
|
|
400
|
+
sandbox_mode_requested: sandboxModeRequested,
|
|
401
|
+
sandbox_mode: sandboxModeReported ?? null
|
|
402
|
+
}
|
|
403
|
+
} : {}
|
|
404
|
+
});
|
|
405
|
+
return "written";
|
|
406
|
+
};
|
|
407
|
+
var runPromptMode = async (options) => {
|
|
408
|
+
const emitProgressToStderr = envTruthy(
|
|
409
|
+
process.env.CODELIA_PROMPT_PROGRESS_STDERR
|
|
410
|
+
);
|
|
411
|
+
const atifOut = process.env.CODELIA_ATIF_OUT?.trim();
|
|
412
|
+
const harborShellRequested = options.harborShellApproval === true && options.sandboxMode === "full-access" && process.env.CODELIA_HARBOR_SHELL_APPROVAL === "1";
|
|
413
|
+
const runtimeEnv = resolveRuntimeEnvForTui(process.env);
|
|
414
|
+
const runtimeCmd = runtimeEnv.CODELIA_RUNTIME_CMD ?? process.execPath;
|
|
415
|
+
const runtimeArgsValue = runtimeEnv.CODELIA_RUNTIME_ARGS ?? "packages/runtime/src/index.ts";
|
|
416
|
+
const runtimeArgs = parseShellLikeArgs(runtimeArgsValue);
|
|
417
|
+
if (runtimeArgs.length === 0) {
|
|
418
|
+
runtimeArgs.push("packages/runtime/src/index.ts");
|
|
419
|
+
}
|
|
420
|
+
if (options.sandboxMode) {
|
|
421
|
+
runtimeArgs.push("--sandbox-mode", options.sandboxMode);
|
|
422
|
+
}
|
|
423
|
+
if (options.approvalMode) {
|
|
424
|
+
runtimeArgs.push("--approval-mode", options.approvalMode);
|
|
425
|
+
}
|
|
426
|
+
const child = spawn(runtimeCmd, runtimeArgs, {
|
|
427
|
+
env: runtimeEnv,
|
|
428
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
429
|
+
});
|
|
430
|
+
let buffer = "";
|
|
431
|
+
let runId = null;
|
|
432
|
+
let reportedSandbox = null;
|
|
433
|
+
let harborShellAllowed = false;
|
|
434
|
+
let sessionLogPath = null;
|
|
435
|
+
let finalText = "";
|
|
436
|
+
let terminalStatus = null;
|
|
437
|
+
let terminalMessage;
|
|
438
|
+
let atifWritten = false;
|
|
439
|
+
let atifWriteInFlight = null;
|
|
440
|
+
const pendingResponses = /* @__PURE__ */ new Map();
|
|
441
|
+
let startupFailure = null;
|
|
442
|
+
const failPending = (error) => {
|
|
443
|
+
if (startupFailure) return;
|
|
444
|
+
startupFailure = error;
|
|
445
|
+
for (const pending of pendingResponses.values()) {
|
|
446
|
+
pending.reject(error);
|
|
447
|
+
}
|
|
448
|
+
pendingResponses.clear();
|
|
449
|
+
};
|
|
450
|
+
const waitResponse = (id) => {
|
|
451
|
+
if (startupFailure) {
|
|
452
|
+
return Promise.reject(startupFailure);
|
|
453
|
+
}
|
|
454
|
+
return new Promise((resolve, reject) => {
|
|
455
|
+
pendingResponses.set(id, { resolve, reject });
|
|
456
|
+
});
|
|
457
|
+
};
|
|
458
|
+
const sendMessage = (request) => {
|
|
459
|
+
if (startupFailure) {
|
|
460
|
+
throw startupFailure;
|
|
461
|
+
}
|
|
462
|
+
const wrote = child.stdin.write(toLine(request));
|
|
463
|
+
if (!wrote) {
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
const writeAtifOnce = async () => {
|
|
467
|
+
if (atifWritten) {
|
|
468
|
+
return "written";
|
|
469
|
+
}
|
|
470
|
+
atifWriteInFlight ??= writePromptModeAtif({
|
|
471
|
+
atifOut,
|
|
472
|
+
sessionLogPath,
|
|
473
|
+
runId,
|
|
474
|
+
sandboxModeRequested: options.sandboxMode,
|
|
475
|
+
sandboxModeReported: reportedSandbox
|
|
476
|
+
});
|
|
477
|
+
const result = await atifWriteInFlight;
|
|
478
|
+
if (result === "written") {
|
|
479
|
+
atifWritten = true;
|
|
480
|
+
}
|
|
481
|
+
return result;
|
|
482
|
+
};
|
|
483
|
+
const signalNumbers = {
|
|
484
|
+
SIGHUP: 1,
|
|
485
|
+
SIGINT: 2,
|
|
486
|
+
SIGTERM: 15
|
|
487
|
+
};
|
|
488
|
+
const handledSignals = Object.keys(signalNumbers);
|
|
489
|
+
const handleTerminationSignal = (signal) => {
|
|
490
|
+
void (async () => {
|
|
491
|
+
try {
|
|
492
|
+
await writeAtifOnce();
|
|
493
|
+
} catch (error) {
|
|
494
|
+
console.error(
|
|
495
|
+
`Failed to write partial ATIF trajectory on ${signal}: ${error instanceof Error ? error.message : String(error)}`
|
|
496
|
+
);
|
|
497
|
+
} finally {
|
|
498
|
+
if (!child.killed) {
|
|
499
|
+
child.kill(signal);
|
|
500
|
+
}
|
|
501
|
+
process.exit(
|
|
502
|
+
128 + (signalNumbers[signal] ?? 1)
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
})();
|
|
506
|
+
};
|
|
507
|
+
for (const signal of handledSignals) {
|
|
508
|
+
process.once(signal, handleTerminationSignal);
|
|
509
|
+
}
|
|
510
|
+
const cleanupSignalHandlers = () => {
|
|
511
|
+
for (const signal of handledSignals) {
|
|
512
|
+
process.removeListener(signal, handleTerminationSignal);
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
const maybeTrackRunLifecycle = (value) => {
|
|
516
|
+
if (!isRpcNotification(value)) return;
|
|
517
|
+
if (value.method === "run.status") {
|
|
518
|
+
const params = value.params ?? {};
|
|
519
|
+
if (!runId || params.run_id !== runId) return;
|
|
520
|
+
if (params.status === "completed" || params.status === "error" || params.status === "cancelled") {
|
|
521
|
+
terminalStatus = params.status;
|
|
522
|
+
terminalMessage = params.message;
|
|
523
|
+
}
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
if (value.method === "run.end") {
|
|
527
|
+
const params = value.params ?? {};
|
|
528
|
+
if (!runId || params.run_id !== runId) return;
|
|
529
|
+
if (typeof params.final === "string") {
|
|
530
|
+
finalText = params.final;
|
|
531
|
+
}
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if (value.method === "agent.event") {
|
|
535
|
+
const params = value.params ?? {};
|
|
536
|
+
if (!runId || params.run_id !== runId) return;
|
|
537
|
+
if (params.event?.type === "final" && typeof params.event.content === "string") {
|
|
538
|
+
finalText = params.event.content;
|
|
539
|
+
}
|
|
540
|
+
const event = params.event;
|
|
541
|
+
if (emitProgressToStderr && event && event.type !== "final") {
|
|
542
|
+
const summary = summarizeProgressEvent(event);
|
|
543
|
+
if (summary) {
|
|
544
|
+
process.stderr.write(`${summary}
|
|
545
|
+
`);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
child.on("error", (error) => {
|
|
551
|
+
failPending(
|
|
552
|
+
error instanceof Error ? error : new Error(`runtime process error: ${String(error)}`)
|
|
553
|
+
);
|
|
554
|
+
});
|
|
555
|
+
child.on("close", (code, signal) => {
|
|
556
|
+
if (terminalStatus) return;
|
|
557
|
+
failPending(
|
|
558
|
+
new Error(
|
|
559
|
+
`runtime exited before completion (code=${String(code)} signal=${String(signal)})`
|
|
560
|
+
)
|
|
561
|
+
);
|
|
562
|
+
});
|
|
563
|
+
child.stdin.on("error", (error) => {
|
|
564
|
+
failPending(
|
|
565
|
+
error instanceof Error ? error : new Error(`runtime stdin error: ${String(error)}`)
|
|
566
|
+
);
|
|
567
|
+
});
|
|
568
|
+
child.stdout.setEncoding("utf8");
|
|
569
|
+
child.stdout.on("data", (chunk) => {
|
|
570
|
+
buffer += chunk;
|
|
571
|
+
let index = buffer.indexOf("\n");
|
|
572
|
+
while (index >= 0) {
|
|
573
|
+
const line = buffer.slice(0, index).trim();
|
|
574
|
+
buffer = buffer.slice(index + 1);
|
|
575
|
+
if (line.length > 0) {
|
|
576
|
+
try {
|
|
577
|
+
const parsed = JSON.parse(line);
|
|
578
|
+
if (isRpcResponse(parsed)) {
|
|
579
|
+
const pending = pendingResponses.get(String(parsed.id));
|
|
580
|
+
if (pending) {
|
|
581
|
+
pendingResponses.delete(String(parsed.id));
|
|
582
|
+
if (parsed.id === "run-1") {
|
|
583
|
+
const result = asRecord2(parsed.result);
|
|
584
|
+
runId = typeof result?.run_id === "string" ? result.run_id : null;
|
|
585
|
+
}
|
|
586
|
+
pending.resolve(parsed);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if (harborShellRequested) {
|
|
590
|
+
const response = harborUiResponse(
|
|
591
|
+
parsed,
|
|
592
|
+
terminalStatus ? null : runId,
|
|
593
|
+
harborShellAllowed
|
|
594
|
+
);
|
|
595
|
+
if (response) sendMessage(response);
|
|
596
|
+
}
|
|
597
|
+
maybeTrackRunLifecycle(parsed);
|
|
598
|
+
} catch {
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
index = buffer.indexOf("\n");
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
child.stderr.setEncoding("utf8");
|
|
605
|
+
child.stderr.on("data", (chunk) => {
|
|
606
|
+
process.stderr.write(chunk);
|
|
607
|
+
});
|
|
608
|
+
try {
|
|
609
|
+
sendMessage({
|
|
610
|
+
jsonrpc: "2.0",
|
|
611
|
+
id: "init-1",
|
|
612
|
+
method: "initialize",
|
|
613
|
+
params: {
|
|
614
|
+
protocol_version: "0",
|
|
615
|
+
client: { name: "codelia-cli-prompt", version: "0.1.0" },
|
|
616
|
+
ui_capabilities: {
|
|
617
|
+
supports_confirm: false,
|
|
618
|
+
supports_prompt: false,
|
|
619
|
+
supports_pick: harborShellRequested,
|
|
620
|
+
...harborShellRequested ? { supports_structured_approval: true } : {}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
const initResponse = await waitResponse("init-1");
|
|
625
|
+
if (initResponse.error) {
|
|
626
|
+
throw new Error(`initialize failed: ${initResponse.error.message}`);
|
|
627
|
+
}
|
|
628
|
+
const init = initResponse.result;
|
|
629
|
+
const mode = init?.sandbox_mode?.value;
|
|
630
|
+
reportedSandbox = mode === "readonly" || mode === "workspace-write" || mode === "full-access" ? mode : null;
|
|
631
|
+
harborShellAllowed = harborShellRequested && init?.server_capabilities?.supports_structured_approval === true && reportedSandbox === "full-access";
|
|
632
|
+
sendMessage({
|
|
633
|
+
jsonrpc: "2.0",
|
|
634
|
+
id: "run-1",
|
|
635
|
+
method: "run.start",
|
|
636
|
+
params: {
|
|
637
|
+
input: { type: "text", text: options.prompt }
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
const runResponse = await waitResponse("run-1");
|
|
641
|
+
if (runResponse.error) {
|
|
642
|
+
throw new Error(`run.start failed: ${runResponse.error.message}`);
|
|
643
|
+
}
|
|
644
|
+
const runResult = typeof runResponse.result === "object" && runResponse.result !== null ? runResponse.result : null;
|
|
645
|
+
sessionLogPath = typeof runResult?.session_log_path === "string" ? runResult.session_log_path : null;
|
|
646
|
+
if (!runId) {
|
|
647
|
+
throw new Error("run.start did not return run_id");
|
|
648
|
+
}
|
|
649
|
+
await new Promise((resolve, reject) => {
|
|
650
|
+
const timeout = setInterval(() => {
|
|
651
|
+
if (terminalStatus) {
|
|
652
|
+
clearInterval(timeout);
|
|
653
|
+
resolve();
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (startupFailure) {
|
|
657
|
+
clearInterval(timeout);
|
|
658
|
+
reject(startupFailure);
|
|
659
|
+
}
|
|
660
|
+
}, 50);
|
|
661
|
+
});
|
|
662
|
+
} catch (error) {
|
|
663
|
+
cleanupSignalHandlers();
|
|
664
|
+
console.error(
|
|
665
|
+
`Prompt run failed: ${error instanceof Error ? error.message : String(error)}`
|
|
666
|
+
);
|
|
667
|
+
return 1;
|
|
668
|
+
} finally {
|
|
669
|
+
if (!child.killed) {
|
|
670
|
+
child.kill();
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (terminalStatus === "completed") {
|
|
674
|
+
try {
|
|
675
|
+
await writeAtifOnce();
|
|
676
|
+
} catch (error) {
|
|
677
|
+
cleanupSignalHandlers();
|
|
678
|
+
console.error(
|
|
679
|
+
`Failed to write ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
|
|
680
|
+
);
|
|
681
|
+
return 1;
|
|
682
|
+
}
|
|
683
|
+
cleanupSignalHandlers();
|
|
684
|
+
if (finalText.trim().length > 0) {
|
|
685
|
+
console.log(finalText);
|
|
686
|
+
}
|
|
687
|
+
return 0;
|
|
688
|
+
}
|
|
689
|
+
try {
|
|
690
|
+
await writeAtifOnce();
|
|
691
|
+
} catch (error) {
|
|
692
|
+
console.error(
|
|
693
|
+
`Failed to write partial ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
cleanupSignalHandlers();
|
|
697
|
+
if (terminalMessage) {
|
|
698
|
+
console.error(terminalMessage);
|
|
699
|
+
}
|
|
700
|
+
return terminalStatus === "cancelled" ? 130 : 1;
|
|
701
|
+
};
|
|
702
|
+
export {
|
|
703
|
+
runPromptMode,
|
|
704
|
+
writePromptModeAtif
|
|
705
|
+
};
|