@evident-ai/cli 3.6.1-dev.00837f1 → 3.6.1-dev.0ac2fac
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/index.js +1932 -1728
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -335,14 +335,14 @@ function blank() {
|
|
|
335
335
|
console.log();
|
|
336
336
|
}
|
|
337
337
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
338
|
-
return new Promise((
|
|
338
|
+
return new Promise((resolve6) => {
|
|
339
339
|
process.stdout.write(chalk.dim(prompt));
|
|
340
340
|
const handler = () => {
|
|
341
341
|
process.stdin.removeListener("data", handler);
|
|
342
342
|
process.stdin.setRawMode?.(false);
|
|
343
343
|
process.stdin.pause();
|
|
344
344
|
console.log();
|
|
345
|
-
|
|
345
|
+
resolve6();
|
|
346
346
|
};
|
|
347
347
|
if (process.stdin.isTTY) {
|
|
348
348
|
process.stdin.setRawMode?.(true);
|
|
@@ -352,7 +352,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
352
352
|
});
|
|
353
353
|
}
|
|
354
354
|
function sleep(ms) {
|
|
355
|
-
return new Promise((
|
|
355
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
356
356
|
}
|
|
357
357
|
|
|
358
358
|
// src/commands/login.ts
|
|
@@ -430,19 +430,19 @@ async function tokenLogin() {
|
|
|
430
430
|
);
|
|
431
431
|
blank();
|
|
432
432
|
process.stdout.write("Paste token: ");
|
|
433
|
-
const token = await new Promise((
|
|
433
|
+
const token = await new Promise((resolve6) => {
|
|
434
434
|
let data = "";
|
|
435
435
|
process.stdin.setEncoding("utf8");
|
|
436
436
|
process.stdin.on("data", (chunk) => {
|
|
437
437
|
data += chunk;
|
|
438
438
|
});
|
|
439
439
|
process.stdin.on("end", () => {
|
|
440
|
-
|
|
440
|
+
resolve6(data.trim());
|
|
441
441
|
});
|
|
442
442
|
if (process.stdin.isTTY) {
|
|
443
443
|
process.stdin.once("data", (chunk) => {
|
|
444
444
|
process.stdin.pause();
|
|
445
|
-
|
|
445
|
+
resolve6(chunk.toString().trim());
|
|
446
446
|
});
|
|
447
447
|
process.stdin.resume();
|
|
448
448
|
}
|
|
@@ -1180,8 +1180,8 @@ async function claudeUsage() {
|
|
|
1180
1180
|
|
|
1181
1181
|
// src/commands/run.ts
|
|
1182
1182
|
import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
|
|
1183
|
-
import { homedir as
|
|
1184
|
-
import { isAbsolute as
|
|
1183
|
+
import { homedir as homedir9 } from "node:os";
|
|
1184
|
+
import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
|
|
1185
1185
|
import chalk7 from "chalk";
|
|
1186
1186
|
|
|
1187
1187
|
// ../../packages/types/src/agents/index.ts
|
|
@@ -1234,23 +1234,28 @@ function lastText(assistantRun) {
|
|
|
1234
1234
|
}
|
|
1235
1235
|
return null;
|
|
1236
1236
|
}
|
|
1237
|
-
function
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
if (userIndex === -1) return run2;
|
|
1237
|
+
function literalContinueRun(messages, userMessageId) {
|
|
1238
|
+
if (!messages) return [];
|
|
1239
|
+
const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
|
|
1240
|
+
if (userIndex === -1) return [];
|
|
1242
1241
|
let continuation;
|
|
1243
|
-
for (let i = userIndex + 1;
|
|
1242
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
1244
1243
|
if (roleOf(messages[i]) === "user") {
|
|
1245
1244
|
continuation = messages[i];
|
|
1246
1245
|
break;
|
|
1247
1246
|
}
|
|
1248
1247
|
}
|
|
1249
1248
|
const continuationId = idOf(continuation);
|
|
1250
|
-
if (roleOf(continuation)
|
|
1251
|
-
|
|
1252
|
-
if (continuationRun.length > 0) return continuationRun;
|
|
1249
|
+
if (roleOf(continuation) !== "user" || textPartsOf(continuation).join("\n").trim().toLowerCase() !== "continue" || !continuationId) {
|
|
1250
|
+
return [];
|
|
1253
1251
|
}
|
|
1252
|
+
return correlatedAssistantRun(messages, continuationId);
|
|
1253
|
+
}
|
|
1254
|
+
function effectiveCorrelatedRun(messages, userMessageId) {
|
|
1255
|
+
const run2 = correlatedAssistantRun(messages, userMessageId);
|
|
1256
|
+
if (lastText(run2) !== null) return run2;
|
|
1257
|
+
const continuationRun = literalContinueRun(messages, userMessageId);
|
|
1258
|
+
if (continuationRun.length > 0) return continuationRun;
|
|
1254
1259
|
return run2;
|
|
1255
1260
|
}
|
|
1256
1261
|
function extractReplyTextForMessage(messages, opencodeUserMessageId) {
|
|
@@ -1335,6 +1340,8 @@ function decodeBinaryBodyFrame(bytes) {
|
|
|
1335
1340
|
var MAX_FRAME_BYTES = 256 * 1024;
|
|
1336
1341
|
var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
|
|
1337
1342
|
var TUNNEL_USAGE_REARM_PING_PATH = "/__evident/usage-rearm";
|
|
1343
|
+
var TUNNEL_FILE_READ_PATH = "/__evident/file";
|
|
1344
|
+
var TUNNEL_FILE_READ_MAX_BYTES = 5 * 1024 * 1024;
|
|
1338
1345
|
|
|
1339
1346
|
// ../../packages/types/src/runner-files.ts
|
|
1340
1347
|
var MAX_FILE_PUSH_BYTES = 64 * 1024;
|
|
@@ -1475,7 +1482,7 @@ import ora4 from "ora";
|
|
|
1475
1482
|
import { select as select4 } from "@inquirer/prompts";
|
|
1476
1483
|
|
|
1477
1484
|
// src/lib/telemetry.ts
|
|
1478
|
-
var CLI_VERSION = (true ? "3.6.1-dev.
|
|
1485
|
+
var CLI_VERSION = (true ? "3.6.1-dev.0ac2fac" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
1479
1486
|
function getCliVersion() {
|
|
1480
1487
|
return CLI_VERSION;
|
|
1481
1488
|
}
|
|
@@ -2047,8 +2054,8 @@ function resolveExistingPath(absolutePath) {
|
|
|
2047
2054
|
let current = candidate;
|
|
2048
2055
|
while (current) {
|
|
2049
2056
|
try {
|
|
2050
|
-
const
|
|
2051
|
-
if (
|
|
2057
|
+
const stat3 = lstatSync(current);
|
|
2058
|
+
if (stat3.isSymbolicLink()) {
|
|
2052
2059
|
if (remaining.length === 0) {
|
|
2053
2060
|
return { path: join2(realpathSync(dirname3(current)), basename(current)) };
|
|
2054
2061
|
}
|
|
@@ -2099,15 +2106,15 @@ function classifyScope(dir, roots) {
|
|
|
2099
2106
|
function unresolvedRootForPath(path, unresolved) {
|
|
2100
2107
|
return unresolved.find((spec) => isWithin(path, spec.configured));
|
|
2101
2108
|
}
|
|
2102
|
-
function statType(
|
|
2103
|
-
if (
|
|
2104
|
-
if (
|
|
2105
|
-
if (
|
|
2109
|
+
function statType(stat3) {
|
|
2110
|
+
if (stat3.isDirectory()) return "d";
|
|
2111
|
+
if (stat3.isFile()) return "f";
|
|
2112
|
+
if (stat3.isSymbolicLink()) return "l";
|
|
2106
2113
|
return "o";
|
|
2107
2114
|
}
|
|
2108
|
-
function renderStat(name,
|
|
2109
|
-
const mode = (
|
|
2110
|
-
return `${name}:${statType(
|
|
2115
|
+
function renderStat(name, stat3) {
|
|
2116
|
+
const mode = (stat3.mode & 4095).toString(8).padStart(4, "0");
|
|
2117
|
+
return `${name}:${statType(stat3)}:${stat3.uid}:${stat3.gid}:${mode}`;
|
|
2111
2118
|
}
|
|
2112
2119
|
function renderStatError(name, error2) {
|
|
2113
2120
|
const code = getErrorCode(error2);
|
|
@@ -2133,9 +2140,9 @@ function inspectChain(rootReal, rootToken, absolutePath, resolutionFailure) {
|
|
|
2133
2140
|
break;
|
|
2134
2141
|
}
|
|
2135
2142
|
try {
|
|
2136
|
-
const
|
|
2137
|
-
entries.push(renderStat(name,
|
|
2138
|
-
finalStat =
|
|
2143
|
+
const stat3 = lstatSync(current);
|
|
2144
|
+
entries.push(renderStat(name, stat3));
|
|
2145
|
+
finalStat = stat3;
|
|
2139
2146
|
} catch (error2) {
|
|
2140
2147
|
entries.push(renderStatError(name, error2));
|
|
2141
2148
|
if (getErrorCode(error2) !== "ENOENT") status2 = "stat_failed";
|
|
@@ -3355,7 +3362,7 @@ function appendError(stderr, error2) {
|
|
|
3355
3362
|
${message}`;
|
|
3356
3363
|
}
|
|
3357
3364
|
function runSynchroniser(args, opts) {
|
|
3358
|
-
return new Promise((
|
|
3365
|
+
return new Promise((resolve6) => {
|
|
3359
3366
|
let child;
|
|
3360
3367
|
let stdout = "";
|
|
3361
3368
|
let stderr = "";
|
|
@@ -3375,7 +3382,7 @@ function runSynchroniser(args, opts) {
|
|
|
3375
3382
|
if (closeFallbackTimer.handle) clearTimeout(closeFallbackTimer.handle);
|
|
3376
3383
|
if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
|
|
3377
3384
|
if (spawnListener) child.removeListener("spawn", spawnListener);
|
|
3378
|
-
|
|
3385
|
+
resolve6(result);
|
|
3379
3386
|
};
|
|
3380
3387
|
const armErrorCloseFallback = () => {
|
|
3381
3388
|
if (closeFallbackTimer.handle) return;
|
|
@@ -4046,7 +4053,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
4046
4053
|
if (health.healthy || health.authFailed) {
|
|
4047
4054
|
return health;
|
|
4048
4055
|
}
|
|
4049
|
-
await new Promise((
|
|
4056
|
+
await new Promise((resolve6) => setTimeout(resolve6, 1e3));
|
|
4050
4057
|
}
|
|
4051
4058
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
4052
4059
|
}
|
|
@@ -4057,7 +4064,7 @@ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
|
|
|
4057
4064
|
if (health.healthy || health.authFailed) {
|
|
4058
4065
|
return health;
|
|
4059
4066
|
}
|
|
4060
|
-
await new Promise((
|
|
4067
|
+
await new Promise((resolve6) => setTimeout(resolve6, 1e3));
|
|
4061
4068
|
}
|
|
4062
4069
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
4063
4070
|
}
|
|
@@ -4167,1827 +4174,1786 @@ function createOpenCodeClient(options) {
|
|
|
4167
4174
|
};
|
|
4168
4175
|
}
|
|
4169
4176
|
|
|
4170
|
-
// src/lib/opencode/session.ts
|
|
4177
|
+
// src/lib/opencode/session-v2.ts
|
|
4171
4178
|
var ALL_HTTP_STATUSES = Array.from({ length: 500 }, (_, index) => index + 100);
|
|
4172
|
-
function
|
|
4173
|
-
return
|
|
4179
|
+
function isRecord5(value) {
|
|
4180
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4174
4181
|
}
|
|
4175
|
-
function
|
|
4176
|
-
return
|
|
4182
|
+
function finiteNumber(value) {
|
|
4183
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
4177
4184
|
}
|
|
4178
|
-
function
|
|
4179
|
-
return
|
|
4185
|
+
function adaptTime(value) {
|
|
4186
|
+
if (!isRecord5(value)) return void 0;
|
|
4187
|
+
const created = finiteNumber(value.created);
|
|
4188
|
+
const completed = finiteNumber(value.completed);
|
|
4189
|
+
if (created === void 0 && completed === void 0) return void 0;
|
|
4190
|
+
return {
|
|
4191
|
+
...created !== void 0 ? { created } : {},
|
|
4192
|
+
...completed !== void 0 ? { completed } : {}
|
|
4193
|
+
};
|
|
4180
4194
|
}
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
4186
|
-
|
|
4187
|
-
|
|
4188
|
-
|
|
4189
|
-
|
|
4190
|
-
|
|
4191
|
-
|
|
4192
|
-
return null;
|
|
4195
|
+
function adaptTokens(value) {
|
|
4196
|
+
if (!isRecord5(value)) return void 0;
|
|
4197
|
+
const input = finiteNumber(value.input);
|
|
4198
|
+
const output = finiteNumber(value.output);
|
|
4199
|
+
const reasoning = finiteNumber(value.reasoning);
|
|
4200
|
+
const cache = isRecord5(value.cache) ? {
|
|
4201
|
+
...finiteNumber(value.cache.read) !== void 0 ? { read: finiteNumber(value.cache.read) } : {},
|
|
4202
|
+
...finiteNumber(value.cache.write) !== void 0 ? { write: finiteNumber(value.cache.write) } : {}
|
|
4203
|
+
} : void 0;
|
|
4204
|
+
if (input === void 0 && output === void 0 && reasoning === void 0 && !cache) {
|
|
4205
|
+
return void 0;
|
|
4193
4206
|
}
|
|
4207
|
+
return {
|
|
4208
|
+
...input !== void 0 ? { input } : {},
|
|
4209
|
+
...output !== void 0 ? { output } : {},
|
|
4210
|
+
...reasoning !== void 0 ? { reasoning } : {},
|
|
4211
|
+
...cache ? { cache } : {}
|
|
4212
|
+
};
|
|
4194
4213
|
}
|
|
4195
|
-
function
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4214
|
+
function adaptMessageInfo(value, role) {
|
|
4215
|
+
const info = {
|
|
4216
|
+
id: value.id,
|
|
4217
|
+
role
|
|
4218
|
+
};
|
|
4219
|
+
const time = adaptTime(value.time);
|
|
4220
|
+
if (time) info.time = time;
|
|
4221
|
+
if (typeof value.finish === "string") info.finish = value.finish;
|
|
4222
|
+
if ("error" in value) info.error = value.error;
|
|
4223
|
+
if (typeof value.agent === "string") info.agent = value.agent;
|
|
4224
|
+
if (isRecord5(value.model)) {
|
|
4225
|
+
if (typeof value.model.id === "string") info.modelID = value.model.id;
|
|
4226
|
+
if (typeof value.model.providerID === "string") info.providerID = value.model.providerID;
|
|
4227
|
+
}
|
|
4228
|
+
if (typeof value.cost === "number" && Number.isFinite(value.cost)) info.cost = value.cost;
|
|
4229
|
+
const tokens = adaptTokens(value.tokens);
|
|
4230
|
+
if (tokens) info.tokens = tokens;
|
|
4231
|
+
return info;
|
|
4200
4232
|
}
|
|
4201
|
-
function
|
|
4202
|
-
|
|
4203
|
-
|
|
4233
|
+
function v2ChildSessionEvidence(content) {
|
|
4234
|
+
const state = isRecord5(content.state) ? content.state : null;
|
|
4235
|
+
const metadata = state && isRecord5(state.metadata) ? state.metadata : null;
|
|
4236
|
+
const sessionId = typeof metadata?.sessionID === "string" && metadata.sessionID.length > 0 ? metadata.sessionID : typeof metadata?.sessionId === "string" && metadata.sessionId.length > 0 ? metadata.sessionId : null;
|
|
4237
|
+
if (sessionId === null) return null;
|
|
4238
|
+
const time = isRecord5(content.time) ? content.time : null;
|
|
4239
|
+
return { sessionId, startedAtMs: finiteNumber(time?.created) ?? null };
|
|
4204
4240
|
}
|
|
4205
|
-
function
|
|
4206
|
-
if (!
|
|
4207
|
-
|
|
4241
|
+
function adaptV2Message(value) {
|
|
4242
|
+
if (!isRecord5(value) || typeof value.id !== "string" || typeof value.type !== "string") {
|
|
4243
|
+
return null;
|
|
4244
|
+
}
|
|
4245
|
+
if (value.type === "user") {
|
|
4246
|
+
if (typeof value.text !== "string") return null;
|
|
4247
|
+
return {
|
|
4248
|
+
info: adaptMessageInfo(value, "user"),
|
|
4249
|
+
parts: [{ type: "text", text: value.text }]
|
|
4250
|
+
};
|
|
4251
|
+
}
|
|
4252
|
+
if (value.type !== "assistant" || !Array.isArray(value.content)) return null;
|
|
4253
|
+
const parts = [];
|
|
4254
|
+
for (const content of value.content) {
|
|
4255
|
+
if (!isRecord5(content) || typeof content.type !== "string") return null;
|
|
4256
|
+
const toolPart = projectV2ToolContent(content);
|
|
4257
|
+
if (toolPart) {
|
|
4258
|
+
const childSession = v2ChildSessionEvidence(content);
|
|
4259
|
+
parts.push(childSession ? { ...toolPart, childSession } : toolPart);
|
|
4260
|
+
continue;
|
|
4261
|
+
}
|
|
4262
|
+
if (content.type === "text") {
|
|
4263
|
+
if (typeof content.text !== "string") return null;
|
|
4264
|
+
parts.push({ type: "text", text: content.text });
|
|
4265
|
+
} else {
|
|
4266
|
+
parts.push({ type: content.type });
|
|
4267
|
+
}
|
|
4268
|
+
}
|
|
4269
|
+
return {
|
|
4270
|
+
info: adaptMessageInfo(value, "assistant"),
|
|
4271
|
+
parts
|
|
4272
|
+
};
|
|
4208
4273
|
}
|
|
4209
|
-
function
|
|
4210
|
-
if (!
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
return
|
|
4274
|
+
function adaptFormTool(value) {
|
|
4275
|
+
if (!isRecord5(value) || typeof value.messageID !== "string" || typeof value.id !== "string") {
|
|
4276
|
+
return void 0;
|
|
4277
|
+
}
|
|
4278
|
+
return { messageID: value.messageID, callID: value.id };
|
|
4214
4279
|
}
|
|
4215
|
-
function
|
|
4216
|
-
if (!
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
return
|
|
4280
|
+
function adaptV2FormWire(value) {
|
|
4281
|
+
if (!isRecord5(value) || typeof value.id !== "string" || typeof value.sessionID !== "string") {
|
|
4282
|
+
return null;
|
|
4283
|
+
}
|
|
4284
|
+
return value;
|
|
4220
4285
|
}
|
|
4221
|
-
function
|
|
4222
|
-
if (!
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
|
|
4286
|
+
function adaptV2FormField(value, header) {
|
|
4287
|
+
if (!isRecord5(value)) return null;
|
|
4288
|
+
const question = typeof value.title === "string" ? value.title : typeof value.question === "string" ? value.question : typeof value.key === "string" ? value.key : null;
|
|
4289
|
+
if (!question) return null;
|
|
4290
|
+
const options = Array.isArray(value.options) ? value.options.flatMap((option) => {
|
|
4291
|
+
if (!isRecord5(option)) return [];
|
|
4292
|
+
const label = typeof option.label === "string" ? option.label : typeof option.value === "string" ? option.value : null;
|
|
4293
|
+
if (!label) return [];
|
|
4294
|
+
return [
|
|
4295
|
+
{
|
|
4296
|
+
label,
|
|
4297
|
+
description: typeof option.description === "string" ? option.description : ""
|
|
4298
|
+
}
|
|
4299
|
+
];
|
|
4300
|
+
}) : [];
|
|
4301
|
+
return { question, header, options };
|
|
4226
4302
|
}
|
|
4227
|
-
function
|
|
4228
|
-
|
|
4229
|
-
|
|
4303
|
+
function adaptV2Form(value) {
|
|
4304
|
+
const form = adaptV2FormWire(value);
|
|
4305
|
+
if (!form || !Array.isArray(form.fields)) return null;
|
|
4306
|
+
const header = typeof form.title === "string" ? form.title : "";
|
|
4307
|
+
const questions = form.fields.map((field) => adaptV2FormField(field, header)).filter((question) => question !== null);
|
|
4308
|
+
if (questions.length === 0) return null;
|
|
4309
|
+
const tool = isRecord5(form.metadata) ? adaptFormTool(form.metadata.tool) : void 0;
|
|
4310
|
+
return {
|
|
4311
|
+
id: form.id,
|
|
4312
|
+
sessionID: form.sessionID,
|
|
4313
|
+
questions,
|
|
4314
|
+
...tool ? { tool } : {},
|
|
4315
|
+
raw: form
|
|
4316
|
+
};
|
|
4230
4317
|
}
|
|
4231
|
-
function
|
|
4232
|
-
|
|
4318
|
+
function adaptV2FormList(value) {
|
|
4319
|
+
if (!isRecord5(value) || !Array.isArray(value.data)) return null;
|
|
4320
|
+
return value.data.map(adaptV2Form).filter((form) => form !== null);
|
|
4233
4321
|
}
|
|
4234
|
-
function
|
|
4235
|
-
if (
|
|
4236
|
-
if (
|
|
4237
|
-
|
|
4322
|
+
function adaptPattern(value) {
|
|
4323
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
4324
|
+
if (Array.isArray(value) && value.every((pattern) => typeof pattern === "string")) {
|
|
4325
|
+
return value;
|
|
4326
|
+
}
|
|
4327
|
+
return void 0;
|
|
4238
4328
|
}
|
|
4239
|
-
|
|
4240
|
-
|
|
4241
|
-
const path = `/session/${sessionId}/message`;
|
|
4242
|
-
const res = await requestWithClient(port, client, path);
|
|
4243
|
-
if (!res.ok) return null;
|
|
4244
|
-
const body = await res.json();
|
|
4245
|
-
return Array.isArray(body) ? body : null;
|
|
4246
|
-
} catch (error2) {
|
|
4247
|
-
console.error(
|
|
4248
|
-
`[getSessionMessages] GET /session/${sessionId}/message failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4249
|
-
);
|
|
4329
|
+
function adaptV2PermissionWire(value) {
|
|
4330
|
+
if (!isRecord5(value) || typeof value.id !== "string" || typeof value.sessionID !== "string") {
|
|
4250
4331
|
return null;
|
|
4251
4332
|
}
|
|
4333
|
+
if (typeof value.permission !== "string" && typeof value.action !== "string") return null;
|
|
4334
|
+
return value;
|
|
4252
4335
|
}
|
|
4253
|
-
|
|
4254
|
-
const
|
|
4255
|
-
if (!
|
|
4256
|
-
const
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
}
|
|
4271
|
-
|
|
4272
|
-
if (!Array.isArray(body)) return { ok: false, status: null, body: "", malformed: true };
|
|
4273
|
-
return { ok: true, messages: body };
|
|
4274
|
-
} catch (error2) {
|
|
4275
|
-
console.error(
|
|
4276
|
-
`[pollSessionMessagesForRedrive] GET /session/${sessionId}/message failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4277
|
-
);
|
|
4278
|
-
return { ok: false, status: null, body: "", malformed: false };
|
|
4279
|
-
}
|
|
4336
|
+
function adaptV2Permission(value) {
|
|
4337
|
+
const permission = adaptV2PermissionWire(value);
|
|
4338
|
+
if (!permission) return null;
|
|
4339
|
+
const type = permission.permission ?? permission.action;
|
|
4340
|
+
if (!type) return null;
|
|
4341
|
+
const pattern = adaptPattern(permission.pattern) ?? adaptPattern(permission.patterns) ?? adaptPattern(permission.resources);
|
|
4342
|
+
const time = isRecord5(permission.time) ? finiteNumber(permission.time.created) !== void 0 ? { created: finiteNumber(permission.time.created) } : void 0 : void 0;
|
|
4343
|
+
return {
|
|
4344
|
+
id: permission.id,
|
|
4345
|
+
type,
|
|
4346
|
+
sessionID: permission.sessionID,
|
|
4347
|
+
metadata: isRecord5(permission.metadata) ? permission.metadata : {},
|
|
4348
|
+
raw: permission,
|
|
4349
|
+
...pattern !== void 0 ? { pattern } : {},
|
|
4350
|
+
...typeof permission.messageID === "string" ? { messageID: permission.messageID } : {},
|
|
4351
|
+
...typeof permission.callID === "string" ? { callID: permission.callID } : {},
|
|
4352
|
+
...typeof permission.title === "string" ? { title: permission.title } : {},
|
|
4353
|
+
...time ? { time } : {}
|
|
4354
|
+
};
|
|
4280
4355
|
}
|
|
4281
|
-
function
|
|
4282
|
-
if (!
|
|
4283
|
-
|
|
4284
|
-
if (roleOf2(last) !== "assistant") return false;
|
|
4285
|
-
return completedOf(last) == null;
|
|
4356
|
+
function adaptV2PermissionList(value) {
|
|
4357
|
+
if (!isRecord5(value) || !Array.isArray(value.data)) return null;
|
|
4358
|
+
return value.data.map(adaptV2Permission).filter((permission) => permission !== null);
|
|
4286
4359
|
}
|
|
4287
|
-
|
|
4288
|
-
|
|
4360
|
+
function adaptV2Session(value) {
|
|
4361
|
+
if (!isRecord5(value) || typeof value.id !== "string" || value.id.length === 0) return null;
|
|
4362
|
+
const time = isRecord5(value.time) ? {
|
|
4363
|
+
...finiteNumber(value.time.created) !== void 0 ? { created: finiteNumber(value.time.created) } : {},
|
|
4364
|
+
...finiteNumber(value.time.updated) !== void 0 ? { updated: finiteNumber(value.time.updated) } : {}
|
|
4365
|
+
} : void 0;
|
|
4366
|
+
return {
|
|
4367
|
+
id: value.id,
|
|
4368
|
+
...typeof value.title === "string" ? { title: value.title } : {},
|
|
4369
|
+
...typeof value.parentID === "string" ? { parentID: value.parentID } : {},
|
|
4370
|
+
...time && Object.keys(time).length > 0 ? { time } : {}
|
|
4371
|
+
};
|
|
4372
|
+
}
|
|
4373
|
+
function adaptV2SessionList(value) {
|
|
4374
|
+
if (!isRecord5(value) || !Array.isArray(value.data) || !isRecord5(value.cursor)) return null;
|
|
4375
|
+
return {
|
|
4376
|
+
data: value.data.map(adaptV2Session).filter((session) => session !== null),
|
|
4377
|
+
cursor: value.cursor
|
|
4378
|
+
};
|
|
4379
|
+
}
|
|
4380
|
+
function adaptV2Location(value) {
|
|
4289
4381
|
const candidates = [
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
session.time_created,
|
|
4294
|
-
session.updated,
|
|
4295
|
-
session.created
|
|
4382
|
+
value,
|
|
4383
|
+
isRecord5(value) ? value.data : void 0,
|
|
4384
|
+
isRecord5(value) ? value.location : void 0
|
|
4296
4385
|
];
|
|
4297
|
-
for (const
|
|
4298
|
-
if (typeof
|
|
4386
|
+
for (const candidate of candidates) {
|
|
4387
|
+
if (!isRecord5(candidate) || typeof candidate.directory !== "string") continue;
|
|
4388
|
+
const directory = candidate.directory.trim();
|
|
4389
|
+
if (directory) return directory;
|
|
4299
4390
|
}
|
|
4300
4391
|
return null;
|
|
4301
4392
|
}
|
|
4302
|
-
function
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
const query = params.toString();
|
|
4306
|
-
return query ? `/session?${query}` : "/session";
|
|
4393
|
+
function adaptV2Messages(value) {
|
|
4394
|
+
if (!isRecord5(value) || !Array.isArray(value.data)) return [];
|
|
4395
|
+
return value.data.slice().reverse().map(adaptV2Message).filter((message) => message !== null);
|
|
4307
4396
|
}
|
|
4308
|
-
async function
|
|
4309
|
-
const path = sessionListPath(options);
|
|
4397
|
+
async function readJson(response) {
|
|
4310
4398
|
try {
|
|
4311
|
-
|
|
4312
|
-
port,
|
|
4313
|
-
client,
|
|
4314
|
-
path,
|
|
4315
|
-
options?.signal ? { signal: options.signal } : void 0,
|
|
4316
|
-
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
4317
|
-
);
|
|
4318
|
-
if (!res.ok) {
|
|
4319
|
-
console.error(`[listSessionPage] GET ${path} returned HTTP ${res.status} (port ${port})`);
|
|
4320
|
-
return null;
|
|
4321
|
-
}
|
|
4322
|
-
const body = await res.json();
|
|
4323
|
-
return Array.isArray(body) ? body : null;
|
|
4399
|
+
return await response.json();
|
|
4324
4400
|
} catch (error2) {
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
return null;
|
|
4401
|
+
throw new Error(
|
|
4402
|
+
`OpenCode V2 response was not valid JSON: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4403
|
+
);
|
|
4329
4404
|
}
|
|
4330
4405
|
}
|
|
4331
|
-
async function
|
|
4332
|
-
|
|
4333
|
-
|
|
4406
|
+
async function readData(client, path, init) {
|
|
4407
|
+
const response = await client.request(path, init);
|
|
4408
|
+
const body = await readJson(response);
|
|
4409
|
+
if (!isRecord5(body) || !("data" in body)) {
|
|
4410
|
+
throw new Error(`OpenCode V2 response for ${path} was missing its data envelope`);
|
|
4411
|
+
}
|
|
4412
|
+
return body.data;
|
|
4334
4413
|
}
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4414
|
+
var OpenCodeV2PromptAckError = class extends Error {
|
|
4415
|
+
constructor(message) {
|
|
4416
|
+
super(message);
|
|
4417
|
+
this.name = "OpenCodeV2PromptAckError";
|
|
4339
4418
|
}
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4419
|
+
};
|
|
4420
|
+
var OpenCodeV2ModelSwitchError = class extends Error {
|
|
4421
|
+
statusCode;
|
|
4422
|
+
constructor(error2) {
|
|
4423
|
+
super(error2 instanceof Error ? error2.message : String(error2));
|
|
4424
|
+
this.name = "OpenCodeV2ModelSwitchError";
|
|
4425
|
+
this.statusCode = error2 instanceof OpenCodeRequestError ? error2.statusCode : null;
|
|
4426
|
+
}
|
|
4427
|
+
};
|
|
4428
|
+
async function getOpenCodeDirectoryV2(client) {
|
|
4429
|
+
try {
|
|
4430
|
+
return adaptV2Location(await readJson(await client.request("/api/location")));
|
|
4431
|
+
} catch (error2) {
|
|
4432
|
+
console.error(
|
|
4433
|
+
`[getOpenCodeDirectoryV2] GET /api/location failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4434
|
+
);
|
|
4435
|
+
return null;
|
|
4347
4436
|
}
|
|
4348
|
-
return { sessions };
|
|
4349
4437
|
}
|
|
4350
|
-
|
|
4351
|
-
"
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
"
|
|
4357
|
-
|
|
4358
|
-
"UND_ERR_CONNECT_TIMEOUT",
|
|
4359
|
-
"UND_ERR_HEADERS_TIMEOUT",
|
|
4360
|
-
"UND_ERR_SOCKET"
|
|
4361
|
-
]);
|
|
4362
|
-
function interruptFailureDiagnostic(error2) {
|
|
4363
|
-
const message = error2 instanceof Error ? error2.message : "";
|
|
4364
|
-
const httpStatus = /^OpenCode request failed: HTTP ([1-5]\d{2})(?::|$)/.exec(message)?.[1];
|
|
4365
|
-
if (httpStatus) return `HTTP ${httpStatus}`;
|
|
4366
|
-
const candidates = [error2, error2 instanceof Error ? error2.cause : void 0];
|
|
4367
|
-
for (const candidate of candidates) {
|
|
4368
|
-
if (typeof candidate !== "object" || candidate === null || !("code" in candidate)) continue;
|
|
4369
|
-
const code = candidate.code;
|
|
4370
|
-
if (typeof code === "string" && INTERRUPT_NETWORK_CODES.has(code)) {
|
|
4371
|
-
return redactDiagnosticText(`network ${code}`).slice(0, 120);
|
|
4372
|
-
}
|
|
4438
|
+
async function createV2Session(client, directory) {
|
|
4439
|
+
const data = await readData(client, "/api/session", {
|
|
4440
|
+
method: "POST",
|
|
4441
|
+
headers: { "Content-Type": "application/json" },
|
|
4442
|
+
body: JSON.stringify({ location: { directory } })
|
|
4443
|
+
});
|
|
4444
|
+
if (!isRecord5(data) || typeof data.id !== "string" || data.id.length === 0) {
|
|
4445
|
+
throw new Error("OpenCode V2 create session response was missing data.id");
|
|
4373
4446
|
}
|
|
4374
|
-
|
|
4375
|
-
return redactDiagnosticText(`request threw ${name}`).slice(0, 120);
|
|
4447
|
+
return data.id;
|
|
4376
4448
|
}
|
|
4377
|
-
async function
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4449
|
+
async function getV2Session(client, sessionId) {
|
|
4450
|
+
const data = await readData(client, `/api/session/${encodeURIComponent(sessionId)}`);
|
|
4451
|
+
const session = adaptV2Session(data);
|
|
4452
|
+
if (!session) throw new Error("OpenCode V2 get session response contained an invalid session");
|
|
4453
|
+
return session;
|
|
4454
|
+
}
|
|
4455
|
+
async function listV2SessionPage(client, cursor, signal) {
|
|
4456
|
+
const operation = cursor ? "GET /api/session (next page)" : "GET /api/session";
|
|
4457
|
+
const path = cursor ? `/api/session?cursor=${encodeURIComponent(cursor)}` : "/api/session";
|
|
4458
|
+
try {
|
|
4459
|
+
const response = await client.request(path, signal ? { signal } : void 0, {
|
|
4460
|
+
allowStatuses: ALL_HTTP_STATUSES
|
|
4461
|
+
});
|
|
4462
|
+
if (!response.ok) {
|
|
4463
|
+
console.error(
|
|
4464
|
+
`[listV2SessionPage] ${operation} returned HTTP ${response.status} (port ${client.port})`
|
|
4465
|
+
);
|
|
4466
|
+
return null;
|
|
4384
4467
|
}
|
|
4468
|
+
return adaptV2SessionList(await readJson(response));
|
|
4469
|
+
} catch (error2) {
|
|
4470
|
+
if (signal?.aborted) return null;
|
|
4471
|
+
const errorName = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
4472
|
+
console.error(`[listV2SessionPage] ${operation} failed (port ${client.port}): ${errorName}`);
|
|
4473
|
+
return null;
|
|
4385
4474
|
}
|
|
4475
|
+
}
|
|
4476
|
+
async function listV2Sessions(client, signal) {
|
|
4477
|
+
const sessions = [];
|
|
4478
|
+
const seenCursors = /* @__PURE__ */ new Set();
|
|
4479
|
+
let cursor;
|
|
4480
|
+
let hasNextPage = true;
|
|
4386
4481
|
try {
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4482
|
+
while (hasNextPage) {
|
|
4483
|
+
const page = await listV2SessionPage(client, cursor, signal);
|
|
4484
|
+
if (!page) return null;
|
|
4485
|
+
sessions.push(...page.data);
|
|
4486
|
+
const next = page.cursor.next;
|
|
4487
|
+
if (next === void 0 || next === null) {
|
|
4488
|
+
hasNextPage = false;
|
|
4489
|
+
continue;
|
|
4490
|
+
}
|
|
4491
|
+
if (typeof next !== "string" || next.length === 0 || seenCursors.has(next)) {
|
|
4492
|
+
throw new Error("OpenCode V2 session list contained an invalid next cursor");
|
|
4493
|
+
}
|
|
4494
|
+
seenCursors.add(next);
|
|
4495
|
+
cursor = next;
|
|
4396
4496
|
}
|
|
4397
|
-
return
|
|
4497
|
+
return sessions;
|
|
4398
4498
|
} catch (error2) {
|
|
4399
|
-
|
|
4499
|
+
const errorName = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
4500
|
+
console.error(
|
|
4501
|
+
`[listV2Sessions] GET /api/session pagination failed (port ${client.port}): ${errorName}`
|
|
4502
|
+
);
|
|
4503
|
+
return null;
|
|
4400
4504
|
}
|
|
4401
4505
|
}
|
|
4402
|
-
async function
|
|
4403
|
-
if (client?.version === "v2") return deleteV2Session(client, id);
|
|
4506
|
+
async function deleteV2Session(client, sessionId) {
|
|
4404
4507
|
try {
|
|
4405
|
-
const
|
|
4406
|
-
|
|
4407
|
-
client,
|
|
4408
|
-
`/session/${id}`,
|
|
4508
|
+
const response = await client.request(
|
|
4509
|
+
`/api/session/${encodeURIComponent(sessionId)}`,
|
|
4409
4510
|
{ method: "DELETE" },
|
|
4410
4511
|
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
4411
4512
|
);
|
|
4412
|
-
if (
|
|
4413
|
-
return { ok: true, status:
|
|
4513
|
+
if (response.status >= 200 && response.status < 300) {
|
|
4514
|
+
return { ok: true, status: response.status };
|
|
4414
4515
|
}
|
|
4415
4516
|
try {
|
|
4416
|
-
const body = await
|
|
4417
|
-
return body ? { ok: false, status:
|
|
4517
|
+
const body = await response.text();
|
|
4518
|
+
return body ? { ok: false, status: response.status, body } : { ok: false, status: response.status };
|
|
4418
4519
|
} catch (error2) {
|
|
4419
4520
|
console.error(
|
|
4420
|
-
`[
|
|
4521
|
+
`[deleteV2Session] DELETE /api/session/${sessionId} response body read failed for HTTP ${response.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4421
4522
|
);
|
|
4422
|
-
return { ok: false, status:
|
|
4523
|
+
return { ok: false, status: response.status };
|
|
4423
4524
|
}
|
|
4424
4525
|
} catch (error2) {
|
|
4425
4526
|
console.error(
|
|
4426
|
-
`[
|
|
4527
|
+
`[deleteV2Session] DELETE /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4427
4528
|
);
|
|
4428
4529
|
return { ok: false, status: "threw" };
|
|
4429
4530
|
}
|
|
4430
4531
|
}
|
|
4431
|
-
async function
|
|
4532
|
+
async function v2SessionExists(client, sessionId) {
|
|
4432
4533
|
try {
|
|
4433
|
-
const
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
return
|
|
4439
|
-
} catch {
|
|
4440
|
-
return null;
|
|
4441
|
-
}
|
|
4442
|
-
}
|
|
4443
|
-
async function getOpenCodeSession(port, id, client) {
|
|
4444
|
-
try {
|
|
4445
|
-
const response = await requestWithClient(port, client, `/session/${id}`);
|
|
4446
|
-
const body = await response.json();
|
|
4447
|
-
return body && typeof body === "object" && !Array.isArray(body) ? body : null;
|
|
4534
|
+
const response = await client.request(
|
|
4535
|
+
`/api/session/${encodeURIComponent(sessionId)}`,
|
|
4536
|
+
void 0,
|
|
4537
|
+
{ allowStatuses: [404] }
|
|
4538
|
+
);
|
|
4539
|
+
return response.status === 404 ? false : true;
|
|
4448
4540
|
} catch (error2) {
|
|
4449
4541
|
console.error(
|
|
4450
|
-
`[
|
|
4542
|
+
`[v2SessionExists] GET /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4451
4543
|
);
|
|
4452
4544
|
return null;
|
|
4453
4545
|
}
|
|
4454
4546
|
}
|
|
4455
|
-
async function
|
|
4456
|
-
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
4461
|
-
|
|
4462
|
-
|
|
4463
|
-
|
|
4464
|
-
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
)
|
|
4470
|
-
|
|
4547
|
+
async function sendV2Prompt(client, sessionId, text, options, onInvalidModelSelection) {
|
|
4548
|
+
const modelSelection = options?.model?.trim();
|
|
4549
|
+
const { model, variant } = splitModelVariant(modelSelection);
|
|
4550
|
+
const separator = model?.indexOf("/") ?? -1;
|
|
4551
|
+
const modelReference = model && separator > 0 && separator < model.length - 1 ? {
|
|
4552
|
+
id: model.slice(separator + 1),
|
|
4553
|
+
providerID: model.slice(0, separator),
|
|
4554
|
+
...variant ? { variant } : {}
|
|
4555
|
+
} : void 0;
|
|
4556
|
+
if (modelSelection && !modelReference) onInvalidModelSelection?.();
|
|
4557
|
+
if (options?.agent) {
|
|
4558
|
+
await client.request(`/api/session/${encodeURIComponent(sessionId)}/agent`, {
|
|
4559
|
+
method: "POST",
|
|
4560
|
+
headers: { "Content-Type": "application/json" },
|
|
4561
|
+
body: JSON.stringify({ agent: options.agent })
|
|
4562
|
+
});
|
|
4563
|
+
}
|
|
4564
|
+
if (modelReference) {
|
|
4565
|
+
try {
|
|
4566
|
+
await client.request(`/api/session/${encodeURIComponent(sessionId)}/model`, {
|
|
4567
|
+
method: "POST",
|
|
4568
|
+
headers: { "Content-Type": "application/json" },
|
|
4569
|
+
body: JSON.stringify({ model: modelReference })
|
|
4570
|
+
});
|
|
4571
|
+
} catch (error2) {
|
|
4572
|
+
throw new OpenCodeV2ModelSwitchError(error2);
|
|
4471
4573
|
}
|
|
4472
|
-
|
|
4473
|
-
|
|
4474
|
-
|
|
4475
|
-
|
|
4574
|
+
}
|
|
4575
|
+
const path = `/api/session/${encodeURIComponent(sessionId)}/prompt`;
|
|
4576
|
+
const response = await client.request(path, {
|
|
4577
|
+
method: "POST",
|
|
4578
|
+
headers: { "Content-Type": "application/json" },
|
|
4579
|
+
body: JSON.stringify({ text, delivery: "queue" })
|
|
4580
|
+
});
|
|
4581
|
+
let body;
|
|
4582
|
+
try {
|
|
4583
|
+
body = await readJson(response);
|
|
4584
|
+
} catch (error2) {
|
|
4585
|
+
throw new OpenCodeV2PromptAckError(
|
|
4586
|
+
`OpenCode V2 prompt response could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4476
4587
|
);
|
|
4477
|
-
return null;
|
|
4478
4588
|
}
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
const map = await getSessionStatuses(port, client);
|
|
4483
|
-
if (map == null) return null;
|
|
4484
|
-
const entry = map[id];
|
|
4485
|
-
return entry != null && entry.type !== "idle";
|
|
4486
|
-
}
|
|
4487
|
-
async function createOpenCodeSession(port, directory, client) {
|
|
4488
|
-
const path = new URL(`${opencodeBase(port)}/session`);
|
|
4489
|
-
if (directory && directory.trim()) path.searchParams.set("directory", directory.trim());
|
|
4490
|
-
const requestPath = `${path.pathname}${path.search}`;
|
|
4491
|
-
const response = await requestWithClient(
|
|
4492
|
-
port,
|
|
4493
|
-
client,
|
|
4494
|
-
requestPath,
|
|
4495
|
-
{
|
|
4496
|
-
method: "POST",
|
|
4497
|
-
headers: { "Content-Type": "application/json" },
|
|
4498
|
-
body: JSON.stringify({})
|
|
4499
|
-
},
|
|
4500
|
-
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
4501
|
-
);
|
|
4502
|
-
if (!response.ok) {
|
|
4503
|
-
const text = await response.text().catch(() => "");
|
|
4504
|
-
throw new Error(`Failed to create session: HTTP ${response.status}${text ? `: ${text}` : ""}`);
|
|
4589
|
+
const data = isRecord5(body) && "data" in body ? body.data : void 0;
|
|
4590
|
+
if (!isRecord5(data) || typeof data.id !== "string" || data.id.length === 0) {
|
|
4591
|
+
throw new OpenCodeV2PromptAckError("OpenCode V2 prompt response was missing data.id");
|
|
4505
4592
|
}
|
|
4506
|
-
const data = await response.json();
|
|
4507
4593
|
return data.id;
|
|
4508
4594
|
}
|
|
4509
|
-
async function
|
|
4510
|
-
const
|
|
4511
|
-
|
|
4595
|
+
async function getV2SessionMessages(client, sessionId) {
|
|
4596
|
+
const path = `/api/session/${encodeURIComponent(sessionId)}/message?order=desc&limit=200`;
|
|
4597
|
+
try {
|
|
4598
|
+
const body = await readJson(await client.request(path));
|
|
4599
|
+
if (!isRecord5(body) || !Array.isArray(body.data) || !isRecord5(body.cursor)) return null;
|
|
4600
|
+
return adaptV2Messages(body);
|
|
4601
|
+
} catch (error2) {
|
|
4512
4602
|
console.error(
|
|
4513
|
-
`[
|
|
4603
|
+
`[getV2SessionMessages] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4514
4604
|
);
|
|
4515
4605
|
return null;
|
|
4516
4606
|
}
|
|
4607
|
+
}
|
|
4608
|
+
async function listV2Forms(client, sessionId) {
|
|
4609
|
+
const path = `/api/session/${encodeURIComponent(sessionId)}/form`;
|
|
4517
4610
|
try {
|
|
4518
|
-
|
|
4519
|
-
|
|
4520
|
-
console.error(
|
|
4521
|
-
`[getModelAttachmentCapability] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
4522
|
-
);
|
|
4523
|
-
return null;
|
|
4524
|
-
}
|
|
4525
|
-
const body = await res.json();
|
|
4526
|
-
const providers = Array.isArray(body?.providers) ? body.providers : null;
|
|
4527
|
-
if (!providers) {
|
|
4528
|
-
console.error(
|
|
4529
|
-
`[getModelAttachmentCapability] GET /config/providers body had no providers array (port ${port})`
|
|
4530
|
-
);
|
|
4531
|
-
return null;
|
|
4532
|
-
}
|
|
4533
|
-
const slash = baseModel ? baseModel.indexOf("/") : -1;
|
|
4534
|
-
const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
|
|
4535
|
-
let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
|
|
4536
|
-
const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
|
|
4537
|
-
let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
|
|
4538
|
-
if (!provider && !providerId) {
|
|
4539
|
-
const defaultProviderIds = defaults2 ? Object.keys(defaults2) : [];
|
|
4540
|
-
if (defaultProviderIds.length === 1) {
|
|
4541
|
-
provider = providers.find((p) => p?.id === defaultProviderIds[0]);
|
|
4542
|
-
}
|
|
4543
|
-
}
|
|
4544
|
-
if (!provider || !provider.models) return null;
|
|
4545
|
-
if (!modelId && defaults2 && typeof provider.id === "string") {
|
|
4546
|
-
const def = defaults2[provider.id];
|
|
4547
|
-
if (typeof def === "string") modelId = def;
|
|
4548
|
-
}
|
|
4549
|
-
if (!modelId) {
|
|
4550
|
-
if (providerId) {
|
|
4551
|
-
const keys = Object.keys(provider.models);
|
|
4552
|
-
if (keys.length === 1) modelId = keys[0];
|
|
4553
|
-
}
|
|
4554
|
-
if (!modelId) return null;
|
|
4555
|
-
}
|
|
4556
|
-
const entry = provider.models[modelId];
|
|
4557
|
-
if (!entry || typeof entry !== "object") return null;
|
|
4558
|
-
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
4559
|
-
if (typeof entry.capabilities.attachment === "boolean") {
|
|
4560
|
-
return entry.capabilities.attachment;
|
|
4561
|
-
}
|
|
4562
|
-
}
|
|
4563
|
-
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
4564
|
-
} catch (err) {
|
|
4611
|
+
return adaptV2FormList(await readJson(await client.request(path)));
|
|
4612
|
+
} catch (error2) {
|
|
4565
4613
|
console.error(
|
|
4566
|
-
`[
|
|
4614
|
+
`[listV2Forms] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4567
4615
|
);
|
|
4568
4616
|
return null;
|
|
4569
4617
|
}
|
|
4570
4618
|
}
|
|
4571
|
-
async function
|
|
4572
|
-
|
|
4573
|
-
const { model: baseModel } = splitModelVariant(model);
|
|
4574
|
-
if (!baseModel) return null;
|
|
4575
|
-
const slash = baseModel.indexOf("/");
|
|
4576
|
-
if (slash <= 0) return null;
|
|
4577
|
-
const providerId = baseModel.slice(0, slash);
|
|
4619
|
+
async function listV2Permissions(client, sessionId) {
|
|
4620
|
+
const path = `/api/session/${encodeURIComponent(sessionId)}/permission`;
|
|
4578
4621
|
try {
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
console.error(
|
|
4582
|
-
`[isPinnedProviderLoaded] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
4583
|
-
);
|
|
4584
|
-
return null;
|
|
4585
|
-
}
|
|
4586
|
-
const body = await res.json();
|
|
4587
|
-
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
4588
|
-
console.error(
|
|
4589
|
-
`[isPinnedProviderLoaded] GET /config/providers body was not a plain object (port ${port})`
|
|
4590
|
-
);
|
|
4591
|
-
return null;
|
|
4592
|
-
}
|
|
4593
|
-
const providers = body.providers;
|
|
4594
|
-
if (!Array.isArray(providers)) {
|
|
4595
|
-
console.error(
|
|
4596
|
-
`[isPinnedProviderLoaded] GET /config/providers body had no providers array (port ${port})`
|
|
4597
|
-
);
|
|
4598
|
-
return null;
|
|
4599
|
-
}
|
|
4600
|
-
const providerIds = providers.filter(
|
|
4601
|
-
(provider) => provider !== null && typeof provider === "object" && typeof provider.id === "string"
|
|
4602
|
-
).map((provider) => provider.id);
|
|
4603
|
-
if (providerIds.length === 0) {
|
|
4604
|
-
console.error(
|
|
4605
|
-
`[isPinnedProviderLoaded] GET /config/providers had no provider entries with string ids (port ${port})`
|
|
4606
|
-
);
|
|
4607
|
-
return null;
|
|
4608
|
-
}
|
|
4609
|
-
return providerIds.includes(providerId);
|
|
4610
|
-
} catch (err) {
|
|
4622
|
+
return adaptV2PermissionList(await readJson(await client.request(path)));
|
|
4623
|
+
} catch (error2) {
|
|
4611
4624
|
console.error(
|
|
4612
|
-
`[
|
|
4625
|
+
`[listV2Permissions] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4613
4626
|
);
|
|
4614
4627
|
return null;
|
|
4615
4628
|
}
|
|
4616
4629
|
}
|
|
4617
|
-
async function
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4630
|
+
async function interruptV2Session(client, sessionId) {
|
|
4631
|
+
await client.request(`/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
|
|
4632
|
+
method: "POST"
|
|
4633
|
+
});
|
|
4634
|
+
}
|
|
4635
|
+
async function getV2ActiveSessions(client) {
|
|
4636
|
+
try {
|
|
4637
|
+
const body = await readJson(await client.request("/api/session/active"));
|
|
4638
|
+
if (!isRecord5(body) || !isRecord5(body.data)) return null;
|
|
4639
|
+
return body.data;
|
|
4640
|
+
} catch (error2) {
|
|
4641
|
+
console.error(
|
|
4642
|
+
`[getV2ActiveSessions] GET /api/session/active failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4643
|
+
);
|
|
4644
|
+
return null;
|
|
4626
4645
|
}
|
|
4627
|
-
|
|
4628
|
-
|
|
4646
|
+
}
|
|
4647
|
+
async function isV2SessionOngoing(client, sessionId) {
|
|
4648
|
+
const activeSessions = await getV2ActiveSessions(client);
|
|
4649
|
+
if (activeSessions === null) return null;
|
|
4650
|
+
return Object.prototype.hasOwnProperty.call(activeSessions, sessionId);
|
|
4651
|
+
}
|
|
4652
|
+
function sessionErrorReason(value) {
|
|
4653
|
+
if (typeof value === "string" && value.trim()) return value.trim().slice(0, 500);
|
|
4654
|
+
if (isRecord5(value)) {
|
|
4655
|
+
const data = isRecord5(value.data) ? value.data : void 0;
|
|
4656
|
+
const reason = typeof data?.message === "string" && data.message || typeof value.message === "string" && value.message || typeof value.name === "string" && value.name;
|
|
4657
|
+
if (reason) return reason.replace(/\s+/g, " ").trim().slice(0, 500);
|
|
4658
|
+
}
|
|
4659
|
+
return "OpenCode reported a session error with no details";
|
|
4660
|
+
}
|
|
4661
|
+
function adaptV2SessionErrorEvent(value) {
|
|
4662
|
+
let parsed = value;
|
|
4663
|
+
if (typeof value === "string") {
|
|
4629
4664
|
try {
|
|
4630
|
-
|
|
4631
|
-
} catch (
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
);
|
|
4635
|
-
dataUrl = null;
|
|
4665
|
+
parsed = JSON.parse(value);
|
|
4666
|
+
} catch (error2) {
|
|
4667
|
+
void error2;
|
|
4668
|
+
return null;
|
|
4636
4669
|
}
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
|
|
4670
|
+
}
|
|
4671
|
+
if (!isRecord5(parsed)) return null;
|
|
4672
|
+
try {
|
|
4673
|
+
const establishedShape = parseSessionErrorFrame(JSON.stringify(parsed));
|
|
4674
|
+
if (establishedShape) return establishedShape;
|
|
4675
|
+
} catch (error2) {
|
|
4676
|
+
void error2;
|
|
4677
|
+
}
|
|
4678
|
+
const candidates = [parsed, parsed.payload, parsed.data].filter(isRecord5);
|
|
4679
|
+
for (const event of candidates) {
|
|
4680
|
+
if (event.type !== "session.error") continue;
|
|
4681
|
+
const properties = [event.properties, event.data, event].find(isRecord5);
|
|
4682
|
+
if (!properties) continue;
|
|
4683
|
+
const sessionId = typeof properties.sessionID === "string" && properties.sessionID || typeof properties.sessionId === "string" && properties.sessionId;
|
|
4684
|
+
if (!sessionId) continue;
|
|
4685
|
+
return {
|
|
4686
|
+
sessionId,
|
|
4687
|
+
reason: sessionErrorReason(properties.error ?? properties)
|
|
4688
|
+
};
|
|
4689
|
+
}
|
|
4690
|
+
return null;
|
|
4691
|
+
}
|
|
4692
|
+
async function readV2SessionErrorStream(client, options) {
|
|
4693
|
+
let reader = null;
|
|
4694
|
+
try {
|
|
4695
|
+
const response = await client.request("/api/event", {
|
|
4696
|
+
headers: { accept: "text/event-stream" },
|
|
4697
|
+
signal: options.signal
|
|
4698
|
+
});
|
|
4699
|
+
if (!response.ok || !response.body) {
|
|
4700
|
+
return { reason: "unavailable", detail: `HTTP ${response.status}` };
|
|
4646
4701
|
}
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4702
|
+
reader = response.body.getReader();
|
|
4703
|
+
const decoder = new TextDecoder();
|
|
4704
|
+
let buffer = "";
|
|
4705
|
+
const processLine = (line) => {
|
|
4706
|
+
const trimmed = line.trimEnd();
|
|
4707
|
+
if (!trimmed.startsWith("data:")) return;
|
|
4708
|
+
const event = adaptV2SessionErrorEvent(trimmed.slice("data:".length).replace(/^ /, ""));
|
|
4709
|
+
if (event) options.onSessionError(event);
|
|
4710
|
+
};
|
|
4711
|
+
while (true) {
|
|
4712
|
+
const { done, value } = await reader.read();
|
|
4713
|
+
if (done) return { reason: "ended" };
|
|
4714
|
+
buffer += decoder.decode(value, { stream: true });
|
|
4715
|
+
const lines = buffer.split("\n");
|
|
4716
|
+
buffer = lines.pop() ?? "";
|
|
4717
|
+
for (const line of lines) processLine(line);
|
|
4650
4718
|
}
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
}
|
|
4657
|
-
|
|
4719
|
+
} catch (error2) {
|
|
4720
|
+
if (options.signal.aborted) return { reason: "aborted" };
|
|
4721
|
+
return {
|
|
4722
|
+
reason: "unavailable",
|
|
4723
|
+
detail: error2 instanceof Error ? error2.message : String(error2)
|
|
4724
|
+
};
|
|
4725
|
+
} finally {
|
|
4726
|
+
if (reader) void reader.cancel().catch(() => void 0);
|
|
4658
4727
|
}
|
|
4659
|
-
return { parts, outcomes, capabilityUnknown };
|
|
4660
4728
|
}
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
const model = value.slice(0, hashIndex).trim() || void 0;
|
|
4667
|
-
const variant = value.slice(hashIndex + 1).trim() || void 0;
|
|
4668
|
-
return { model, variant };
|
|
4729
|
+
|
|
4730
|
+
// src/lib/opencode/session.ts
|
|
4731
|
+
var ALL_HTTP_STATUSES2 = Array.from({ length: 500 }, (_, index) => index + 100);
|
|
4732
|
+
function timedFetch(input, init) {
|
|
4733
|
+
return withRequestTimeout(fetch, REQUEST_TIMEOUT_MS)(input, init);
|
|
4669
4734
|
}
|
|
4670
|
-
function
|
|
4671
|
-
|
|
4672
|
-
const { model, variant } = splitModelVariant(options?.model);
|
|
4673
|
-
if (model) {
|
|
4674
|
-
const slashIndex = model.indexOf("/");
|
|
4675
|
-
if (slashIndex !== -1) {
|
|
4676
|
-
body.model = {
|
|
4677
|
-
providerID: model.substring(0, slashIndex),
|
|
4678
|
-
modelID: model.substring(slashIndex + 1)
|
|
4679
|
-
};
|
|
4680
|
-
}
|
|
4681
|
-
}
|
|
4682
|
-
if (variant) body.variant = variant;
|
|
4735
|
+
function requestWithClient(port, client, path, init, options) {
|
|
4736
|
+
return client ? client.request(path, init, options) : timedFetch(`${opencodeBase(port)}${path}`, init);
|
|
4683
4737
|
}
|
|
4684
|
-
|
|
4738
|
+
function opencodeBase(port) {
|
|
4739
|
+
return `http://127.0.0.1:${port}`;
|
|
4740
|
+
}
|
|
4741
|
+
async function getOpenCodeDirectory(port, client) {
|
|
4685
4742
|
try {
|
|
4686
|
-
const
|
|
4687
|
-
|
|
4688
|
-
|
|
4743
|
+
const res = await requestWithClient(port, client, "/path");
|
|
4744
|
+
if (!res.ok) return null;
|
|
4745
|
+
const body = await res.json();
|
|
4746
|
+
const dir = typeof body.directory === "string" && body.directory || typeof body.worktree === "string" && body.worktree || typeof body.path?.cwd === "string" && body.path.cwd || typeof body.path?.directory === "string" && body.path.directory || null;
|
|
4747
|
+
return dir && dir.trim() ? dir.trim() : null;
|
|
4689
4748
|
} catch (error2) {
|
|
4690
4749
|
console.error(
|
|
4691
|
-
`[
|
|
4750
|
+
`[getOpenCodeDirectory] GET /path failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4692
4751
|
);
|
|
4693
4752
|
return null;
|
|
4694
4753
|
}
|
|
4695
4754
|
}
|
|
4696
|
-
async function
|
|
4755
|
+
async function resolveOpenCodeDirectoryForVersion(apiVersion, port, client) {
|
|
4756
|
+
if (apiVersion === "v2") return client ? getOpenCodeDirectoryV2(client) : null;
|
|
4757
|
+
return getOpenCodeDirectory(port, client ?? void 0);
|
|
4758
|
+
}
|
|
4759
|
+
function roleOf2(m) {
|
|
4760
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4761
|
+
if (typeof m.role === "string") return m.role;
|
|
4762
|
+
const infoRole = m.info?.role;
|
|
4763
|
+
return typeof infoRole === "string" ? infoRole : void 0;
|
|
4764
|
+
}
|
|
4765
|
+
function completedOf(m) {
|
|
4766
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4767
|
+
return m.info?.time?.completed ?? m.time?.completed;
|
|
4768
|
+
}
|
|
4769
|
+
function createdOf(m) {
|
|
4770
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4771
|
+
return m.info?.time?.created ?? m.time?.created;
|
|
4772
|
+
}
|
|
4773
|
+
function idOf2(m) {
|
|
4774
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4775
|
+
if (typeof m.id === "string") return m.id;
|
|
4776
|
+
const infoId = m.info?.id;
|
|
4777
|
+
return typeof infoId === "string" ? infoId : void 0;
|
|
4778
|
+
}
|
|
4779
|
+
function parentIdOf2(m) {
|
|
4780
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4781
|
+
if (typeof m.parentID === "string") return m.parentID;
|
|
4782
|
+
const infoParent = m.info?.parentID;
|
|
4783
|
+
return typeof infoParent === "string" ? infoParent : void 0;
|
|
4784
|
+
}
|
|
4785
|
+
function finishOf(m) {
|
|
4786
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4787
|
+
if (typeof m.finish === "string") return m.finish;
|
|
4788
|
+
const infoFinish = m.info?.finish;
|
|
4789
|
+
return typeof infoFinish === "string" ? infoFinish : void 0;
|
|
4790
|
+
}
|
|
4791
|
+
function errorOf(m) {
|
|
4792
|
+
if (!m || typeof m !== "object") return void 0;
|
|
4793
|
+
return m.info?.error ?? m.error;
|
|
4794
|
+
}
|
|
4795
|
+
function isTerminalStopAnswer(m) {
|
|
4796
|
+
return completedOf(m) != null && errorOf(m) == null && finishOf(m) === "stop";
|
|
4797
|
+
}
|
|
4798
|
+
function isAssistantInFlight(m) {
|
|
4799
|
+
if (completedOf(m) == null) return true;
|
|
4800
|
+
if (errorOf(m) != null) return false;
|
|
4801
|
+
return finishOf(m) === "tool-calls";
|
|
4802
|
+
}
|
|
4803
|
+
async function getSessionMessages(port, sessionId, client) {
|
|
4697
4804
|
try {
|
|
4698
|
-
const
|
|
4699
|
-
const
|
|
4805
|
+
const path = `/session/${sessionId}/message`;
|
|
4806
|
+
const res = await requestWithClient(port, client, path);
|
|
4807
|
+
if (!res.ok) return null;
|
|
4808
|
+
const body = await res.json();
|
|
4700
4809
|
return Array.isArray(body) ? body : null;
|
|
4701
4810
|
} catch (error2) {
|
|
4702
4811
|
console.error(
|
|
4703
|
-
`[
|
|
4812
|
+
`[getSessionMessages] GET /session/${sessionId}/message failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4704
4813
|
);
|
|
4705
4814
|
return null;
|
|
4706
4815
|
}
|
|
4707
4816
|
}
|
|
4708
|
-
function
|
|
4709
|
-
|
|
4710
|
-
|
|
4817
|
+
async function fetchSessionMessages(port, sessionId, client) {
|
|
4818
|
+
const response = await requestWithClient(port, client, `/session/${sessionId}/message`);
|
|
4819
|
+
if (!response.ok) return null;
|
|
4820
|
+
const body = await response.json();
|
|
4821
|
+
return Array.isArray(body) ? body : null;
|
|
4711
4822
|
}
|
|
4712
|
-
function
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
if (
|
|
4823
|
+
async function pollSessionMessagesForRedrive(port, sessionId, client) {
|
|
4824
|
+
try {
|
|
4825
|
+
const response = await requestWithClient(
|
|
4826
|
+
port,
|
|
4827
|
+
client,
|
|
4828
|
+
`/session/${sessionId}/message`,
|
|
4829
|
+
void 0,
|
|
4830
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
4831
|
+
);
|
|
4832
|
+
if (!response.ok) {
|
|
4833
|
+
return { ok: false, status: response.status, body: await response.text(), malformed: false };
|
|
4834
|
+
}
|
|
4835
|
+
const body = await response.json();
|
|
4836
|
+
if (!Array.isArray(body)) return { ok: false, status: null, body: "", malformed: true };
|
|
4837
|
+
return { ok: true, messages: body };
|
|
4838
|
+
} catch (error2) {
|
|
4839
|
+
console.error(
|
|
4840
|
+
`[pollSessionMessagesForRedrive] GET /session/${sessionId}/message failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4841
|
+
);
|
|
4842
|
+
return { ok: false, status: null, body: "", malformed: false };
|
|
4722
4843
|
}
|
|
4723
|
-
return best?.id ?? null;
|
|
4724
4844
|
}
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
const
|
|
4728
|
-
|
|
4729
|
-
);
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
|
|
4733
|
-
|
|
4734
|
-
|
|
4735
|
-
|
|
4845
|
+
function isSessionActivelyGenerating(messages) {
|
|
4846
|
+
if (!messages || messages.length === 0) return false;
|
|
4847
|
+
const last = messages[messages.length - 1];
|
|
4848
|
+
if (roleOf2(last) !== "assistant") return false;
|
|
4849
|
+
return completedOf(last) == null;
|
|
4850
|
+
}
|
|
4851
|
+
var FULL_SESSION_ENUMERATION_MAX_SESSIONS = 3200;
|
|
4852
|
+
function sessionLastActivityMs(session) {
|
|
4853
|
+
const candidates = [
|
|
4854
|
+
session.time?.updated,
|
|
4855
|
+
session.time?.created,
|
|
4856
|
+
session.time_updated,
|
|
4857
|
+
session.time_created,
|
|
4858
|
+
session.updated,
|
|
4859
|
+
session.created
|
|
4860
|
+
];
|
|
4861
|
+
for (const c of candidates) {
|
|
4862
|
+
if (typeof c === "number" && Number.isFinite(c)) return c;
|
|
4736
4863
|
}
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
|
|
4740
|
-
|
|
4741
|
-
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
4754
|
-
port,
|
|
4755
|
-
client,
|
|
4756
|
-
`/session/${sessionId}/prompt_async`,
|
|
4757
|
-
{
|
|
4758
|
-
method: "POST",
|
|
4759
|
-
headers: { "Content-Type": "application/json" },
|
|
4760
|
-
body: JSON.stringify(body)
|
|
4761
|
-
},
|
|
4762
|
-
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
4763
|
-
);
|
|
4764
|
-
if (res.status < 200 || res.status >= 300) {
|
|
4765
|
-
const text = await res.text().catch(() => "");
|
|
4766
|
-
const { variant } = splitModelVariant(options?.model);
|
|
4767
|
-
throw new Error(
|
|
4768
|
-
`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
|
|
4864
|
+
return null;
|
|
4865
|
+
}
|
|
4866
|
+
function sessionListPath(options) {
|
|
4867
|
+
const params = new URLSearchParams();
|
|
4868
|
+
if (options?.limit !== void 0) params.set("limit", String(options.limit));
|
|
4869
|
+
const query = params.toString();
|
|
4870
|
+
return query ? `/session?${query}` : "/session";
|
|
4871
|
+
}
|
|
4872
|
+
async function listSessionPage(port, client, options) {
|
|
4873
|
+
const path = sessionListPath(options);
|
|
4874
|
+
try {
|
|
4875
|
+
const res = await requestWithClient(
|
|
4876
|
+
port,
|
|
4877
|
+
client,
|
|
4878
|
+
path,
|
|
4879
|
+
options?.signal ? { signal: options.signal } : void 0,
|
|
4880
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
4769
4881
|
);
|
|
4770
|
-
|
|
4771
|
-
|
|
4772
|
-
|
|
4773
|
-
for (let attempt = 0; attempt < READ_BACK_ATTEMPTS; attempt++) {
|
|
4774
|
-
const after = await getSessionMessages(port, sessionId, client);
|
|
4775
|
-
const dispatchedUserMessageId = findDispatchedUserMessageId(after, content, knownUserIds);
|
|
4776
|
-
if (dispatchedUserMessageId !== null) {
|
|
4777
|
-
if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
|
|
4778
|
-
return dispatchedUserMessageId;
|
|
4779
|
-
}
|
|
4780
|
-
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
4781
|
-
await new Promise((resolve5) => setTimeout(resolve5, READ_BACK_DELAY_MS));
|
|
4882
|
+
if (!res.ok) {
|
|
4883
|
+
console.error(`[listSessionPage] GET ${path} returned HTTP ${res.status} (port ${port})`);
|
|
4884
|
+
return null;
|
|
4782
4885
|
}
|
|
4886
|
+
const body = await res.json();
|
|
4887
|
+
return Array.isArray(body) ? body : null;
|
|
4888
|
+
} catch (error2) {
|
|
4889
|
+
if (options?.signal?.aborted) return null;
|
|
4890
|
+
const errorName = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
4891
|
+
console.error(`[listSessionPage] GET ${path} failed (port ${port}): ${errorName}`);
|
|
4892
|
+
return null;
|
|
4783
4893
|
}
|
|
4784
|
-
return null;
|
|
4785
4894
|
}
|
|
4786
|
-
function
|
|
4787
|
-
if (
|
|
4788
|
-
|
|
4789
|
-
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId
|
|
4790
|
-
);
|
|
4791
|
-
if (byParent) return byParent;
|
|
4792
|
-
const userIndex = messages.findIndex((m) => idOf2(m) === userMessageId);
|
|
4793
|
-
if (userIndex === -1) return null;
|
|
4794
|
-
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
4795
|
-
if (roleOf2(messages[i]) === "assistant") return messages[i];
|
|
4796
|
-
}
|
|
4797
|
-
return null;
|
|
4895
|
+
async function listSessions(port, client, options) {
|
|
4896
|
+
if (client?.version === "v2") return listV2Sessions(client, options?.signal);
|
|
4897
|
+
return listSessionPage(port, client, options);
|
|
4798
4898
|
}
|
|
4799
|
-
function
|
|
4800
|
-
if (
|
|
4801
|
-
|
|
4802
|
-
|
|
4803
|
-
const m = messages[i];
|
|
4804
|
-
if (roleOf2(m) !== "assistant" || parentIdOf2(m) !== userMessageId) continue;
|
|
4805
|
-
lastCorrelated = m;
|
|
4806
|
-
break;
|
|
4899
|
+
async function listAllSessions(port, client, signal) {
|
|
4900
|
+
if (client?.version === "v2") {
|
|
4901
|
+
const sessions2 = await listV2Sessions(client, signal);
|
|
4902
|
+
return sessions2 === null ? { sessions: null, reason: "opencode-unreachable" } : { sessions: sessions2 };
|
|
4807
4903
|
}
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
|
|
4814
|
-
|
|
4815
|
-
}
|
|
4816
|
-
return lastCorrelated;
|
|
4904
|
+
const sessions = await listSessionPage(port, client, {
|
|
4905
|
+
limit: FULL_SESSION_ENUMERATION_MAX_SESSIONS,
|
|
4906
|
+
signal
|
|
4907
|
+
});
|
|
4908
|
+
if (sessions === null) return { sessions: null, reason: "opencode-unreachable" };
|
|
4909
|
+
if (sessions.length >= FULL_SESSION_ENUMERATION_MAX_SESSIONS) {
|
|
4910
|
+
return { sessions: null, reason: "session-enumeration-limit-bound" };
|
|
4817
4911
|
}
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4912
|
+
return { sessions };
|
|
4913
|
+
}
|
|
4914
|
+
var INTERRUPT_NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
4915
|
+
"ABORT_ERR",
|
|
4916
|
+
"EAI_AGAIN",
|
|
4917
|
+
"ECONNREFUSED",
|
|
4918
|
+
"ECONNRESET",
|
|
4919
|
+
"ENETUNREACH",
|
|
4920
|
+
"ENOTFOUND",
|
|
4921
|
+
"ETIMEDOUT",
|
|
4922
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
4923
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
4924
|
+
"UND_ERR_SOCKET"
|
|
4925
|
+
]);
|
|
4926
|
+
function interruptFailureDiagnostic(error2) {
|
|
4927
|
+
const message = error2 instanceof Error ? error2.message : "";
|
|
4928
|
+
const httpStatus = /^OpenCode request failed: HTTP ([1-5]\d{2})(?::|$)/.exec(message)?.[1];
|
|
4929
|
+
if (httpStatus) return `HTTP ${httpStatus}`;
|
|
4930
|
+
const candidates = [error2, error2 instanceof Error ? error2.cause : void 0];
|
|
4931
|
+
for (const candidate of candidates) {
|
|
4932
|
+
if (typeof candidate !== "object" || candidate === null || !("code" in candidate)) continue;
|
|
4933
|
+
const code = candidate.code;
|
|
4934
|
+
if (typeof code === "string" && INTERRUPT_NETWORK_CODES.has(code)) {
|
|
4935
|
+
return redactDiagnosticText(`network ${code}`).slice(0, 120);
|
|
4828
4936
|
}
|
|
4829
4937
|
}
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
const m = messages[i];
|
|
4833
|
-
if (roleOf2(m) === "user") break;
|
|
4834
|
-
if (roleOf2(m) === "assistant" && isTerminalStopAnswer(m)) return m;
|
|
4835
|
-
}
|
|
4836
|
-
return last;
|
|
4938
|
+
const name = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
4939
|
+
return redactDiagnosticText(`request threw ${name}`).slice(0, 120);
|
|
4837
4940
|
}
|
|
4838
|
-
function
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
|
|
4846
|
-
|
|
4941
|
+
async function interruptSession(port, id, client) {
|
|
4942
|
+
if (client?.version === "v2") {
|
|
4943
|
+
try {
|
|
4944
|
+
await interruptV2Session(client, id);
|
|
4945
|
+
return { kind: "confirmed_stopped" };
|
|
4946
|
+
} catch (error2) {
|
|
4947
|
+
return { kind: "not_confirmed", diagnostic: interruptFailureDiagnostic(error2) };
|
|
4948
|
+
}
|
|
4949
|
+
}
|
|
4950
|
+
try {
|
|
4951
|
+
const res = await requestWithClient(
|
|
4952
|
+
port,
|
|
4953
|
+
client,
|
|
4954
|
+
`/session/${id}/abort`,
|
|
4955
|
+
{ method: "POST" },
|
|
4956
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
4957
|
+
);
|
|
4958
|
+
if (res.status >= 200 && res.status < 300) {
|
|
4959
|
+
return { kind: "confirmed_stopped", status: res.status };
|
|
4960
|
+
}
|
|
4961
|
+
return { kind: "not_confirmed", status: res.status };
|
|
4962
|
+
} catch (error2) {
|
|
4963
|
+
return { kind: "threw", diagnostic: interruptFailureDiagnostic(error2) };
|
|
4847
4964
|
}
|
|
4848
|
-
return assistants;
|
|
4849
4965
|
}
|
|
4850
|
-
function
|
|
4851
|
-
if (
|
|
4852
|
-
|
|
4853
|
-
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
if (!state || typeof state !== "object") continue;
|
|
4872
|
-
const metadata = state.metadata;
|
|
4873
|
-
if (!metadata || typeof metadata !== "object") continue;
|
|
4874
|
-
const sessionId = metadata.sessionId;
|
|
4875
|
-
if (typeof sessionId !== "string" || sessionId.length === 0 || seen.has(sessionId)) continue;
|
|
4876
|
-
seen.add(sessionId);
|
|
4877
|
-
const start = state.time?.start;
|
|
4878
|
-
refs.push({
|
|
4879
|
-
sessionId,
|
|
4880
|
-
startedAtMs: typeof start === "number" && Number.isFinite(start) ? start : null
|
|
4881
|
-
});
|
|
4966
|
+
async function deleteSession(port, id, client) {
|
|
4967
|
+
if (client?.version === "v2") return deleteV2Session(client, id);
|
|
4968
|
+
try {
|
|
4969
|
+
const res = await requestWithClient(
|
|
4970
|
+
port,
|
|
4971
|
+
client,
|
|
4972
|
+
`/session/${id}`,
|
|
4973
|
+
{ method: "DELETE" },
|
|
4974
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
4975
|
+
);
|
|
4976
|
+
if (res.status >= 200 && res.status < 300) {
|
|
4977
|
+
return { ok: true, status: res.status };
|
|
4978
|
+
}
|
|
4979
|
+
try {
|
|
4980
|
+
const body = await res.text();
|
|
4981
|
+
return body ? { ok: false, status: res.status, body } : { ok: false, status: res.status };
|
|
4982
|
+
} catch (error2) {
|
|
4983
|
+
console.error(
|
|
4984
|
+
`[deleteSession] DELETE /session/${id} response body read failed for HTTP ${res.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4985
|
+
);
|
|
4986
|
+
return { ok: false, status: res.status };
|
|
4882
4987
|
}
|
|
4988
|
+
} catch (error2) {
|
|
4989
|
+
console.error(
|
|
4990
|
+
`[deleteSession] DELETE /session/${id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4991
|
+
);
|
|
4992
|
+
return { ok: false, status: "threw" };
|
|
4883
4993
|
}
|
|
4884
|
-
return refs;
|
|
4885
4994
|
}
|
|
4886
|
-
function
|
|
4887
|
-
|
|
4995
|
+
async function sessionExists(port, id, client) {
|
|
4996
|
+
try {
|
|
4997
|
+
const res = await requestWithClient(port, client, `/session/${id}`, void 0, {
|
|
4998
|
+
allowStatuses: [404]
|
|
4999
|
+
});
|
|
5000
|
+
if (res.status >= 200 && res.status < 300) return true;
|
|
5001
|
+
if (res.status === 404) return false;
|
|
5002
|
+
return null;
|
|
5003
|
+
} catch {
|
|
5004
|
+
return null;
|
|
5005
|
+
}
|
|
4888
5006
|
}
|
|
4889
|
-
function
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
4893
|
-
|
|
4894
|
-
|
|
4895
|
-
|
|
4896
|
-
|
|
4897
|
-
if (!messages || messages.length === 0) return [];
|
|
4898
|
-
const calls = [];
|
|
4899
|
-
for (const message of messages) {
|
|
4900
|
-
if (roleOf2(message) !== "assistant" || parentIdOf2(message) !== userMessageId) continue;
|
|
4901
|
-
for (const part of message.parts ?? []) {
|
|
4902
|
-
if (part.tool !== "task" || !part.callID || !part.state || part.state.status === "pending") {
|
|
4903
|
-
continue;
|
|
4904
|
-
}
|
|
4905
|
-
const rawName = part.state.input?.subagent_type;
|
|
4906
|
-
const subagentName = typeof rawName === "string" && rawName.trim().length > 0 ? rawName : rawName === void 0 ? "general" : "unknown";
|
|
4907
|
-
const metadata = part.state.metadata;
|
|
4908
|
-
calls.push({
|
|
4909
|
-
callID: part.callID,
|
|
4910
|
-
subagentName,
|
|
4911
|
-
childSessionId: typeof metadata?.sessionId === "string" ? metadata.sessionId : null,
|
|
4912
|
-
parentSessionId: typeof metadata?.parentSessionId === "string" ? metadata.parentSessionId : null,
|
|
4913
|
-
model: taskCallModel(metadata?.model),
|
|
4914
|
-
status: part.state.status ?? "unknown",
|
|
4915
|
-
timeStart: finiteNumber(part.state.time?.start),
|
|
4916
|
-
timeEnd: finiteNumber(part.state.time?.end)
|
|
4917
|
-
});
|
|
4918
|
-
}
|
|
4919
|
-
}
|
|
4920
|
-
return calls;
|
|
4921
|
-
}
|
|
4922
|
-
function attributeTaskCallUsage(messages, windows) {
|
|
4923
|
-
const eligibleWindows = windows.filter(
|
|
4924
|
-
(window) => window.timeStart !== null && Number.isFinite(window.timeStart)
|
|
4925
|
-
);
|
|
4926
|
-
const assignments = /* @__PURE__ */ new Map();
|
|
4927
|
-
for (const window of eligibleWindows) assignments.set(window.callID, []);
|
|
4928
|
-
const unattributed = [];
|
|
4929
|
-
for (const message of messages ?? []) {
|
|
4930
|
-
if (roleOf2(message) !== "assistant") continue;
|
|
4931
|
-
const created = finiteNumber(createdOf(message));
|
|
4932
|
-
const matching = created === null ? [] : eligibleWindows.filter(
|
|
4933
|
-
(window) => window.timeStart <= created && (window.timeEnd === null || window.timeEnd === void 0 || created <= window.timeEnd)
|
|
5007
|
+
async function getOpenCodeSession(port, id, client) {
|
|
5008
|
+
try {
|
|
5009
|
+
const response = await requestWithClient(port, client, `/session/${id}`);
|
|
5010
|
+
const body = await response.json();
|
|
5011
|
+
return body && typeof body === "object" && !Array.isArray(body) ? body : null;
|
|
5012
|
+
} catch (error2) {
|
|
5013
|
+
console.error(
|
|
5014
|
+
`[getOpenCodeSession] GET /session/${id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
4934
5015
|
);
|
|
4935
|
-
if (matching.length === 0) {
|
|
4936
|
-
unattributed.push(message);
|
|
4937
|
-
continue;
|
|
4938
|
-
}
|
|
4939
|
-
matching.sort((a, b) => a.timeStart - b.timeStart);
|
|
4940
|
-
assignments.get(matching[0].callID)?.push(message);
|
|
4941
|
-
}
|
|
4942
|
-
return {
|
|
4943
|
-
invocations: eligibleWindows.map((window) => {
|
|
4944
|
-
const assigned = assignments.get(window.callID) ?? [];
|
|
4945
|
-
return { callID: window.callID, messages: assigned, usage: sumAssistantUsage(assigned) };
|
|
4946
|
-
}),
|
|
4947
|
-
unattributed
|
|
4948
|
-
};
|
|
4949
|
-
}
|
|
4950
|
-
function sumAssistantUsage(messages) {
|
|
4951
|
-
if (!messages || messages.length === 0) return null;
|
|
4952
|
-
const hasTrailingError = errorOf(messages[messages.length - 1]) != null;
|
|
4953
|
-
const hasTerminalStopAnswer = messages.some(isTerminalStopAnswer);
|
|
4954
|
-
const selected = hasTrailingError && hasTerminalStopAnswer ? messages.filter((message) => errorOf(message) == null) : messages;
|
|
4955
|
-
let sawAnyUsage = false;
|
|
4956
|
-
let inputSum = 0;
|
|
4957
|
-
let outputSum = 0;
|
|
4958
|
-
let reasoningSum = 0;
|
|
4959
|
-
let cacheReadSum = 0;
|
|
4960
|
-
let cacheWriteSum = 0;
|
|
4961
|
-
let costSum = 0;
|
|
4962
|
-
let sawCost = false;
|
|
4963
|
-
let toolCallCount = 0;
|
|
4964
|
-
let modelId = null;
|
|
4965
|
-
let providerId = null;
|
|
4966
|
-
for (const m of selected) {
|
|
4967
|
-
toolCallCount += m.parts?.filter((part) => part.type === "tool").length ?? 0;
|
|
4968
|
-
const info = m.info;
|
|
4969
|
-
if (!info) continue;
|
|
4970
|
-
const tokens = info.tokens;
|
|
4971
|
-
if (tokens) {
|
|
4972
|
-
sawAnyUsage = true;
|
|
4973
|
-
inputSum += tokens.input ?? 0;
|
|
4974
|
-
outputSum += tokens.output ?? 0;
|
|
4975
|
-
reasoningSum += tokens.reasoning ?? 0;
|
|
4976
|
-
cacheReadSum += tokens.cache?.read ?? 0;
|
|
4977
|
-
cacheWriteSum += tokens.cache?.write ?? 0;
|
|
4978
|
-
}
|
|
4979
|
-
if (typeof info.cost === "number") {
|
|
4980
|
-
sawAnyUsage = true;
|
|
4981
|
-
sawCost = true;
|
|
4982
|
-
costSum += info.cost;
|
|
4983
|
-
}
|
|
4984
|
-
if (typeof info.modelID === "string") {
|
|
4985
|
-
sawAnyUsage = true;
|
|
4986
|
-
modelId = info.modelID;
|
|
4987
|
-
}
|
|
4988
|
-
if (typeof info.providerID === "string") {
|
|
4989
|
-
sawAnyUsage = true;
|
|
4990
|
-
providerId = info.providerID;
|
|
4991
|
-
}
|
|
4992
|
-
}
|
|
4993
|
-
if (!sawAnyUsage) return null;
|
|
4994
|
-
return {
|
|
4995
|
-
usage_provider_id: providerId,
|
|
4996
|
-
usage_model_id: modelId,
|
|
4997
|
-
usage_tokens_input: inputSum,
|
|
4998
|
-
usage_tokens_output: outputSum,
|
|
4999
|
-
usage_tokens_reasoning: reasoningSum,
|
|
5000
|
-
usage_tokens_cache_read: cacheReadSum,
|
|
5001
|
-
usage_tokens_cache_write: cacheWriteSum,
|
|
5002
|
-
// NULL means OpenCode never reported a cost; it is distinct from a genuine
|
|
5003
|
-
// zero-cost message, which sets `sawCost` with `costSum === 0`.
|
|
5004
|
-
usage_cost_usd: sawCost ? costSum : null,
|
|
5005
|
-
turn_tool_calls: toolCallCount
|
|
5006
|
-
};
|
|
5007
|
-
}
|
|
5008
|
-
function messageUsage(messages, userMessageId) {
|
|
5009
|
-
if (!messages || messages.length === 0) return null;
|
|
5010
|
-
const byParentAll = messages.filter(
|
|
5011
|
-
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId
|
|
5012
|
-
);
|
|
5013
|
-
let correlated;
|
|
5014
|
-
if (byParentAll.length > 0) {
|
|
5015
|
-
correlated = byParentAll;
|
|
5016
|
-
} else {
|
|
5017
|
-
correlated = assistantMessagesInTurnBlock(messages, userMessageId);
|
|
5018
|
-
}
|
|
5019
|
-
if (correlated.length === 0) return null;
|
|
5020
|
-
return sumAssistantUsage(correlated);
|
|
5021
|
-
}
|
|
5022
|
-
function messageRunState(messages, userMessageId) {
|
|
5023
|
-
if (!messages || messages.length === 0) return "unknown";
|
|
5024
|
-
const hasUser = messages.some((m) => idOf2(m) === userMessageId);
|
|
5025
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5026
|
-
if (!hasUser) {
|
|
5027
|
-
if (!reply) return "unknown";
|
|
5028
|
-
}
|
|
5029
|
-
if (!reply) return "queued";
|
|
5030
|
-
if (isAssistantInFlight(reply)) return "running";
|
|
5031
|
-
if (errorOf(reply) != null) return "failed";
|
|
5032
|
-
if (isAmbiguousTerminalFinish(reply)) return "running";
|
|
5033
|
-
return "done";
|
|
5034
|
-
}
|
|
5035
|
-
function isPreamblePinnedRunning(messages, userMessageId) {
|
|
5036
|
-
if (messageRunState(messages, userMessageId) !== "running") return false;
|
|
5037
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5038
|
-
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
5039
|
-
}
|
|
5040
|
-
function isMidFlightPinnedRunning(messages, userMessageId) {
|
|
5041
|
-
if (messageRunState(messages, userMessageId) !== "running") return false;
|
|
5042
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5043
|
-
return reply !== null && isAssistantInFlight(reply) && completedOf(reply) == null;
|
|
5044
|
-
}
|
|
5045
|
-
function isB2AbandonmentConfirmed(params) {
|
|
5046
|
-
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
|
|
5047
|
-
}
|
|
5048
|
-
function isMidFlightOrphanConfirmed(params) {
|
|
5049
|
-
return params.pinnedForMs >= params.minPinnedMs && params.notOngoingStreak >= params.minNotOngoingStreak;
|
|
5050
|
-
}
|
|
5051
|
-
function isAmbiguousTerminalFinish(m) {
|
|
5052
|
-
if (completedOf(m) == null) return false;
|
|
5053
|
-
if (errorOf(m) != null) return false;
|
|
5054
|
-
const finish = finishOf(m);
|
|
5055
|
-
return finish !== "tool-calls" && finish !== "stop";
|
|
5056
|
-
}
|
|
5057
|
-
function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
|
|
5058
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5059
|
-
return isAmbiguousTerminalFinish(reply);
|
|
5060
|
-
}
|
|
5061
|
-
function isAmbiguousFinishResolved(params) {
|
|
5062
|
-
return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
|
|
5063
|
-
}
|
|
5064
|
-
function messageError(messages, userMessageId) {
|
|
5065
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5066
|
-
const error2 = errorOf(reply);
|
|
5067
|
-
if (error2 == null) return null;
|
|
5068
|
-
let rendered;
|
|
5069
|
-
if (typeof error2 === "string") {
|
|
5070
|
-
rendered = error2;
|
|
5071
|
-
} else if (typeof error2 === "object") {
|
|
5072
|
-
const e = error2;
|
|
5073
|
-
const dataMessage = e.data?.message;
|
|
5074
|
-
if (typeof dataMessage === "string") {
|
|
5075
|
-
rendered = dataMessage;
|
|
5076
|
-
} else if (typeof e.message === "string") {
|
|
5077
|
-
rendered = e.message;
|
|
5078
|
-
} else {
|
|
5079
|
-
rendered = "The agent run failed.";
|
|
5080
|
-
}
|
|
5081
|
-
} else {
|
|
5082
|
-
rendered = "The agent run failed.";
|
|
5083
|
-
}
|
|
5084
|
-
const toolPart = Array.isArray(reply?.parts) ? reply.parts.find(
|
|
5085
|
-
(part) => part && typeof part === "object" && part.type === "tool" && part.state?.status === "error"
|
|
5086
|
-
) : void 0;
|
|
5087
|
-
return typeof toolPart?.tool === "string" && toolPart.tool.length > 0 ? `${rendered} (tool "${toolPart.tool}")` : rendered;
|
|
5088
|
-
}
|
|
5089
|
-
function describeAbandonedReplyShape(messages, userMessageId) {
|
|
5090
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5091
|
-
if (!reply) return null;
|
|
5092
|
-
const parts = Array.isArray(reply.parts) ? reply.parts : [];
|
|
5093
|
-
const lastTool = [...parts].reverse().find((part) => part?.type === "tool");
|
|
5094
|
-
return {
|
|
5095
|
-
partTypes: parts.slice(-12).map((part) => typeof part?.type === "string" ? part.type : "(unknown)"),
|
|
5096
|
-
droppedPartCount: Math.max(0, parts.length - 12),
|
|
5097
|
-
lastToolName: typeof lastTool?.tool === "string" && lastTool.tool.length > 0 ? lastTool.tool : null,
|
|
5098
|
-
lastToolStatus: typeof lastTool?.state?.status === "string" && lastTool.state.status.length > 0 ? lastTool.state.status : null
|
|
5099
|
-
};
|
|
5100
|
-
}
|
|
5101
|
-
function isAbortedTerminalReply(messages, userMessageId) {
|
|
5102
|
-
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5103
|
-
const error2 = errorOf(reply);
|
|
5104
|
-
if (error2 == null) return false;
|
|
5105
|
-
if (typeof error2 === "string") return error2.trim() === "Aborted";
|
|
5106
|
-
if (typeof error2 === "object") {
|
|
5107
|
-
const e = error2;
|
|
5108
|
-
if (e.name === "MessageAbortedError") return true;
|
|
5109
|
-
if (e.name === "AbortError") return true;
|
|
5110
|
-
const dataMessage = e.data?.message;
|
|
5111
|
-
const rendered = typeof dataMessage === "string" ? dataMessage : typeof e.message === "string" ? e.message : null;
|
|
5112
|
-
return rendered != null && rendered.trim() === "Aborted";
|
|
5113
|
-
}
|
|
5114
|
-
return false;
|
|
5115
|
-
}
|
|
5116
|
-
var CLAUDE_AUTH_EXPIRY_MESSAGES = Object.freeze([
|
|
5117
|
-
"Claude Code credentials are unavailable or expired. Run `claude` to refresh them."
|
|
5118
|
-
]);
|
|
5119
|
-
function extractReplyErrorShape(reply) {
|
|
5120
|
-
const error2 = errorOf(reply);
|
|
5121
|
-
if (error2 == null || typeof error2 !== "object") {
|
|
5122
|
-
return { name: null, statusCode: null };
|
|
5123
|
-
}
|
|
5124
|
-
const e = error2;
|
|
5125
|
-
const name = typeof e.name === "string" ? e.name.slice(0, 100) : null;
|
|
5126
|
-
const data = e.data;
|
|
5127
|
-
const statusCode = typeof data?.statusCode === "number" && Number.isFinite(data.statusCode) ? data.statusCode : null;
|
|
5128
|
-
return { name, statusCode };
|
|
5129
|
-
}
|
|
5130
|
-
function classifyReplyAuthError(reply) {
|
|
5131
|
-
const error2 = errorOf(reply);
|
|
5132
|
-
if (error2 == null || typeof error2 !== "object") return null;
|
|
5133
|
-
const e = error2;
|
|
5134
|
-
const replyProviderId = reply?.info?.providerID ?? null;
|
|
5135
|
-
const replyModelId = reply?.info?.modelID ?? null;
|
|
5136
|
-
const data = e.data;
|
|
5137
|
-
if (e.name === "ProviderAuthError") {
|
|
5138
|
-
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
5139
|
-
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
5140
|
-
}
|
|
5141
|
-
if (e.name === "APIError") {
|
|
5142
|
-
const statusCode = data?.statusCode;
|
|
5143
|
-
if (statusCode === 401 || statusCode === 403) {
|
|
5144
|
-
return {
|
|
5145
|
-
kind: "model_auth",
|
|
5146
|
-
providerId: replyProviderId,
|
|
5147
|
-
modelId: replyModelId,
|
|
5148
|
-
reason: "rejected"
|
|
5149
|
-
};
|
|
5150
|
-
}
|
|
5151
|
-
}
|
|
5152
|
-
const errorMessage4 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
|
|
5153
|
-
if (errorMessage4 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage4.includes(knownMessage))) {
|
|
5154
|
-
return {
|
|
5155
|
-
kind: "model_auth",
|
|
5156
|
-
providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
|
|
5157
|
-
modelId: replyModelId,
|
|
5158
|
-
reason: "rejected"
|
|
5159
|
-
};
|
|
5160
|
-
}
|
|
5161
|
-
return null;
|
|
5162
|
-
}
|
|
5163
|
-
function messageFailure(messages, userMessageId) {
|
|
5164
|
-
return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
|
|
5165
|
-
}
|
|
5166
|
-
function isProviderModelNotFoundError(reason) {
|
|
5167
|
-
return reason.includes("Model not found:");
|
|
5168
|
-
}
|
|
5169
|
-
function findLatestSubagentAuthOutcome(messages, sinceMs) {
|
|
5170
|
-
if (!messages || messages.length === 0) return null;
|
|
5171
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
5172
|
-
const message = messages[i];
|
|
5173
|
-
if (roleOf2(message) !== "assistant") continue;
|
|
5174
|
-
const created = createdOf(message);
|
|
5175
|
-
if (sinceMs !== null && typeof created === "number" && created < sinceMs) continue;
|
|
5176
|
-
const failure = classifyReplyAuthError(message);
|
|
5177
|
-
if (failure) {
|
|
5178
|
-
if (!failure.providerId) return null;
|
|
5179
|
-
return { providerId: failure.providerId, outcome: "failed", failure };
|
|
5180
|
-
}
|
|
5181
|
-
const providerId = message.info?.providerID;
|
|
5182
|
-
if (errorOf(message) == null && typeof providerId === "string" && providerId.length > 0) {
|
|
5183
|
-
return { providerId, outcome: "succeeded" };
|
|
5184
|
-
}
|
|
5185
5016
|
return null;
|
|
5186
5017
|
}
|
|
5187
|
-
return null;
|
|
5188
|
-
}
|
|
5189
|
-
function findSubagentAuthOutcome(messages, sinceMs) {
|
|
5190
|
-
return findLatestSubagentAuthOutcome(messages, sinceMs);
|
|
5191
5018
|
}
|
|
5192
|
-
function
|
|
5193
|
-
if (
|
|
5194
|
-
|
|
5195
|
-
|
|
5196
|
-
|
|
5197
|
-
|
|
5198
|
-
|
|
5199
|
-
|
|
5200
|
-
|
|
5201
|
-
}
|
|
5202
|
-
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
5203
|
-
if (!messages || messages.length === 0) return false;
|
|
5204
|
-
return messages.some(
|
|
5205
|
-
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
5206
|
-
);
|
|
5207
|
-
}
|
|
5208
|
-
function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
|
|
5209
|
-
if (!messages || messages.length === 0) return false;
|
|
5210
|
-
const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
|
|
5211
|
-
if (userIndex === -1) return false;
|
|
5212
|
-
let hasLaterUser = false;
|
|
5213
|
-
let hasStartedLaterUser = false;
|
|
5214
|
-
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
5215
|
-
const message = messages[i];
|
|
5216
|
-
if (roleOf2(message) !== "user") continue;
|
|
5217
|
-
hasLaterUser = true;
|
|
5218
|
-
const laterUserMessageId = idOf2(message);
|
|
5219
|
-
if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
|
|
5220
|
-
return false;
|
|
5221
|
-
}
|
|
5222
|
-
if (messages.some(
|
|
5223
|
-
(candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
|
|
5224
|
-
)) {
|
|
5225
|
-
hasStartedLaterUser = true;
|
|
5019
|
+
async function getSessionStatuses(port, client) {
|
|
5020
|
+
if (client?.version === "v2") return null;
|
|
5021
|
+
try {
|
|
5022
|
+
const res = await requestWithClient(port, client, "/session/status");
|
|
5023
|
+
if (!res.ok) {
|
|
5024
|
+
console.error(
|
|
5025
|
+
`[getSessionStatuses] GET /session/status returned HTTP ${res.status} (port ${port})`
|
|
5026
|
+
);
|
|
5027
|
+
return null;
|
|
5226
5028
|
}
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
}
|
|
5230
|
-
async function hasAnyConfiguredProvider(port, client) {
|
|
5231
|
-
if (client?.version === "v2") {
|
|
5232
|
-
const directory = await getOpenCodeDirectoryV2(client);
|
|
5233
|
-
if (!directory) {
|
|
5029
|
+
const body = await res.json();
|
|
5030
|
+
if (body == null || typeof body !== "object" || Array.isArray(body)) {
|
|
5234
5031
|
console.error(
|
|
5235
|
-
`[
|
|
5032
|
+
`[getSessionStatuses] GET /session/status body was not a plain object (port ${port})`
|
|
5236
5033
|
);
|
|
5237
5034
|
return null;
|
|
5238
5035
|
}
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
|
|
5257
|
-
|
|
5258
|
-
|
|
5259
|
-
|
|
5260
|
-
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
|
|
5270
|
-
|
|
5271
|
-
|
|
5272
|
-
|
|
5036
|
+
return body;
|
|
5037
|
+
} catch (err) {
|
|
5038
|
+
console.error(
|
|
5039
|
+
`[getSessionStatuses] GET /session/status failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
5040
|
+
);
|
|
5041
|
+
return null;
|
|
5042
|
+
}
|
|
5043
|
+
}
|
|
5044
|
+
async function isSessionOngoing(port, id, client) {
|
|
5045
|
+
if (client?.version === "v2") return isV2SessionOngoing(client, id);
|
|
5046
|
+
const map = await getSessionStatuses(port, client);
|
|
5047
|
+
if (map == null) return null;
|
|
5048
|
+
const entry = map[id];
|
|
5049
|
+
return entry != null && entry.type !== "idle";
|
|
5050
|
+
}
|
|
5051
|
+
async function createOpenCodeSession(port, directory, client) {
|
|
5052
|
+
const path = new URL(`${opencodeBase(port)}/session`);
|
|
5053
|
+
if (directory && directory.trim()) path.searchParams.set("directory", directory.trim());
|
|
5054
|
+
const requestPath = `${path.pathname}${path.search}`;
|
|
5055
|
+
const response = await requestWithClient(
|
|
5056
|
+
port,
|
|
5057
|
+
client,
|
|
5058
|
+
requestPath,
|
|
5059
|
+
{
|
|
5060
|
+
method: "POST",
|
|
5061
|
+
headers: { "Content-Type": "application/json" },
|
|
5062
|
+
body: JSON.stringify({})
|
|
5063
|
+
},
|
|
5064
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
5065
|
+
);
|
|
5066
|
+
if (!response.ok) {
|
|
5067
|
+
const text = await response.text().catch(() => "");
|
|
5068
|
+
throw new Error(`Failed to create session: HTTP ${response.status}${text ? `: ${text}` : ""}`);
|
|
5069
|
+
}
|
|
5070
|
+
const data = await response.json();
|
|
5071
|
+
return data.id;
|
|
5072
|
+
}
|
|
5073
|
+
async function getModelAttachmentCapability(port, model, client) {
|
|
5074
|
+
const { model: baseModel } = splitModelVariant(model);
|
|
5075
|
+
if (client?.version === "v2") {
|
|
5076
|
+
console.error(
|
|
5077
|
+
`[getModelAttachmentCapability] V2 provider capabilities are unavailable; using text-only fallback (port ${port})`
|
|
5078
|
+
);
|
|
5079
|
+
return null;
|
|
5080
|
+
}
|
|
5081
|
+
try {
|
|
5082
|
+
const res = await requestWithClient(port, client, "/config/providers");
|
|
5083
|
+
if (!res.ok) {
|
|
5273
5084
|
console.error(
|
|
5274
|
-
`[
|
|
5085
|
+
`[getModelAttachmentCapability] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
5275
5086
|
);
|
|
5087
|
+
return null;
|
|
5276
5088
|
}
|
|
5277
|
-
|
|
5278
|
-
const
|
|
5279
|
-
|
|
5280
|
-
try {
|
|
5281
|
-
const res = await client.request(providerPath);
|
|
5282
|
-
if (!res.ok) {
|
|
5283
|
-
console.error(
|
|
5284
|
-
`[hasAnyConfiguredProvider] GET ${providerPath} returned HTTP ${res.status} (port ${port})`
|
|
5285
|
-
);
|
|
5286
|
-
} else {
|
|
5287
|
-
const body = await res.json();
|
|
5288
|
-
if (!body || typeof body !== "object" || Array.isArray(body) || !Array.isArray(body.data)) {
|
|
5289
|
-
console.error(
|
|
5290
|
-
`[hasAnyConfiguredProvider] GET ${providerPath} body had no provider data array (port ${port})`
|
|
5291
|
-
);
|
|
5292
|
-
} else {
|
|
5293
|
-
let valid = true;
|
|
5294
|
-
for (const provider of body.data) {
|
|
5295
|
-
if (!provider || typeof provider !== "object" || Array.isArray(provider) || typeof provider.id !== "string") {
|
|
5296
|
-
console.error(
|
|
5297
|
-
`[hasAnyConfiguredProvider] GET ${providerPath} body contained an invalid provider (port ${port})`
|
|
5298
|
-
);
|
|
5299
|
-
valid = false;
|
|
5300
|
-
break;
|
|
5301
|
-
}
|
|
5302
|
-
}
|
|
5303
|
-
if (valid) {
|
|
5304
|
-
providerReady = body.data.some(
|
|
5305
|
-
(provider) => provider.activation === "enabled"
|
|
5306
|
-
);
|
|
5307
|
-
}
|
|
5308
|
-
}
|
|
5309
|
-
}
|
|
5310
|
-
} catch (error2) {
|
|
5089
|
+
const body = await res.json();
|
|
5090
|
+
const providers = Array.isArray(body?.providers) ? body.providers : null;
|
|
5091
|
+
if (!providers) {
|
|
5311
5092
|
console.error(
|
|
5312
|
-
`[
|
|
5093
|
+
`[getModelAttachmentCapability] GET /config/providers body had no providers array (port ${port})`
|
|
5313
5094
|
);
|
|
5095
|
+
return null;
|
|
5314
5096
|
}
|
|
5315
|
-
|
|
5316
|
-
|
|
5317
|
-
|
|
5097
|
+
const slash = baseModel ? baseModel.indexOf("/") : -1;
|
|
5098
|
+
const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
|
|
5099
|
+
let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
|
|
5100
|
+
const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
|
|
5101
|
+
let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
|
|
5102
|
+
if (!provider && !providerId) {
|
|
5103
|
+
const defaultProviderIds = defaults2 ? Object.keys(defaults2) : [];
|
|
5104
|
+
if (defaultProviderIds.length === 1) {
|
|
5105
|
+
provider = providers.find((p) => p?.id === defaultProviderIds[0]);
|
|
5106
|
+
}
|
|
5107
|
+
}
|
|
5108
|
+
if (!provider || !provider.models) return null;
|
|
5109
|
+
if (!modelId && defaults2 && typeof provider.id === "string") {
|
|
5110
|
+
const def = defaults2[provider.id];
|
|
5111
|
+
if (typeof def === "string") modelId = def;
|
|
5112
|
+
}
|
|
5113
|
+
if (!modelId) {
|
|
5114
|
+
if (providerId) {
|
|
5115
|
+
const keys = Object.keys(provider.models);
|
|
5116
|
+
if (keys.length === 1) modelId = keys[0];
|
|
5117
|
+
}
|
|
5118
|
+
if (!modelId) return null;
|
|
5119
|
+
}
|
|
5120
|
+
const entry = provider.models[modelId];
|
|
5121
|
+
if (!entry || typeof entry !== "object") return null;
|
|
5122
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
5123
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
5124
|
+
return entry.capabilities.attachment;
|
|
5125
|
+
}
|
|
5126
|
+
}
|
|
5127
|
+
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
5128
|
+
} catch (err) {
|
|
5129
|
+
console.error(
|
|
5130
|
+
`[getModelAttachmentCapability] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
5131
|
+
);
|
|
5132
|
+
return null;
|
|
5318
5133
|
}
|
|
5134
|
+
}
|
|
5135
|
+
async function isPinnedProviderLoaded(port, model, client) {
|
|
5136
|
+
if (client?.version === "v2") return null;
|
|
5137
|
+
const { model: baseModel } = splitModelVariant(model);
|
|
5138
|
+
if (!baseModel) return null;
|
|
5139
|
+
const slash = baseModel.indexOf("/");
|
|
5140
|
+
if (slash <= 0) return null;
|
|
5141
|
+
const providerId = baseModel.slice(0, slash);
|
|
5319
5142
|
try {
|
|
5320
5143
|
const res = await requestWithClient(port, client, "/config/providers");
|
|
5321
5144
|
if (!res.ok) {
|
|
5322
5145
|
console.error(
|
|
5323
|
-
`[
|
|
5146
|
+
`[isPinnedProviderLoaded] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
5324
5147
|
);
|
|
5325
5148
|
return null;
|
|
5326
5149
|
}
|
|
5327
5150
|
const body = await res.json();
|
|
5328
|
-
if (
|
|
5151
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
5329
5152
|
console.error(
|
|
5330
|
-
`[
|
|
5153
|
+
`[isPinnedProviderLoaded] GET /config/providers body was not a plain object (port ${port})`
|
|
5331
5154
|
);
|
|
5332
5155
|
return null;
|
|
5333
5156
|
}
|
|
5334
|
-
const
|
|
5335
|
-
if (!
|
|
5157
|
+
const providers = body.providers;
|
|
5158
|
+
if (!Array.isArray(providers)) {
|
|
5336
5159
|
console.error(
|
|
5337
|
-
`[
|
|
5160
|
+
`[isPinnedProviderLoaded] GET /config/providers body had no providers array (port ${port})`
|
|
5338
5161
|
);
|
|
5339
5162
|
return null;
|
|
5340
5163
|
}
|
|
5341
|
-
|
|
5164
|
+
const providerIds = providers.filter(
|
|
5165
|
+
(provider) => provider !== null && typeof provider === "object" && typeof provider.id === "string"
|
|
5166
|
+
).map((provider) => provider.id);
|
|
5167
|
+
if (providerIds.length === 0) {
|
|
5168
|
+
console.error(
|
|
5169
|
+
`[isPinnedProviderLoaded] GET /config/providers had no provider entries with string ids (port ${port})`
|
|
5170
|
+
);
|
|
5171
|
+
return null;
|
|
5172
|
+
}
|
|
5173
|
+
return providerIds.includes(providerId);
|
|
5342
5174
|
} catch (err) {
|
|
5343
5175
|
console.error(
|
|
5344
|
-
`[
|
|
5176
|
+
`[isPinnedProviderLoaded] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
5345
5177
|
);
|
|
5346
5178
|
return null;
|
|
5347
5179
|
}
|
|
5348
5180
|
}
|
|
5349
|
-
function
|
|
5350
|
-
const
|
|
5351
|
-
const
|
|
5352
|
-
const
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
}
|
|
5357
|
-
|
|
5358
|
-
let parsed;
|
|
5359
|
-
try {
|
|
5360
|
-
parsed = JSON.parse(data);
|
|
5361
|
-
} catch (error2) {
|
|
5362
|
-
void error2;
|
|
5363
|
-
return null;
|
|
5364
|
-
}
|
|
5365
|
-
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
5366
|
-
const parsedRecord = parsed;
|
|
5367
|
-
const payload = parsedRecord.payload;
|
|
5368
|
-
const event = payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : parsedRecord;
|
|
5369
|
-
if (event.type !== "session.error") return null;
|
|
5370
|
-
const properties = event.properties;
|
|
5371
|
-
if (properties === null || typeof properties !== "object" || Array.isArray(properties)) {
|
|
5372
|
-
return null;
|
|
5181
|
+
async function buildFileParts(attachments, capable) {
|
|
5182
|
+
const outcomes = [];
|
|
5183
|
+
const parts = [];
|
|
5184
|
+
const capabilityUnknown = capable === null;
|
|
5185
|
+
if (capable !== true) {
|
|
5186
|
+
for (const a of attachments.inputs) {
|
|
5187
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "skipped" });
|
|
5188
|
+
}
|
|
5189
|
+
return { parts, outcomes, capabilityUnknown };
|
|
5373
5190
|
}
|
|
5374
|
-
const
|
|
5375
|
-
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
if (client?.version === "v2") return readV2SessionErrorStream(client, options);
|
|
5384
|
-
let reader = null;
|
|
5385
|
-
try {
|
|
5386
|
-
const response = await (client?.request("/event", {
|
|
5387
|
-
headers: { accept: "text/event-stream" },
|
|
5388
|
-
signal: options.signal
|
|
5389
|
-
}) ?? fetch(`${opencodeBase(port)}/event`, {
|
|
5390
|
-
headers: { accept: "text/event-stream" },
|
|
5391
|
-
signal: options.signal
|
|
5392
|
-
}));
|
|
5393
|
-
if (!response.ok || !response.body) {
|
|
5394
|
-
return { reason: "unavailable", detail: `HTTP ${response.status}` };
|
|
5191
|
+
for (const a of attachments.inputs) {
|
|
5192
|
+
let dataUrl = null;
|
|
5193
|
+
try {
|
|
5194
|
+
dataUrl = await attachments.fetchDataUrl(a.index);
|
|
5195
|
+
} catch (err) {
|
|
5196
|
+
console.error(
|
|
5197
|
+
`[buildFileParts] attachment ${a.index} (${a.mime}) fetch threw \u2014 omitting: ${err instanceof Error ? err.message : String(err)}`
|
|
5198
|
+
);
|
|
5199
|
+
dataUrl = null;
|
|
5395
5200
|
}
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5409
|
-
|
|
5410
|
-
|
|
5411
|
-
|
|
5201
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
5202
|
+
outcomes.push({
|
|
5203
|
+
index: a.index,
|
|
5204
|
+
mime: a.mime,
|
|
5205
|
+
filename: a.filename,
|
|
5206
|
+
status: "failed",
|
|
5207
|
+
reason: "needs_reauth"
|
|
5208
|
+
});
|
|
5209
|
+
continue;
|
|
5210
|
+
}
|
|
5211
|
+
if (dataUrl == null) {
|
|
5212
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
5213
|
+
continue;
|
|
5214
|
+
}
|
|
5215
|
+
parts.push({
|
|
5216
|
+
type: "file",
|
|
5217
|
+
mime: a.mime,
|
|
5218
|
+
url: dataUrl,
|
|
5219
|
+
...a.filename ? { filename: a.filename } : {}
|
|
5220
|
+
});
|
|
5221
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "sent" });
|
|
5222
|
+
}
|
|
5223
|
+
return { parts, outcomes, capabilityUnknown };
|
|
5224
|
+
}
|
|
5225
|
+
function splitModelVariant(raw) {
|
|
5226
|
+
const value = raw?.trim();
|
|
5227
|
+
if (!value) return {};
|
|
5228
|
+
const hashIndex = value.indexOf("#");
|
|
5229
|
+
if (hashIndex === -1) return { model: value };
|
|
5230
|
+
const model = value.slice(0, hashIndex).trim() || void 0;
|
|
5231
|
+
const variant = value.slice(hashIndex + 1).trim() || void 0;
|
|
5232
|
+
return { model, variant };
|
|
5233
|
+
}
|
|
5234
|
+
function applyModelOptions(body, options) {
|
|
5235
|
+
if (options?.agent) body.agent = options.agent;
|
|
5236
|
+
const { model, variant } = splitModelVariant(options?.model);
|
|
5237
|
+
if (model) {
|
|
5238
|
+
const slashIndex = model.indexOf("/");
|
|
5239
|
+
if (slashIndex !== -1) {
|
|
5240
|
+
body.model = {
|
|
5241
|
+
providerID: model.substring(0, slashIndex),
|
|
5242
|
+
modelID: model.substring(slashIndex + 1)
|
|
5243
|
+
};
|
|
5412
5244
|
}
|
|
5413
|
-
} catch (err) {
|
|
5414
|
-
if (options.signal.aborted) return { reason: "aborted" };
|
|
5415
|
-
return {
|
|
5416
|
-
reason: "unavailable",
|
|
5417
|
-
detail: err instanceof Error ? err.message : String(err)
|
|
5418
|
-
};
|
|
5419
|
-
} finally {
|
|
5420
|
-
if (reader) void reader.cancel().catch(() => void 0);
|
|
5421
5245
|
}
|
|
5246
|
+
if (variant) body.variant = variant;
|
|
5422
5247
|
}
|
|
5423
|
-
async function
|
|
5424
|
-
if (client?.version === "v2") return { outcome: "skipped_v2" };
|
|
5248
|
+
async function listOpenCodeQuestions(port, client) {
|
|
5425
5249
|
try {
|
|
5426
|
-
const
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
{
|
|
5431
|
-
method: "PATCH",
|
|
5432
|
-
headers: { "Content-Type": "application/json" },
|
|
5433
|
-
body: JSON.stringify({})
|
|
5434
|
-
},
|
|
5435
|
-
{ allowStatuses: ALL_HTTP_STATUSES }
|
|
5436
|
-
);
|
|
5437
|
-
if (!res.ok) {
|
|
5438
|
-
console.error(
|
|
5439
|
-
`[disposeAndReloadProviderConfig] PATCH /config returned HTTP ${res.status} (port ${port})`
|
|
5440
|
-
);
|
|
5441
|
-
return { outcome: "failed", status: res.status, detail: null };
|
|
5442
|
-
}
|
|
5443
|
-
return { outcome: "reloaded" };
|
|
5444
|
-
} catch (err) {
|
|
5250
|
+
const response = await requestWithClient(port, client, "/question");
|
|
5251
|
+
const body = await response.json();
|
|
5252
|
+
return Array.isArray(body) ? body : null;
|
|
5253
|
+
} catch (error2) {
|
|
5445
5254
|
console.error(
|
|
5446
|
-
`[
|
|
5255
|
+
`[listOpenCodeQuestions] GET /question failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5447
5256
|
);
|
|
5448
|
-
return
|
|
5449
|
-
outcome: "failed",
|
|
5450
|
-
status: null,
|
|
5451
|
-
detail: err instanceof Error ? err.message : String(err)
|
|
5452
|
-
};
|
|
5257
|
+
return null;
|
|
5453
5258
|
}
|
|
5454
5259
|
}
|
|
5455
|
-
async function
|
|
5260
|
+
async function listOpenCodePermissions(port, client) {
|
|
5456
5261
|
try {
|
|
5457
|
-
const
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
|
|
5463
|
-
|
|
5464
|
-
|
|
5465
|
-
return { ok: false, status: null, bodyEmpty: null, detail };
|
|
5262
|
+
const response = await requestWithClient(port, client, "/permission");
|
|
5263
|
+
const body = await response.json();
|
|
5264
|
+
return Array.isArray(body) ? body : null;
|
|
5265
|
+
} catch (error2) {
|
|
5266
|
+
console.error(
|
|
5267
|
+
`[listOpenCodePermissions] GET /permission failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5268
|
+
);
|
|
5269
|
+
return null;
|
|
5466
5270
|
}
|
|
5467
5271
|
}
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
function isRecord5(value) {
|
|
5472
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5272
|
+
function messageText(m) {
|
|
5273
|
+
if (!m || !Array.isArray(m.parts)) return "";
|
|
5274
|
+
return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
|
|
5473
5275
|
}
|
|
5474
|
-
function
|
|
5475
|
-
|
|
5276
|
+
function findDispatchedUserMessageId(messages, content, excludeIds) {
|
|
5277
|
+
if (!messages || messages.length === 0) return null;
|
|
5278
|
+
let best = null;
|
|
5279
|
+
for (const message of messages) {
|
|
5280
|
+
if (roleOf2(message) !== "user") continue;
|
|
5281
|
+
const id = idOf2(message);
|
|
5282
|
+
if (typeof id !== "string" || excludeIds?.has(id)) continue;
|
|
5283
|
+
if (messageText(message) !== content) continue;
|
|
5284
|
+
const created = createdOf(message) ?? 0;
|
|
5285
|
+
if (best === null || created > best.created) best = { id, created };
|
|
5286
|
+
}
|
|
5287
|
+
return best?.id ?? null;
|
|
5476
5288
|
}
|
|
5477
|
-
function
|
|
5478
|
-
|
|
5479
|
-
const
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5289
|
+
async function sendPromptAsync(port, sessionId, content, options, attachments, client, callbacks) {
|
|
5290
|
+
const before = await getSessionMessages(port, sessionId, client);
|
|
5291
|
+
const knownUserIds = new Set(
|
|
5292
|
+
(before ?? []).filter((m) => roleOf2(m) === "user").map((m) => idOf2(m)).filter((id) => typeof id === "string")
|
|
5293
|
+
);
|
|
5294
|
+
if (callbacks) {
|
|
5295
|
+
try {
|
|
5296
|
+
callbacks.onKnownUserIds(before === null ? null : knownUserIds);
|
|
5297
|
+
} catch (error2) {
|
|
5298
|
+
callbacks.onKnownUserIdsError(error2);
|
|
5299
|
+
}
|
|
5300
|
+
}
|
|
5301
|
+
const parts = [{ type: "text", text: content }];
|
|
5302
|
+
let pendingOutcomes = null;
|
|
5303
|
+
if (attachments && attachments.inputs.length > 0) {
|
|
5304
|
+
const capable = await getModelAttachmentCapability(port, options?.model, client);
|
|
5305
|
+
const {
|
|
5306
|
+
parts: fileParts,
|
|
5307
|
+
outcomes,
|
|
5308
|
+
capabilityUnknown
|
|
5309
|
+
} = await buildFileParts(attachments, capable);
|
|
5310
|
+
parts.push(...fileParts);
|
|
5311
|
+
if (attachments.onOutcomes) pendingOutcomes = { outcomes, capabilityUnknown };
|
|
5312
|
+
}
|
|
5313
|
+
const body = {
|
|
5314
|
+
parts
|
|
5485
5315
|
};
|
|
5316
|
+
applyModelOptions(body, options);
|
|
5317
|
+
const res = await requestWithClient(
|
|
5318
|
+
port,
|
|
5319
|
+
client,
|
|
5320
|
+
`/session/${sessionId}/prompt_async`,
|
|
5321
|
+
{
|
|
5322
|
+
method: "POST",
|
|
5323
|
+
headers: { "Content-Type": "application/json" },
|
|
5324
|
+
body: JSON.stringify(body)
|
|
5325
|
+
},
|
|
5326
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
5327
|
+
);
|
|
5328
|
+
if (res.status < 200 || res.status >= 300) {
|
|
5329
|
+
const text = await res.text().catch(() => "");
|
|
5330
|
+
const { variant } = splitModelVariant(options?.model);
|
|
5331
|
+
throw new Error(
|
|
5332
|
+
`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
|
|
5333
|
+
);
|
|
5334
|
+
}
|
|
5335
|
+
const READ_BACK_ATTEMPTS = 5;
|
|
5336
|
+
const READ_BACK_DELAY_MS = 150;
|
|
5337
|
+
for (let attempt = 0; attempt < READ_BACK_ATTEMPTS; attempt++) {
|
|
5338
|
+
const after = await getSessionMessages(port, sessionId, client);
|
|
5339
|
+
const dispatchedUserMessageId = findDispatchedUserMessageId(after, content, knownUserIds);
|
|
5340
|
+
if (dispatchedUserMessageId !== null) {
|
|
5341
|
+
if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
|
|
5342
|
+
return dispatchedUserMessageId;
|
|
5343
|
+
}
|
|
5344
|
+
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
5345
|
+
await new Promise((resolve6) => setTimeout(resolve6, READ_BACK_DELAY_MS));
|
|
5346
|
+
}
|
|
5347
|
+
}
|
|
5348
|
+
return null;
|
|
5486
5349
|
}
|
|
5487
|
-
function
|
|
5488
|
-
if (!
|
|
5489
|
-
const
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
return void 0;
|
|
5350
|
+
function findAssistantReplyAfter(messages, userMessageId) {
|
|
5351
|
+
if (!messages || messages.length === 0) return null;
|
|
5352
|
+
const byParent = messages.find(
|
|
5353
|
+
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId
|
|
5354
|
+
);
|
|
5355
|
+
if (byParent) return byParent;
|
|
5356
|
+
const userIndex = messages.findIndex((m) => idOf2(m) === userMessageId);
|
|
5357
|
+
if (userIndex === -1) return null;
|
|
5358
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
5359
|
+
if (roleOf2(messages[i]) === "assistant") return messages[i];
|
|
5498
5360
|
}
|
|
5499
|
-
return
|
|
5500
|
-
...input !== void 0 ? { input } : {},
|
|
5501
|
-
...output !== void 0 ? { output } : {},
|
|
5502
|
-
...reasoning !== void 0 ? { reasoning } : {},
|
|
5503
|
-
...cache ? { cache } : {}
|
|
5504
|
-
};
|
|
5361
|
+
return null;
|
|
5505
5362
|
}
|
|
5506
|
-
function
|
|
5507
|
-
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
5511
|
-
|
|
5512
|
-
|
|
5513
|
-
|
|
5514
|
-
|
|
5515
|
-
if (
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5363
|
+
function findLastAssistantReplyFor(messages, userMessageId) {
|
|
5364
|
+
if (!messages || messages.length === 0) return null;
|
|
5365
|
+
let lastCorrelated = null;
|
|
5366
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
5367
|
+
const m = messages[i];
|
|
5368
|
+
if (roleOf2(m) !== "assistant" || parentIdOf2(m) !== userMessageId) continue;
|
|
5369
|
+
lastCorrelated = m;
|
|
5370
|
+
break;
|
|
5371
|
+
}
|
|
5372
|
+
if (lastCorrelated) {
|
|
5373
|
+
if (errorOf(lastCorrelated) == null) return lastCorrelated;
|
|
5374
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
5375
|
+
const m = messages[i];
|
|
5376
|
+
if (roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId && isTerminalStopAnswer(m)) {
|
|
5377
|
+
return m;
|
|
5378
|
+
}
|
|
5379
|
+
}
|
|
5380
|
+
return lastCorrelated;
|
|
5381
|
+
}
|
|
5382
|
+
const userIndex = messages.findIndex((m) => idOf2(m) === userMessageId);
|
|
5383
|
+
if (userIndex === -1) return null;
|
|
5384
|
+
let last = null;
|
|
5385
|
+
let lastAssistantIndex = -1;
|
|
5386
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
5387
|
+
const role = roleOf2(messages[i]);
|
|
5388
|
+
if (role === "user") break;
|
|
5389
|
+
if (role === "assistant") {
|
|
5390
|
+
last = messages[i];
|
|
5391
|
+
lastAssistantIndex = i;
|
|
5392
|
+
}
|
|
5393
|
+
}
|
|
5394
|
+
if (last === null || errorOf(last) == null) return last;
|
|
5395
|
+
for (let i = lastAssistantIndex; i > userIndex; i--) {
|
|
5396
|
+
const m = messages[i];
|
|
5397
|
+
if (roleOf2(m) === "user") break;
|
|
5398
|
+
if (roleOf2(m) === "assistant" && isTerminalStopAnswer(m)) return m;
|
|
5399
|
+
}
|
|
5400
|
+
return last;
|
|
5401
|
+
}
|
|
5402
|
+
function assistantMessagesInTurnBlock(messages, userMessageId) {
|
|
5403
|
+
const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
|
|
5404
|
+
if (userIndex === -1) return [];
|
|
5405
|
+
const assistants = [];
|
|
5406
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
5407
|
+
const message = messages[i];
|
|
5408
|
+
const role = roleOf2(message);
|
|
5409
|
+
if (role === "user") break;
|
|
5410
|
+
if (role === "assistant") assistants.push(message);
|
|
5411
|
+
}
|
|
5412
|
+
return assistants;
|
|
5413
|
+
}
|
|
5414
|
+
function collectSubagentSessions(messages, userMessageId) {
|
|
5415
|
+
if (!messages || messages.length === 0) return [];
|
|
5416
|
+
const byParent = messages.filter(
|
|
5417
|
+
(message) => roleOf2(message) === "assistant" && parentIdOf2(message) === userMessageId
|
|
5418
|
+
);
|
|
5419
|
+
const assistants = byParent.length > 0 ? byParent : assistantMessagesInTurnBlock(messages, userMessageId);
|
|
5420
|
+
const refs = [];
|
|
5421
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5422
|
+
for (const message of assistants) {
|
|
5423
|
+
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
5424
|
+
for (const part of parts) {
|
|
5425
|
+
if (!part || typeof part !== "object" || part.type !== "tool") continue;
|
|
5426
|
+
const childSession = part.childSession;
|
|
5427
|
+
if (childSession) {
|
|
5428
|
+
if (seen.has(childSession.sessionId)) continue;
|
|
5429
|
+
seen.add(childSession.sessionId);
|
|
5430
|
+
refs.push(childSession);
|
|
5431
|
+
continue;
|
|
5432
|
+
}
|
|
5433
|
+
if (part.tool !== "task") continue;
|
|
5434
|
+
const state = part.state;
|
|
5435
|
+
if (!state || typeof state !== "object") continue;
|
|
5436
|
+
const metadata = state.metadata;
|
|
5437
|
+
if (!metadata || typeof metadata !== "object") continue;
|
|
5438
|
+
const sessionId = metadata.sessionId;
|
|
5439
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || seen.has(sessionId)) continue;
|
|
5440
|
+
seen.add(sessionId);
|
|
5441
|
+
const start = state.time?.start;
|
|
5442
|
+
refs.push({
|
|
5443
|
+
sessionId,
|
|
5444
|
+
startedAtMs: typeof start === "number" && Number.isFinite(start) ? start : null
|
|
5445
|
+
});
|
|
5446
|
+
}
|
|
5519
5447
|
}
|
|
5520
|
-
|
|
5521
|
-
const tokens = adaptTokens(value.tokens);
|
|
5522
|
-
if (tokens) info.tokens = tokens;
|
|
5523
|
-
return info;
|
|
5448
|
+
return refs;
|
|
5524
5449
|
}
|
|
5525
|
-
function
|
|
5526
|
-
|
|
5527
|
-
const metadata = state && isRecord5(state.metadata) ? state.metadata : null;
|
|
5528
|
-
const sessionId = typeof metadata?.sessionID === "string" && metadata.sessionID.length > 0 ? metadata.sessionID : typeof metadata?.sessionId === "string" && metadata.sessionId.length > 0 ? metadata.sessionId : null;
|
|
5529
|
-
if (sessionId === null) return null;
|
|
5530
|
-
const time = isRecord5(content.time) ? content.time : null;
|
|
5531
|
-
return { sessionId, startedAtMs: finiteNumber2(time?.created) ?? null };
|
|
5450
|
+
function finiteNumber2(value) {
|
|
5451
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
5532
5452
|
}
|
|
5533
|
-
function
|
|
5534
|
-
if (!
|
|
5535
|
-
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5539
|
-
|
|
5540
|
-
|
|
5541
|
-
|
|
5542
|
-
|
|
5453
|
+
function taskCallModel(value) {
|
|
5454
|
+
if (!value || typeof value !== "object") return null;
|
|
5455
|
+
const model = value;
|
|
5456
|
+
const modelID = typeof model.modelID === "string" ? model.modelID : void 0;
|
|
5457
|
+
const providerID = typeof model.providerID === "string" ? model.providerID : void 0;
|
|
5458
|
+
return modelID || providerID ? { modelID, providerID } : null;
|
|
5459
|
+
}
|
|
5460
|
+
function collectTaskCalls(messages, userMessageId) {
|
|
5461
|
+
if (!messages || messages.length === 0) return [];
|
|
5462
|
+
const calls = [];
|
|
5463
|
+
for (const message of messages) {
|
|
5464
|
+
if (roleOf2(message) !== "assistant" || parentIdOf2(message) !== userMessageId) continue;
|
|
5465
|
+
for (const part of message.parts ?? []) {
|
|
5466
|
+
if (part.tool !== "task" || !part.callID || !part.state || part.state.status === "pending") {
|
|
5467
|
+
continue;
|
|
5468
|
+
}
|
|
5469
|
+
const rawName = part.state.input?.subagent_type;
|
|
5470
|
+
const subagentName = typeof rawName === "string" && rawName.trim().length > 0 ? rawName : rawName === void 0 ? "general" : "unknown";
|
|
5471
|
+
const metadata = part.state.metadata;
|
|
5472
|
+
calls.push({
|
|
5473
|
+
callID: part.callID,
|
|
5474
|
+
subagentName,
|
|
5475
|
+
childSessionId: typeof metadata?.sessionId === "string" ? metadata.sessionId : null,
|
|
5476
|
+
parentSessionId: typeof metadata?.parentSessionId === "string" ? metadata.parentSessionId : null,
|
|
5477
|
+
model: taskCallModel(metadata?.model),
|
|
5478
|
+
status: part.state.status ?? "unknown",
|
|
5479
|
+
timeStart: finiteNumber2(part.state.time?.start),
|
|
5480
|
+
timeEnd: finiteNumber2(part.state.time?.end)
|
|
5481
|
+
});
|
|
5482
|
+
}
|
|
5543
5483
|
}
|
|
5544
|
-
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5484
|
+
return calls;
|
|
5485
|
+
}
|
|
5486
|
+
function attributeTaskCallUsage(messages, windows) {
|
|
5487
|
+
const eligibleWindows = windows.filter(
|
|
5488
|
+
(window) => window.timeStart !== null && Number.isFinite(window.timeStart)
|
|
5489
|
+
);
|
|
5490
|
+
const assignments = /* @__PURE__ */ new Map();
|
|
5491
|
+
for (const window of eligibleWindows) assignments.set(window.callID, []);
|
|
5492
|
+
const unattributed = [];
|
|
5493
|
+
for (const message of messages ?? []) {
|
|
5494
|
+
if (roleOf2(message) !== "assistant") continue;
|
|
5495
|
+
const created = finiteNumber2(createdOf(message));
|
|
5496
|
+
const matching = created === null ? [] : eligibleWindows.filter(
|
|
5497
|
+
(window) => window.timeStart <= created && (window.timeEnd === null || window.timeEnd === void 0 || created <= window.timeEnd)
|
|
5498
|
+
);
|
|
5499
|
+
if (matching.length === 0) {
|
|
5500
|
+
unattributed.push(message);
|
|
5552
5501
|
continue;
|
|
5553
5502
|
}
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
parts.push({ type: "text", text: content.text });
|
|
5557
|
-
} else {
|
|
5558
|
-
parts.push({ type: content.type });
|
|
5559
|
-
}
|
|
5503
|
+
matching.sort((a, b) => a.timeStart - b.timeStart);
|
|
5504
|
+
assignments.get(matching[0].callID)?.push(message);
|
|
5560
5505
|
}
|
|
5561
5506
|
return {
|
|
5562
|
-
|
|
5563
|
-
|
|
5507
|
+
invocations: eligibleWindows.map((window) => {
|
|
5508
|
+
const assigned = assignments.get(window.callID) ?? [];
|
|
5509
|
+
return { callID: window.callID, messages: assigned, usage: sumAssistantUsage(assigned) };
|
|
5510
|
+
}),
|
|
5511
|
+
unattributed
|
|
5564
5512
|
};
|
|
5565
5513
|
}
|
|
5566
|
-
function
|
|
5567
|
-
if (!
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5514
|
+
function sumAssistantUsage(messages) {
|
|
5515
|
+
if (!messages || messages.length === 0) return null;
|
|
5516
|
+
const hasTrailingError = errorOf(messages[messages.length - 1]) != null;
|
|
5517
|
+
const hasTerminalStopAnswer = messages.some(isTerminalStopAnswer);
|
|
5518
|
+
const selected = hasTrailingError && hasTerminalStopAnswer ? messages.filter((message) => errorOf(message) == null) : messages;
|
|
5519
|
+
let sawAnyUsage = false;
|
|
5520
|
+
let inputSum = 0;
|
|
5521
|
+
let outputSum = 0;
|
|
5522
|
+
let reasoningSum = 0;
|
|
5523
|
+
let cacheReadSum = 0;
|
|
5524
|
+
let cacheWriteSum = 0;
|
|
5525
|
+
let costSum = 0;
|
|
5526
|
+
let sawCost = false;
|
|
5527
|
+
let toolCallCount = 0;
|
|
5528
|
+
let modelId = null;
|
|
5529
|
+
let providerId = null;
|
|
5530
|
+
for (const m of selected) {
|
|
5531
|
+
toolCallCount += m.parts?.filter((part) => part.type === "tool").length ?? 0;
|
|
5532
|
+
const info = m.info;
|
|
5533
|
+
if (!info) continue;
|
|
5534
|
+
const tokens = info.tokens;
|
|
5535
|
+
if (tokens) {
|
|
5536
|
+
sawAnyUsage = true;
|
|
5537
|
+
inputSum += tokens.input ?? 0;
|
|
5538
|
+
outputSum += tokens.output ?? 0;
|
|
5539
|
+
reasoningSum += tokens.reasoning ?? 0;
|
|
5540
|
+
cacheReadSum += tokens.cache?.read ?? 0;
|
|
5541
|
+
cacheWriteSum += tokens.cache?.write ?? 0;
|
|
5542
|
+
}
|
|
5543
|
+
if (typeof info.cost === "number") {
|
|
5544
|
+
sawAnyUsage = true;
|
|
5545
|
+
sawCost = true;
|
|
5546
|
+
costSum += info.cost;
|
|
5547
|
+
}
|
|
5548
|
+
if (typeof info.modelID === "string") {
|
|
5549
|
+
sawAnyUsage = true;
|
|
5550
|
+
modelId = info.modelID;
|
|
5551
|
+
}
|
|
5552
|
+
if (typeof info.providerID === "string") {
|
|
5553
|
+
sawAnyUsage = true;
|
|
5554
|
+
providerId = info.providerID;
|
|
5555
|
+
}
|
|
5575
5556
|
}
|
|
5576
|
-
return
|
|
5577
|
-
}
|
|
5578
|
-
function adaptV2FormField(value, header) {
|
|
5579
|
-
if (!isRecord5(value)) return null;
|
|
5580
|
-
const question = typeof value.title === "string" ? value.title : typeof value.question === "string" ? value.question : typeof value.key === "string" ? value.key : null;
|
|
5581
|
-
if (!question) return null;
|
|
5582
|
-
const options = Array.isArray(value.options) ? value.options.flatMap((option) => {
|
|
5583
|
-
if (!isRecord5(option)) return [];
|
|
5584
|
-
const label = typeof option.label === "string" ? option.label : typeof option.value === "string" ? option.value : null;
|
|
5585
|
-
if (!label) return [];
|
|
5586
|
-
return [
|
|
5587
|
-
{
|
|
5588
|
-
label,
|
|
5589
|
-
description: typeof option.description === "string" ? option.description : ""
|
|
5590
|
-
}
|
|
5591
|
-
];
|
|
5592
|
-
}) : [];
|
|
5593
|
-
return { question, header, options };
|
|
5594
|
-
}
|
|
5595
|
-
function adaptV2Form(value) {
|
|
5596
|
-
const form = adaptV2FormWire(value);
|
|
5597
|
-
if (!form || !Array.isArray(form.fields)) return null;
|
|
5598
|
-
const header = typeof form.title === "string" ? form.title : "";
|
|
5599
|
-
const questions = form.fields.map((field) => adaptV2FormField(field, header)).filter((question) => question !== null);
|
|
5600
|
-
if (questions.length === 0) return null;
|
|
5601
|
-
const tool = isRecord5(form.metadata) ? adaptFormTool(form.metadata.tool) : void 0;
|
|
5557
|
+
if (!sawAnyUsage) return null;
|
|
5602
5558
|
return {
|
|
5603
|
-
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5559
|
+
usage_provider_id: providerId,
|
|
5560
|
+
usage_model_id: modelId,
|
|
5561
|
+
usage_tokens_input: inputSum,
|
|
5562
|
+
usage_tokens_output: outputSum,
|
|
5563
|
+
usage_tokens_reasoning: reasoningSum,
|
|
5564
|
+
usage_tokens_cache_read: cacheReadSum,
|
|
5565
|
+
usage_tokens_cache_write: cacheWriteSum,
|
|
5566
|
+
// NULL means OpenCode never reported a cost; it is distinct from a genuine
|
|
5567
|
+
// zero-cost message, which sets `sawCost` with `costSum === 0`.
|
|
5568
|
+
usage_cost_usd: sawCost ? costSum : null,
|
|
5569
|
+
turn_tool_calls: toolCallCount
|
|
5608
5570
|
};
|
|
5609
5571
|
}
|
|
5610
|
-
function
|
|
5611
|
-
if (!
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
if (
|
|
5617
|
-
|
|
5572
|
+
function messageUsage(messages, userMessageId) {
|
|
5573
|
+
if (!messages || messages.length === 0) return null;
|
|
5574
|
+
const byParentAll = messages.filter(
|
|
5575
|
+
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) === userMessageId
|
|
5576
|
+
);
|
|
5577
|
+
let correlated;
|
|
5578
|
+
if (byParentAll.length > 0) {
|
|
5579
|
+
correlated = byParentAll;
|
|
5580
|
+
} else {
|
|
5581
|
+
correlated = assistantMessagesInTurnBlock(messages, userMessageId);
|
|
5618
5582
|
}
|
|
5619
|
-
|
|
5583
|
+
if (correlated.length === 0) return null;
|
|
5584
|
+
return sumAssistantUsage(correlated);
|
|
5620
5585
|
}
|
|
5621
|
-
function
|
|
5622
|
-
if (!
|
|
5623
|
-
|
|
5586
|
+
function messageRunState(messages, userMessageId) {
|
|
5587
|
+
if (!messages || messages.length === 0) return "unknown";
|
|
5588
|
+
const hasUser = messages.some((m) => idOf2(m) === userMessageId);
|
|
5589
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5590
|
+
if (!hasUser) {
|
|
5591
|
+
if (!reply) return "unknown";
|
|
5624
5592
|
}
|
|
5625
|
-
if (
|
|
5626
|
-
return
|
|
5593
|
+
if (!reply) return "queued";
|
|
5594
|
+
if (isAssistantInFlight(reply)) return "running";
|
|
5595
|
+
if (errorOf(reply) != null) return "failed";
|
|
5596
|
+
if (isAmbiguousTerminalFinish(reply)) return "running";
|
|
5597
|
+
return "done";
|
|
5627
5598
|
}
|
|
5628
|
-
function
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5634
|
-
|
|
5635
|
-
|
|
5636
|
-
|
|
5637
|
-
type,
|
|
5638
|
-
sessionID: permission.sessionID,
|
|
5639
|
-
metadata: isRecord5(permission.metadata) ? permission.metadata : {},
|
|
5640
|
-
raw: permission,
|
|
5641
|
-
...pattern !== void 0 ? { pattern } : {},
|
|
5642
|
-
...typeof permission.messageID === "string" ? { messageID: permission.messageID } : {},
|
|
5643
|
-
...typeof permission.callID === "string" ? { callID: permission.callID } : {},
|
|
5644
|
-
...typeof permission.title === "string" ? { title: permission.title } : {},
|
|
5645
|
-
...time ? { time } : {}
|
|
5646
|
-
};
|
|
5599
|
+
function isPreamblePinnedRunning(messages, userMessageId) {
|
|
5600
|
+
if (messageRunState(messages, userMessageId) !== "running") return false;
|
|
5601
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5602
|
+
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
5603
|
+
}
|
|
5604
|
+
function isMidFlightPinnedRunning(messages, userMessageId) {
|
|
5605
|
+
if (messageRunState(messages, userMessageId) !== "running") return false;
|
|
5606
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5607
|
+
return reply !== null && isAssistantInFlight(reply) && completedOf(reply) == null;
|
|
5647
5608
|
}
|
|
5648
|
-
function
|
|
5649
|
-
|
|
5650
|
-
return value.data.map(adaptV2Permission).filter((permission) => permission !== null);
|
|
5609
|
+
function isB2AbandonmentConfirmed(params) {
|
|
5610
|
+
return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
|
|
5651
5611
|
}
|
|
5652
|
-
function
|
|
5653
|
-
|
|
5654
|
-
const time = isRecord5(value.time) ? {
|
|
5655
|
-
...finiteNumber2(value.time.created) !== void 0 ? { created: finiteNumber2(value.time.created) } : {},
|
|
5656
|
-
...finiteNumber2(value.time.updated) !== void 0 ? { updated: finiteNumber2(value.time.updated) } : {}
|
|
5657
|
-
} : void 0;
|
|
5658
|
-
return {
|
|
5659
|
-
id: value.id,
|
|
5660
|
-
...typeof value.title === "string" ? { title: value.title } : {},
|
|
5661
|
-
...typeof value.parentID === "string" ? { parentID: value.parentID } : {},
|
|
5662
|
-
...time && Object.keys(time).length > 0 ? { time } : {}
|
|
5663
|
-
};
|
|
5612
|
+
function isMidFlightOrphanConfirmed(params) {
|
|
5613
|
+
return params.pinnedForMs >= params.minPinnedMs && params.notOngoingStreak >= params.minNotOngoingStreak;
|
|
5664
5614
|
}
|
|
5665
|
-
function
|
|
5666
|
-
if (
|
|
5667
|
-
return
|
|
5668
|
-
|
|
5669
|
-
|
|
5670
|
-
};
|
|
5615
|
+
function isAmbiguousTerminalFinish(m) {
|
|
5616
|
+
if (completedOf(m) == null) return false;
|
|
5617
|
+
if (errorOf(m) != null) return false;
|
|
5618
|
+
const finish = finishOf(m);
|
|
5619
|
+
return finish !== "tool-calls" && finish !== "stop";
|
|
5671
5620
|
}
|
|
5672
|
-
function
|
|
5673
|
-
const
|
|
5674
|
-
|
|
5675
|
-
|
|
5676
|
-
|
|
5677
|
-
|
|
5678
|
-
|
|
5679
|
-
|
|
5680
|
-
|
|
5681
|
-
|
|
5621
|
+
function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
|
|
5622
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5623
|
+
return isAmbiguousTerminalFinish(reply);
|
|
5624
|
+
}
|
|
5625
|
+
function isAmbiguousFinishResolved(params) {
|
|
5626
|
+
return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
|
|
5627
|
+
}
|
|
5628
|
+
function messageError(messages, userMessageId) {
|
|
5629
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5630
|
+
const error2 = errorOf(reply);
|
|
5631
|
+
if (error2 == null) return null;
|
|
5632
|
+
let rendered;
|
|
5633
|
+
if (typeof error2 === "string") {
|
|
5634
|
+
rendered = error2;
|
|
5635
|
+
} else if (typeof error2 === "object") {
|
|
5636
|
+
const e = error2;
|
|
5637
|
+
const dataMessage = e.data?.message;
|
|
5638
|
+
if (typeof dataMessage === "string") {
|
|
5639
|
+
rendered = dataMessage;
|
|
5640
|
+
} else if (typeof e.message === "string") {
|
|
5641
|
+
rendered = e.message;
|
|
5642
|
+
} else {
|
|
5643
|
+
rendered = "The agent run failed.";
|
|
5644
|
+
}
|
|
5645
|
+
} else {
|
|
5646
|
+
rendered = "The agent run failed.";
|
|
5682
5647
|
}
|
|
5683
|
-
|
|
5648
|
+
const toolPart = Array.isArray(reply?.parts) ? reply.parts.find(
|
|
5649
|
+
(part) => part && typeof part === "object" && part.type === "tool" && part.state?.status === "error"
|
|
5650
|
+
) : void 0;
|
|
5651
|
+
return typeof toolPart?.tool === "string" && toolPart.tool.length > 0 ? `${rendered} (tool "${toolPart.tool}")` : rendered;
|
|
5684
5652
|
}
|
|
5685
|
-
function
|
|
5686
|
-
|
|
5687
|
-
|
|
5653
|
+
function describeAbandonedReplyShape(messages, userMessageId) {
|
|
5654
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5655
|
+
if (!reply) return null;
|
|
5656
|
+
const parts = Array.isArray(reply.parts) ? reply.parts : [];
|
|
5657
|
+
const lastTool = [...parts].reverse().find((part) => part?.type === "tool");
|
|
5658
|
+
return {
|
|
5659
|
+
partTypes: parts.slice(-12).map((part) => typeof part?.type === "string" ? part.type : "(unknown)"),
|
|
5660
|
+
droppedPartCount: Math.max(0, parts.length - 12),
|
|
5661
|
+
lastToolName: typeof lastTool?.tool === "string" && lastTool.tool.length > 0 ? lastTool.tool : null,
|
|
5662
|
+
lastToolStatus: typeof lastTool?.state?.status === "string" && lastTool.state.status.length > 0 ? lastTool.state.status : null
|
|
5663
|
+
};
|
|
5688
5664
|
}
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5665
|
+
function isAbortedTerminalReply(messages, userMessageId) {
|
|
5666
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
5667
|
+
const error2 = errorOf(reply);
|
|
5668
|
+
if (error2 == null) return false;
|
|
5669
|
+
if (typeof error2 === "string") return error2.trim() === "Aborted";
|
|
5670
|
+
if (typeof error2 === "object") {
|
|
5671
|
+
const e = error2;
|
|
5672
|
+
if (e.name === "MessageAbortedError") return true;
|
|
5673
|
+
if (e.name === "AbortError") return true;
|
|
5674
|
+
const dataMessage = e.data?.message;
|
|
5675
|
+
const rendered = typeof dataMessage === "string" ? dataMessage : typeof e.message === "string" ? e.message : null;
|
|
5676
|
+
return rendered != null && rendered.trim() === "Aborted";
|
|
5696
5677
|
}
|
|
5678
|
+
return false;
|
|
5697
5679
|
}
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
|
|
5701
|
-
|
|
5702
|
-
|
|
5680
|
+
var CLAUDE_AUTH_EXPIRY_MESSAGES = Object.freeze([
|
|
5681
|
+
"Claude Code credentials are unavailable or expired. Run `claude` to refresh them."
|
|
5682
|
+
]);
|
|
5683
|
+
function extractReplyErrorShape(reply) {
|
|
5684
|
+
const error2 = errorOf(reply);
|
|
5685
|
+
if (error2 == null || typeof error2 !== "object") {
|
|
5686
|
+
return { name: null, statusCode: null };
|
|
5703
5687
|
}
|
|
5704
|
-
|
|
5688
|
+
const e = error2;
|
|
5689
|
+
const name = typeof e.name === "string" ? e.name.slice(0, 100) : null;
|
|
5690
|
+
const data = e.data;
|
|
5691
|
+
const statusCode = typeof data?.statusCode === "number" && Number.isFinite(data.statusCode) ? data.statusCode : null;
|
|
5692
|
+
return { name, statusCode };
|
|
5705
5693
|
}
|
|
5706
|
-
|
|
5707
|
-
|
|
5708
|
-
|
|
5709
|
-
|
|
5694
|
+
function classifyReplyAuthError(reply) {
|
|
5695
|
+
const error2 = errorOf(reply);
|
|
5696
|
+
if (error2 == null || typeof error2 !== "object") return null;
|
|
5697
|
+
const e = error2;
|
|
5698
|
+
const replyProviderId = reply?.info?.providerID ?? null;
|
|
5699
|
+
const replyModelId = reply?.info?.modelID ?? null;
|
|
5700
|
+
const data = e.data;
|
|
5701
|
+
if (e.name === "ProviderAuthError") {
|
|
5702
|
+
const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
|
|
5703
|
+
return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
|
|
5710
5704
|
}
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
|
|
5714
|
-
|
|
5715
|
-
|
|
5716
|
-
|
|
5717
|
-
|
|
5705
|
+
if (e.name === "APIError") {
|
|
5706
|
+
const statusCode = data?.statusCode;
|
|
5707
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
5708
|
+
return {
|
|
5709
|
+
kind: "model_auth",
|
|
5710
|
+
providerId: replyProviderId,
|
|
5711
|
+
modelId: replyModelId,
|
|
5712
|
+
reason: "rejected"
|
|
5713
|
+
};
|
|
5714
|
+
}
|
|
5718
5715
|
}
|
|
5719
|
-
|
|
5720
|
-
|
|
5721
|
-
|
|
5722
|
-
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
|
|
5726
|
-
|
|
5727
|
-
return null;
|
|
5716
|
+
const errorMessage4 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
|
|
5717
|
+
if (errorMessage4 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage4.includes(knownMessage))) {
|
|
5718
|
+
return {
|
|
5719
|
+
kind: "model_auth",
|
|
5720
|
+
providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
|
|
5721
|
+
modelId: replyModelId,
|
|
5722
|
+
reason: "rejected"
|
|
5723
|
+
};
|
|
5728
5724
|
}
|
|
5725
|
+
return null;
|
|
5729
5726
|
}
|
|
5730
|
-
|
|
5731
|
-
|
|
5732
|
-
method: "POST",
|
|
5733
|
-
headers: { "Content-Type": "application/json" },
|
|
5734
|
-
body: JSON.stringify({ location: { directory } })
|
|
5735
|
-
});
|
|
5736
|
-
if (!isRecord5(data) || typeof data.id !== "string" || data.id.length === 0) {
|
|
5737
|
-
throw new Error("OpenCode V2 create session response was missing data.id");
|
|
5738
|
-
}
|
|
5739
|
-
return data.id;
|
|
5727
|
+
function messageFailure(messages, userMessageId) {
|
|
5728
|
+
return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
|
|
5740
5729
|
}
|
|
5741
|
-
|
|
5742
|
-
|
|
5743
|
-
const session = adaptV2Session(data);
|
|
5744
|
-
if (!session) throw new Error("OpenCode V2 get session response contained an invalid session");
|
|
5745
|
-
return session;
|
|
5730
|
+
function isProviderModelNotFoundError(reason) {
|
|
5731
|
+
return reason.includes("Model not found:");
|
|
5746
5732
|
}
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5733
|
+
function findLatestSubagentAuthOutcome(messages, sinceMs) {
|
|
5734
|
+
if (!messages || messages.length === 0) return null;
|
|
5735
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
5736
|
+
const message = messages[i];
|
|
5737
|
+
if (roleOf2(message) !== "assistant") continue;
|
|
5738
|
+
const created = createdOf(message);
|
|
5739
|
+
if (sinceMs !== null && typeof created === "number" && created < sinceMs) continue;
|
|
5740
|
+
const failure = classifyReplyAuthError(message);
|
|
5741
|
+
if (failure) {
|
|
5742
|
+
if (!failure.providerId) return null;
|
|
5743
|
+
return { providerId: failure.providerId, outcome: "failed", failure };
|
|
5744
|
+
}
|
|
5745
|
+
const providerId = message.info?.providerID;
|
|
5746
|
+
if (errorOf(message) == null && typeof providerId === "string" && providerId.length > 0) {
|
|
5747
|
+
return { providerId, outcome: "succeeded" };
|
|
5759
5748
|
}
|
|
5760
|
-
return adaptV2SessionList(await readJson(response));
|
|
5761
|
-
} catch (error2) {
|
|
5762
|
-
if (signal?.aborted) return null;
|
|
5763
|
-
const errorName = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
5764
|
-
console.error(`[listV2SessionPage] ${operation} failed (port ${client.port}): ${errorName}`);
|
|
5765
5749
|
return null;
|
|
5766
5750
|
}
|
|
5751
|
+
return null;
|
|
5767
5752
|
}
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
|
|
5778
|
-
|
|
5779
|
-
|
|
5780
|
-
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
|
|
5784
|
-
|
|
5785
|
-
|
|
5786
|
-
|
|
5787
|
-
|
|
5753
|
+
function findSubagentAuthOutcome(messages, sinceMs) {
|
|
5754
|
+
return findLatestSubagentAuthOutcome(messages, sinceMs);
|
|
5755
|
+
}
|
|
5756
|
+
function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
|
|
5757
|
+
if (classified != null) return classified;
|
|
5758
|
+
if (hasConfiguredProvider !== false) return null;
|
|
5759
|
+
return {
|
|
5760
|
+
kind: "model_auth",
|
|
5761
|
+
providerId: replyProviderId,
|
|
5762
|
+
modelId: replyModelId,
|
|
5763
|
+
reason: "missing"
|
|
5764
|
+
};
|
|
5765
|
+
}
|
|
5766
|
+
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
5767
|
+
if (!messages || messages.length === 0) return false;
|
|
5768
|
+
return messages.some(
|
|
5769
|
+
(m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
5770
|
+
);
|
|
5771
|
+
}
|
|
5772
|
+
function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
|
|
5773
|
+
if (!messages || messages.length === 0) return false;
|
|
5774
|
+
const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
|
|
5775
|
+
if (userIndex === -1) return false;
|
|
5776
|
+
let hasLaterUser = false;
|
|
5777
|
+
let hasStartedLaterUser = false;
|
|
5778
|
+
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
5779
|
+
const message = messages[i];
|
|
5780
|
+
if (roleOf2(message) !== "user") continue;
|
|
5781
|
+
hasLaterUser = true;
|
|
5782
|
+
const laterUserMessageId = idOf2(message);
|
|
5783
|
+
if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
|
|
5784
|
+
return false;
|
|
5785
|
+
}
|
|
5786
|
+
if (messages.some(
|
|
5787
|
+
(candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
|
|
5788
|
+
)) {
|
|
5789
|
+
hasStartedLaterUser = true;
|
|
5788
5790
|
}
|
|
5789
|
-
return sessions;
|
|
5790
|
-
} catch (error2) {
|
|
5791
|
-
const errorName = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
|
|
5792
|
-
console.error(
|
|
5793
|
-
`[listV2Sessions] GET /api/session pagination failed (port ${client.port}): ${errorName}`
|
|
5794
|
-
);
|
|
5795
|
-
return null;
|
|
5796
5791
|
}
|
|
5792
|
+
return hasLaterUser && hasStartedLaterUser;
|
|
5797
5793
|
}
|
|
5798
|
-
async function
|
|
5799
|
-
|
|
5800
|
-
const
|
|
5801
|
-
|
|
5802
|
-
|
|
5803
|
-
|
|
5804
|
-
|
|
5805
|
-
|
|
5806
|
-
return { ok: true, status: response.status };
|
|
5794
|
+
async function hasAnyConfiguredProvider(port, client) {
|
|
5795
|
+
if (client?.version === "v2") {
|
|
5796
|
+
const directory = await getOpenCodeDirectoryV2(client);
|
|
5797
|
+
if (!directory) {
|
|
5798
|
+
console.error(
|
|
5799
|
+
`[hasAnyConfiguredProvider] V2 working directory was unavailable (port ${port})`
|
|
5800
|
+
);
|
|
5801
|
+
return null;
|
|
5807
5802
|
}
|
|
5803
|
+
const query = `?location%5Bdirectory%5D=${encodeURIComponent(directory)}`;
|
|
5804
|
+
const integrationPath = `/api/integration${query}`;
|
|
5805
|
+
let integrationReady = null;
|
|
5808
5806
|
try {
|
|
5809
|
-
const
|
|
5810
|
-
|
|
5807
|
+
const res = await client.request(integrationPath);
|
|
5808
|
+
if (!res.ok) {
|
|
5809
|
+
console.error(
|
|
5810
|
+
`[hasAnyConfiguredProvider] GET ${integrationPath} returned HTTP ${res.status} (port ${port})`
|
|
5811
|
+
);
|
|
5812
|
+
} else {
|
|
5813
|
+
const body = await res.json();
|
|
5814
|
+
if (!body || typeof body !== "object" || Array.isArray(body) || !Array.isArray(body.data)) {
|
|
5815
|
+
console.error(
|
|
5816
|
+
`[hasAnyConfiguredProvider] GET ${integrationPath} body had no integration data array (port ${port})`
|
|
5817
|
+
);
|
|
5818
|
+
} else {
|
|
5819
|
+
let valid = true;
|
|
5820
|
+
for (const integration of body.data) {
|
|
5821
|
+
if (!integration || typeof integration !== "object" || Array.isArray(integration) || typeof integration.id !== "string" || !Array.isArray(integration.connections)) {
|
|
5822
|
+
console.error(
|
|
5823
|
+
`[hasAnyConfiguredProvider] GET ${integrationPath} body contained an invalid integration (port ${port})`
|
|
5824
|
+
);
|
|
5825
|
+
valid = false;
|
|
5826
|
+
break;
|
|
5827
|
+
}
|
|
5828
|
+
}
|
|
5829
|
+
if (valid) {
|
|
5830
|
+
integrationReady = body.data.some(
|
|
5831
|
+
(integration) => integration.connections.length > 0
|
|
5832
|
+
);
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
5835
|
+
}
|
|
5811
5836
|
} catch (error2) {
|
|
5812
5837
|
console.error(
|
|
5813
|
-
`[
|
|
5838
|
+
`[hasAnyConfiguredProvider] GET ${integrationPath} failed (port ${port}): ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5814
5839
|
);
|
|
5815
|
-
return { ok: false, status: response.status };
|
|
5816
5840
|
}
|
|
5817
|
-
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
);
|
|
5821
|
-
return { ok: false, status: "threw" };
|
|
5822
|
-
}
|
|
5823
|
-
}
|
|
5824
|
-
async function v2SessionExists(client, sessionId) {
|
|
5825
|
-
try {
|
|
5826
|
-
const response = await client.request(
|
|
5827
|
-
`/api/session/${encodeURIComponent(sessionId)}`,
|
|
5828
|
-
void 0,
|
|
5829
|
-
{ allowStatuses: [404] }
|
|
5830
|
-
);
|
|
5831
|
-
return response.status === 404 ? false : true;
|
|
5832
|
-
} catch (error2) {
|
|
5833
|
-
console.error(
|
|
5834
|
-
`[v2SessionExists] GET /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5835
|
-
);
|
|
5836
|
-
return null;
|
|
5837
|
-
}
|
|
5838
|
-
}
|
|
5839
|
-
async function sendV2Prompt(client, sessionId, text, options, onInvalidModelSelection) {
|
|
5840
|
-
const modelSelection = options?.model?.trim();
|
|
5841
|
-
const { model, variant } = splitModelVariant(modelSelection);
|
|
5842
|
-
const separator = model?.indexOf("/") ?? -1;
|
|
5843
|
-
const modelReference = model && separator > 0 && separator < model.length - 1 ? {
|
|
5844
|
-
id: model.slice(separator + 1),
|
|
5845
|
-
providerID: model.slice(0, separator),
|
|
5846
|
-
...variant ? { variant } : {}
|
|
5847
|
-
} : void 0;
|
|
5848
|
-
if (modelSelection && !modelReference) onInvalidModelSelection?.();
|
|
5849
|
-
if (options?.agent) {
|
|
5850
|
-
await client.request(`/api/session/${encodeURIComponent(sessionId)}/agent`, {
|
|
5851
|
-
method: "POST",
|
|
5852
|
-
headers: { "Content-Type": "application/json" },
|
|
5853
|
-
body: JSON.stringify({ agent: options.agent })
|
|
5854
|
-
});
|
|
5855
|
-
}
|
|
5856
|
-
if (modelReference) {
|
|
5841
|
+
if (integrationReady === true) return true;
|
|
5842
|
+
const providerPath = `/api/provider${query}`;
|
|
5843
|
+
let providerReady = null;
|
|
5857
5844
|
try {
|
|
5858
|
-
await client.request(
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5845
|
+
const res = await client.request(providerPath);
|
|
5846
|
+
if (!res.ok) {
|
|
5847
|
+
console.error(
|
|
5848
|
+
`[hasAnyConfiguredProvider] GET ${providerPath} returned HTTP ${res.status} (port ${port})`
|
|
5849
|
+
);
|
|
5850
|
+
} else {
|
|
5851
|
+
const body = await res.json();
|
|
5852
|
+
if (!body || typeof body !== "object" || Array.isArray(body) || !Array.isArray(body.data)) {
|
|
5853
|
+
console.error(
|
|
5854
|
+
`[hasAnyConfiguredProvider] GET ${providerPath} body had no provider data array (port ${port})`
|
|
5855
|
+
);
|
|
5856
|
+
} else {
|
|
5857
|
+
let valid = true;
|
|
5858
|
+
for (const provider of body.data) {
|
|
5859
|
+
if (!provider || typeof provider !== "object" || Array.isArray(provider) || typeof provider.id !== "string") {
|
|
5860
|
+
console.error(
|
|
5861
|
+
`[hasAnyConfiguredProvider] GET ${providerPath} body contained an invalid provider (port ${port})`
|
|
5862
|
+
);
|
|
5863
|
+
valid = false;
|
|
5864
|
+
break;
|
|
5865
|
+
}
|
|
5866
|
+
}
|
|
5867
|
+
if (valid) {
|
|
5868
|
+
providerReady = body.data.some(
|
|
5869
|
+
(provider) => provider.activation === "enabled"
|
|
5870
|
+
);
|
|
5871
|
+
}
|
|
5872
|
+
}
|
|
5873
|
+
}
|
|
5863
5874
|
} catch (error2) {
|
|
5864
|
-
|
|
5875
|
+
console.error(
|
|
5876
|
+
`[hasAnyConfiguredProvider] GET ${providerPath} failed (port ${port}): ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5877
|
+
);
|
|
5865
5878
|
}
|
|
5879
|
+
if (providerReady === true) return true;
|
|
5880
|
+
if (integrationReady === null || providerReady === null) return null;
|
|
5881
|
+
return false;
|
|
5866
5882
|
}
|
|
5867
|
-
const path = `/api/session/${encodeURIComponent(sessionId)}/prompt`;
|
|
5868
|
-
const response = await client.request(path, {
|
|
5869
|
-
method: "POST",
|
|
5870
|
-
headers: { "Content-Type": "application/json" },
|
|
5871
|
-
body: JSON.stringify({ text, delivery: "queue" })
|
|
5872
|
-
});
|
|
5873
|
-
let body;
|
|
5874
|
-
try {
|
|
5875
|
-
body = await readJson(response);
|
|
5876
|
-
} catch (error2) {
|
|
5877
|
-
throw new OpenCodeV2PromptAckError(
|
|
5878
|
-
`OpenCode V2 prompt response could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5879
|
-
);
|
|
5880
|
-
}
|
|
5881
|
-
const data = isRecord5(body) && "data" in body ? body.data : void 0;
|
|
5882
|
-
if (!isRecord5(data) || typeof data.id !== "string" || data.id.length === 0) {
|
|
5883
|
-
throw new OpenCodeV2PromptAckError("OpenCode V2 prompt response was missing data.id");
|
|
5884
|
-
}
|
|
5885
|
-
return data.id;
|
|
5886
|
-
}
|
|
5887
|
-
async function getV2SessionMessages(client, sessionId) {
|
|
5888
|
-
const path = `/api/session/${encodeURIComponent(sessionId)}/message?order=desc&limit=200`;
|
|
5889
|
-
try {
|
|
5890
|
-
const body = await readJson(await client.request(path));
|
|
5891
|
-
if (!isRecord5(body) || !Array.isArray(body.data) || !isRecord5(body.cursor)) return null;
|
|
5892
|
-
return adaptV2Messages(body);
|
|
5893
|
-
} catch (error2) {
|
|
5894
|
-
console.error(
|
|
5895
|
-
`[getV2SessionMessages] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5896
|
-
);
|
|
5897
|
-
return null;
|
|
5898
|
-
}
|
|
5899
|
-
}
|
|
5900
|
-
async function listV2Forms(client, sessionId) {
|
|
5901
|
-
const path = `/api/session/${encodeURIComponent(sessionId)}/form`;
|
|
5902
|
-
try {
|
|
5903
|
-
return adaptV2FormList(await readJson(await client.request(path)));
|
|
5904
|
-
} catch (error2) {
|
|
5905
|
-
console.error(
|
|
5906
|
-
`[listV2Forms] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5907
|
-
);
|
|
5908
|
-
return null;
|
|
5909
|
-
}
|
|
5910
|
-
}
|
|
5911
|
-
async function listV2Permissions(client, sessionId) {
|
|
5912
|
-
const path = `/api/session/${encodeURIComponent(sessionId)}/permission`;
|
|
5913
|
-
try {
|
|
5914
|
-
return adaptV2PermissionList(await readJson(await client.request(path)));
|
|
5915
|
-
} catch (error2) {
|
|
5916
|
-
console.error(
|
|
5917
|
-
`[listV2Permissions] GET ${path} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
|
|
5918
|
-
);
|
|
5919
|
-
return null;
|
|
5920
|
-
}
|
|
5921
|
-
}
|
|
5922
|
-
async function interruptV2Session(client, sessionId) {
|
|
5923
|
-
await client.request(`/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
|
|
5924
|
-
method: "POST"
|
|
5925
|
-
});
|
|
5926
|
-
}
|
|
5927
|
-
async function getV2ActiveSessions(client) {
|
|
5928
5883
|
try {
|
|
5929
|
-
const
|
|
5930
|
-
if (!
|
|
5931
|
-
|
|
5932
|
-
|
|
5884
|
+
const res = await requestWithClient(port, client, "/config/providers");
|
|
5885
|
+
if (!res.ok) {
|
|
5886
|
+
console.error(
|
|
5887
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
5888
|
+
);
|
|
5889
|
+
return null;
|
|
5890
|
+
}
|
|
5891
|
+
const body = await res.json();
|
|
5892
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
5893
|
+
console.error(
|
|
5894
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
5895
|
+
);
|
|
5896
|
+
return null;
|
|
5897
|
+
}
|
|
5898
|
+
const defaults2 = body.default;
|
|
5899
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
5900
|
+
console.error(
|
|
5901
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
5902
|
+
);
|
|
5903
|
+
return null;
|
|
5904
|
+
}
|
|
5905
|
+
return Object.keys(defaults2).length > 0;
|
|
5906
|
+
} catch (err) {
|
|
5933
5907
|
console.error(
|
|
5934
|
-
`[
|
|
5908
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
5935
5909
|
);
|
|
5936
5910
|
return null;
|
|
5937
5911
|
}
|
|
5938
5912
|
}
|
|
5939
|
-
|
|
5940
|
-
const
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
if (isRecord5(value)) {
|
|
5947
|
-
const data = isRecord5(value.data) ? value.data : void 0;
|
|
5948
|
-
const reason = typeof data?.message === "string" && data.message || typeof value.message === "string" && value.message || typeof value.name === "string" && value.name;
|
|
5949
|
-
if (reason) return reason.replace(/\s+/g, " ").trim().slice(0, 500);
|
|
5950
|
-
}
|
|
5951
|
-
return "OpenCode reported a session error with no details";
|
|
5913
|
+
function sessionErrorReason2(error2) {
|
|
5914
|
+
const record = typeof error2 === "object" && error2 !== null ? error2 : null;
|
|
5915
|
+
const data = record?.data;
|
|
5916
|
+
const dataRecord = typeof data === "object" && data !== null ? data : null;
|
|
5917
|
+
const rawReason = typeof dataRecord?.message === "string" && dataRecord.message || typeof record?.message === "string" && record.message || typeof error2 === "string" && error2 || typeof record?.name === "string" && record.name || "OpenCode reported a session error with no details";
|
|
5918
|
+
const reason = rawReason.replace(/\s+/g, " ").trim().slice(0, 500);
|
|
5919
|
+
return reason || "OpenCode reported a session error with no details";
|
|
5952
5920
|
}
|
|
5953
|
-
function
|
|
5954
|
-
let parsed
|
|
5955
|
-
if (typeof value === "string") {
|
|
5956
|
-
try {
|
|
5957
|
-
parsed = JSON.parse(value);
|
|
5958
|
-
} catch (error2) {
|
|
5959
|
-
void error2;
|
|
5960
|
-
return null;
|
|
5961
|
-
}
|
|
5962
|
-
}
|
|
5963
|
-
if (!isRecord5(parsed)) return null;
|
|
5921
|
+
function parseSessionErrorFrame(data) {
|
|
5922
|
+
let parsed;
|
|
5964
5923
|
try {
|
|
5965
|
-
|
|
5966
|
-
if (establishedShape) return establishedShape;
|
|
5924
|
+
parsed = JSON.parse(data);
|
|
5967
5925
|
} catch (error2) {
|
|
5968
5926
|
void error2;
|
|
5927
|
+
return null;
|
|
5969
5928
|
}
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
return
|
|
5978
|
-
sessionId,
|
|
5979
|
-
reason: sessionErrorReason2(properties.error ?? properties)
|
|
5980
|
-
};
|
|
5929
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
5930
|
+
const parsedRecord = parsed;
|
|
5931
|
+
const payload = parsedRecord.payload;
|
|
5932
|
+
const event = payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : parsedRecord;
|
|
5933
|
+
if (event.type !== "session.error") return null;
|
|
5934
|
+
const properties = event.properties;
|
|
5935
|
+
if (properties === null || typeof properties !== "object" || Array.isArray(properties)) {
|
|
5936
|
+
return null;
|
|
5981
5937
|
}
|
|
5982
|
-
|
|
5938
|
+
const propertiesRecord = properties;
|
|
5939
|
+
const sessionId = propertiesRecord.sessionID;
|
|
5940
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) return null;
|
|
5941
|
+
return {
|
|
5942
|
+
sessionId,
|
|
5943
|
+
reason: sessionErrorReason2(propertiesRecord.error)
|
|
5944
|
+
};
|
|
5983
5945
|
}
|
|
5984
|
-
async function
|
|
5946
|
+
async function readSessionErrorStream(port, options, client) {
|
|
5947
|
+
if (client?.version === "v2") return readV2SessionErrorStream(client, options);
|
|
5985
5948
|
let reader = null;
|
|
5986
5949
|
try {
|
|
5987
|
-
const response = await client
|
|
5950
|
+
const response = await (client?.request("/event", {
|
|
5988
5951
|
headers: { accept: "text/event-stream" },
|
|
5989
5952
|
signal: options.signal
|
|
5990
|
-
})
|
|
5953
|
+
}) ?? fetch(`${opencodeBase(port)}/event`, {
|
|
5954
|
+
headers: { accept: "text/event-stream" },
|
|
5955
|
+
signal: options.signal
|
|
5956
|
+
}));
|
|
5991
5957
|
if (!response.ok || !response.body) {
|
|
5992
5958
|
return { reason: "unavailable", detail: `HTTP ${response.status}` };
|
|
5993
5959
|
}
|
|
@@ -5997,7 +5963,7 @@ async function readV2SessionErrorStream(client, options) {
|
|
|
5997
5963
|
const processLine = (line) => {
|
|
5998
5964
|
const trimmed = line.trimEnd();
|
|
5999
5965
|
if (!trimmed.startsWith("data:")) return;
|
|
6000
|
-
const event =
|
|
5966
|
+
const event = parseSessionErrorFrame(trimmed.slice("data:".length).replace(/^ /, ""));
|
|
6001
5967
|
if (event) options.onSessionError(event);
|
|
6002
5968
|
};
|
|
6003
5969
|
while (true) {
|
|
@@ -6008,16 +5974,61 @@ async function readV2SessionErrorStream(client, options) {
|
|
|
6008
5974
|
buffer = lines.pop() ?? "";
|
|
6009
5975
|
for (const line of lines) processLine(line);
|
|
6010
5976
|
}
|
|
6011
|
-
} catch (
|
|
5977
|
+
} catch (err) {
|
|
6012
5978
|
if (options.signal.aborted) return { reason: "aborted" };
|
|
6013
5979
|
return {
|
|
6014
5980
|
reason: "unavailable",
|
|
6015
|
-
detail:
|
|
5981
|
+
detail: err instanceof Error ? err.message : String(err)
|
|
6016
5982
|
};
|
|
6017
5983
|
} finally {
|
|
6018
5984
|
if (reader) void reader.cancel().catch(() => void 0);
|
|
6019
5985
|
}
|
|
6020
5986
|
}
|
|
5987
|
+
async function disposeAndReloadProviderConfig(port, client) {
|
|
5988
|
+
if (client?.version === "v2") return { outcome: "skipped_v2" };
|
|
5989
|
+
try {
|
|
5990
|
+
const res = await requestWithClient(
|
|
5991
|
+
port,
|
|
5992
|
+
client,
|
|
5993
|
+
"/config",
|
|
5994
|
+
{
|
|
5995
|
+
method: "PATCH",
|
|
5996
|
+
headers: { "Content-Type": "application/json" },
|
|
5997
|
+
body: JSON.stringify({})
|
|
5998
|
+
},
|
|
5999
|
+
{ allowStatuses: ALL_HTTP_STATUSES2 }
|
|
6000
|
+
);
|
|
6001
|
+
if (!res.ok) {
|
|
6002
|
+
console.error(
|
|
6003
|
+
`[disposeAndReloadProviderConfig] PATCH /config returned HTTP ${res.status} (port ${port})`
|
|
6004
|
+
);
|
|
6005
|
+
return { outcome: "failed", status: res.status, detail: null };
|
|
6006
|
+
}
|
|
6007
|
+
return { outcome: "reloaded" };
|
|
6008
|
+
} catch (err) {
|
|
6009
|
+
console.error(
|
|
6010
|
+
`[disposeAndReloadProviderConfig] PATCH /config failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
6011
|
+
);
|
|
6012
|
+
return {
|
|
6013
|
+
outcome: "failed",
|
|
6014
|
+
status: null,
|
|
6015
|
+
detail: err instanceof Error ? err.message : String(err)
|
|
6016
|
+
};
|
|
6017
|
+
}
|
|
6018
|
+
}
|
|
6019
|
+
async function probeOpenCodeRequestReadiness(port, client) {
|
|
6020
|
+
try {
|
|
6021
|
+
const res = await requestWithClient(port, client, "/config", void 0, {
|
|
6022
|
+
allowStatuses: ALL_HTTP_STATUSES2
|
|
6023
|
+
});
|
|
6024
|
+
const body = await res.text();
|
|
6025
|
+
return { ok: res.ok, status: res.status, bodyEmpty: body.trim().length === 0, detail: null };
|
|
6026
|
+
} catch (err) {
|
|
6027
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
6028
|
+
console.error(`[probeOpenCodeRequestReadiness] GET /config failed (port ${port}): ${detail}`);
|
|
6029
|
+
return { ok: false, status: null, bodyEmpty: null, detail };
|
|
6030
|
+
}
|
|
6031
|
+
}
|
|
6021
6032
|
|
|
6022
6033
|
// src/lib/opencode/credential-import-v2.ts
|
|
6023
6034
|
import { readFileSync as readFileSync8 } from "node:fs";
|
|
@@ -6266,7 +6277,7 @@ var INTEGRATION_LIST_RETRY_DELAY_MS = 1e3;
|
|
|
6266
6277
|
function isRecord7(value) {
|
|
6267
6278
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6268
6279
|
}
|
|
6269
|
-
var sleep2 = (milliseconds) => new Promise((
|
|
6280
|
+
var sleep2 = (milliseconds) => new Promise((resolve6) => setTimeout(resolve6, milliseconds));
|
|
6270
6281
|
function emptyResult(unsupported = [], outcome = "completed") {
|
|
6271
6282
|
return { outcome, imported: [], alreadyConnected: [], unsupported, failed: [] };
|
|
6272
6283
|
}
|
|
@@ -6583,7 +6594,7 @@ function parseSynchroniserEnv(stdout) {
|
|
|
6583
6594
|
return values;
|
|
6584
6595
|
}
|
|
6585
6596
|
function runCommand(command, args, options) {
|
|
6586
|
-
return new Promise((
|
|
6597
|
+
return new Promise((resolve6) => {
|
|
6587
6598
|
let child;
|
|
6588
6599
|
let stdout = "";
|
|
6589
6600
|
let stderr = "";
|
|
@@ -6592,7 +6603,7 @@ function runCommand(command, args, options) {
|
|
|
6592
6603
|
if (settled) return;
|
|
6593
6604
|
settled = true;
|
|
6594
6605
|
if (timer) clearTimeout(timer);
|
|
6595
|
-
|
|
6606
|
+
resolve6(result);
|
|
6596
6607
|
};
|
|
6597
6608
|
try {
|
|
6598
6609
|
child = spawn2(command, args, {
|
|
@@ -6600,7 +6611,7 @@ function runCommand(command, args, options) {
|
|
|
6600
6611
|
stdio: ["ignore", "pipe", "pipe"]
|
|
6601
6612
|
});
|
|
6602
6613
|
} catch (error2) {
|
|
6603
|
-
|
|
6614
|
+
resolve6({
|
|
6604
6615
|
code: null,
|
|
6605
6616
|
stdout,
|
|
6606
6617
|
stderr: error2 instanceof Error ? error2.message : String(error2),
|
|
@@ -7127,7 +7138,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
7127
7138
|
if (child.exitCode !== null || child.signalCode !== null) {
|
|
7128
7139
|
return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
|
|
7129
7140
|
}
|
|
7130
|
-
return new Promise((
|
|
7141
|
+
return new Promise((resolve6, reject) => {
|
|
7131
7142
|
let forced = false;
|
|
7132
7143
|
let settled = false;
|
|
7133
7144
|
const timer = setTimeout(() => {
|
|
@@ -7147,7 +7158,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
|
|
|
7147
7158
|
settled = true;
|
|
7148
7159
|
clearTimeout(timer);
|
|
7149
7160
|
child.removeListener("exit", onExit);
|
|
7150
|
-
|
|
7161
|
+
resolve6(result);
|
|
7151
7162
|
};
|
|
7152
7163
|
const fail = (error2) => {
|
|
7153
7164
|
if (settled) return;
|
|
@@ -7744,6 +7755,176 @@ import WebSocket2 from "ws";
|
|
|
7744
7755
|
|
|
7745
7756
|
// src/lib/tunnel/forwarding.ts
|
|
7746
7757
|
import WebSocket from "ws";
|
|
7758
|
+
|
|
7759
|
+
// src/lib/file-read.ts
|
|
7760
|
+
import { constants } from "node:fs";
|
|
7761
|
+
import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
|
|
7762
|
+
import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
|
|
7763
|
+
import { homedir as homedir6 } from "node:os";
|
|
7764
|
+
|
|
7765
|
+
// src/lib/path-validation.ts
|
|
7766
|
+
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute2, join as join12, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
|
|
7767
|
+
import { realpath } from "node:fs/promises";
|
|
7768
|
+
function expandAndValidatePath(requestedPath, homeDir) {
|
|
7769
|
+
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
7770
|
+
return null;
|
|
7771
|
+
}
|
|
7772
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join12(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
7773
|
+
if (expanded.split(/[/\\]/).includes("..") || !isAbsolute2(expanded)) {
|
|
7774
|
+
return null;
|
|
7775
|
+
}
|
|
7776
|
+
const candidate = resolve3(expanded);
|
|
7777
|
+
const name = basename2(candidate);
|
|
7778
|
+
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
7779
|
+
}
|
|
7780
|
+
async function resolveNearestExistingAncestor(directory) {
|
|
7781
|
+
const missingSegments = [];
|
|
7782
|
+
let current = directory;
|
|
7783
|
+
for (; ; ) {
|
|
7784
|
+
try {
|
|
7785
|
+
return { existingAncestor: await realpath(current), missingSegments };
|
|
7786
|
+
} catch (err) {
|
|
7787
|
+
const parent = dirname9(current);
|
|
7788
|
+
if (err.code !== "ENOENT" || parent === current) {
|
|
7789
|
+
throw err;
|
|
7790
|
+
}
|
|
7791
|
+
missingSegments.unshift(basename2(current));
|
|
7792
|
+
current = parent;
|
|
7793
|
+
}
|
|
7794
|
+
}
|
|
7795
|
+
}
|
|
7796
|
+
function isPathContained(directory, target) {
|
|
7797
|
+
const rel = relative2(directory, target);
|
|
7798
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
|
|
7799
|
+
}
|
|
7800
|
+
|
|
7801
|
+
// src/lib/file-read.ts
|
|
7802
|
+
var FILE_MIME_TYPES = {
|
|
7803
|
+
".png": "image/png",
|
|
7804
|
+
".jpg": "image/jpeg",
|
|
7805
|
+
".jpeg": "image/jpeg",
|
|
7806
|
+
".gif": "image/gif",
|
|
7807
|
+
".webp": "image/webp",
|
|
7808
|
+
".mp4": "video/mp4",
|
|
7809
|
+
".mov": "video/quicktime"
|
|
7810
|
+
};
|
|
7811
|
+
async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
|
|
7812
|
+
if (method !== "GET") return refuse(405, "method_not_allowed");
|
|
7813
|
+
if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
|
|
7814
|
+
if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
|
|
7815
|
+
return refuse(400, "invalid_path");
|
|
7816
|
+
}
|
|
7817
|
+
let lexicalRoot;
|
|
7818
|
+
let realRoot;
|
|
7819
|
+
try {
|
|
7820
|
+
lexicalRoot = resolve4(projectRoot);
|
|
7821
|
+
realRoot = await realpath2(lexicalRoot);
|
|
7822
|
+
} catch (err) {
|
|
7823
|
+
log("warn", "tunnel_file_read_root_unavailable", { ...errorFields(err) });
|
|
7824
|
+
return refuse(503, "project_root_unavailable");
|
|
7825
|
+
}
|
|
7826
|
+
const decodedPath = decodeRequestedPath(requestedPath);
|
|
7827
|
+
if (decodedPath.path === null) return refuse(400, "invalid_path", decodedPath.error);
|
|
7828
|
+
const pathValue = decodedPath.path;
|
|
7829
|
+
if (pathValue.split(/[/\\]/).includes("..")) return refuse(400, "invalid_path");
|
|
7830
|
+
const absolutePath = pathValue === "~" || pathValue.startsWith("~/") ? expandAndValidatePath(pathValue, homedir6()) : expandAndValidatePath(
|
|
7831
|
+
isAbsolute3(pathValue) ? pathValue : resolve4(lexicalRoot, pathValue),
|
|
7832
|
+
homedir6()
|
|
7833
|
+
);
|
|
7834
|
+
if (!absolutePath) return refuse(400, "invalid_path");
|
|
7835
|
+
let realTarget;
|
|
7836
|
+
try {
|
|
7837
|
+
realTarget = await realpath2(absolutePath);
|
|
7838
|
+
} catch (err) {
|
|
7839
|
+
if (err.code === "ENOENT") return refuse(404, "not_found");
|
|
7840
|
+
log("warn", "tunnel_file_read_path_resolution_failed", { ...errorFields(err) });
|
|
7841
|
+
return refuse(400, "unresolvable_path");
|
|
7842
|
+
}
|
|
7843
|
+
if (realTarget !== realRoot && !isPathContained(realRoot, realTarget)) {
|
|
7844
|
+
return refuse(
|
|
7845
|
+
403,
|
|
7846
|
+
isPathContained(lexicalRoot, absolutePath) ? "symlink_outside_project" : "path_outside_project"
|
|
7847
|
+
);
|
|
7848
|
+
}
|
|
7849
|
+
let fileStats;
|
|
7850
|
+
try {
|
|
7851
|
+
fileStats = await stat2(realTarget);
|
|
7852
|
+
} catch (err) {
|
|
7853
|
+
if (err.code === "ENOENT") return refuse(404, "not_found");
|
|
7854
|
+
log("warn", "tunnel_file_read_stat_failed", { ...errorFields(err) });
|
|
7855
|
+
return refuse(500, "read_failed");
|
|
7856
|
+
}
|
|
7857
|
+
if (fileStats.isDirectory()) return refuse(409, "is_directory");
|
|
7858
|
+
if (!fileStats.isFile()) return refuse(422, "not_regular_file");
|
|
7859
|
+
if (fileStats.size > TUNNEL_FILE_READ_MAX_BYTES) return refuse(413, "file_too_large");
|
|
7860
|
+
const mimeType = FILE_MIME_TYPES[extname(realTarget).toLowerCase()];
|
|
7861
|
+
if (!mimeType) return refuse(415, "unsupported_type");
|
|
7862
|
+
let handle;
|
|
7863
|
+
try {
|
|
7864
|
+
handle = await openFile(realTarget, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
7865
|
+
const openedStats = await handle.stat();
|
|
7866
|
+
if (!openedStats.isFile()) return refuse(422, "not_regular_file");
|
|
7867
|
+
if (openedStats.size > TUNNEL_FILE_READ_MAX_BYTES) return refuse(413, "file_too_large");
|
|
7868
|
+
const bytes = Buffer.alloc(TUNNEL_FILE_READ_MAX_BYTES + 1);
|
|
7869
|
+
let length = 0;
|
|
7870
|
+
while (length < bytes.length) {
|
|
7871
|
+
const { bytesRead } = await handle.read(bytes, length, bytes.length - length, null);
|
|
7872
|
+
if (bytesRead === 0) break;
|
|
7873
|
+
length += bytesRead;
|
|
7874
|
+
}
|
|
7875
|
+
if (length > TUNNEL_FILE_READ_MAX_BYTES) return refuse(413, "file_too_large");
|
|
7876
|
+
const body = bytes.subarray(0, length);
|
|
7877
|
+
return {
|
|
7878
|
+
status: 200,
|
|
7879
|
+
headers: {
|
|
7880
|
+
"content-type": mimeType,
|
|
7881
|
+
"content-length": String(body.length)
|
|
7882
|
+
},
|
|
7883
|
+
body
|
|
7884
|
+
};
|
|
7885
|
+
} catch (err) {
|
|
7886
|
+
log("error", "tunnel_file_read_failed", { ...errorFields(err) });
|
|
7887
|
+
return refuse(500, "read_failed");
|
|
7888
|
+
} finally {
|
|
7889
|
+
try {
|
|
7890
|
+
await handle?.close();
|
|
7891
|
+
} catch (err) {
|
|
7892
|
+
log("warn", "tunnel_file_read_close_failed", { ...errorFields(err) });
|
|
7893
|
+
}
|
|
7894
|
+
}
|
|
7895
|
+
}
|
|
7896
|
+
function decodeRequestedPath(target) {
|
|
7897
|
+
if (/^file:/i.test(target)) {
|
|
7898
|
+
try {
|
|
7899
|
+
const url = new URL(target);
|
|
7900
|
+
if (url.protocol !== "file:" || url.host) return { path: null };
|
|
7901
|
+
const rawPath = target.slice(target.indexOf(":") + 1).split(/[?#]/, 1)[0];
|
|
7902
|
+
return { path: decodeURIComponent(rawPath) };
|
|
7903
|
+
} catch (error2) {
|
|
7904
|
+
return { path: null, error: error2 };
|
|
7905
|
+
}
|
|
7906
|
+
}
|
|
7907
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(target)) return { path: null };
|
|
7908
|
+
return { path: target };
|
|
7909
|
+
}
|
|
7910
|
+
function refuse(status2, reason, error2) {
|
|
7911
|
+
const body = Buffer.from(JSON.stringify({ reason }));
|
|
7912
|
+
log("warn", "tunnel_file_read_refused", {
|
|
7913
|
+
reason,
|
|
7914
|
+
status: status2,
|
|
7915
|
+
...error2 === void 0 ? {} : errorFields(error2)
|
|
7916
|
+
});
|
|
7917
|
+
return {
|
|
7918
|
+
status: status2,
|
|
7919
|
+
headers: {
|
|
7920
|
+
"content-type": "application/json",
|
|
7921
|
+
"content-length": String(body.length)
|
|
7922
|
+
},
|
|
7923
|
+
body
|
|
7924
|
+
};
|
|
7925
|
+
}
|
|
7926
|
+
|
|
7927
|
+
// src/lib/tunnel/forwarding.ts
|
|
7747
7928
|
var LOOPBACK_HOST = "127.0.0.1";
|
|
7748
7929
|
var FLOW_PAUSE_MAX_MS = 9e4;
|
|
7749
7930
|
var STRIP_REQ = /* @__PURE__ */ new Set([
|
|
@@ -7771,6 +7952,7 @@ var StreamForwarder = class {
|
|
|
7771
7952
|
}
|
|
7772
7953
|
inflight = /* @__PURE__ */ new Map();
|
|
7773
7954
|
binaryFramesSupported = false;
|
|
7955
|
+
projectRoot = null;
|
|
7774
7956
|
/**
|
|
7775
7957
|
* Handle an edge→agent frame. Unknown frame types are ignored.
|
|
7776
7958
|
*/
|
|
@@ -7819,8 +8001,8 @@ var StreamForwarder = class {
|
|
|
7819
8001
|
pauseStream(sid, stream) {
|
|
7820
8002
|
if (!stream.paused) {
|
|
7821
8003
|
stream.paused = true;
|
|
7822
|
-
stream.pausePromise = new Promise((
|
|
7823
|
-
stream.resume =
|
|
8004
|
+
stream.pausePromise = new Promise((resolve6) => {
|
|
8005
|
+
stream.resume = resolve6;
|
|
7824
8006
|
});
|
|
7825
8007
|
}
|
|
7826
8008
|
if (stream.pauseTimer !== null) clearTimeout(stream.pauseTimer);
|
|
@@ -7854,10 +8036,56 @@ var StreamForwarder = class {
|
|
|
7854
8036
|
this.ws.send(JSON.stringify(frame));
|
|
7855
8037
|
}
|
|
7856
8038
|
}
|
|
8039
|
+
async resolveProjectRoot() {
|
|
8040
|
+
if (this.projectRoot !== null) return this.projectRoot;
|
|
8041
|
+
if (!this.options.resolveProjectRoot) return null;
|
|
8042
|
+
try {
|
|
8043
|
+
this.projectRoot = (await this.options.resolveProjectRoot())?.trim() || null;
|
|
8044
|
+
return this.projectRoot;
|
|
8045
|
+
} catch (err) {
|
|
8046
|
+
log("warn", "tunnel_file_read_root_resolution_failed", { ...errorFields(err) });
|
|
8047
|
+
return null;
|
|
8048
|
+
}
|
|
8049
|
+
}
|
|
8050
|
+
async handleFileRead(sid, method, path) {
|
|
8051
|
+
const queryStart = path.indexOf("?");
|
|
8052
|
+
const query = queryStart < 0 ? "" : path.slice(queryStart + 1);
|
|
8053
|
+
const requestedPath = new URLSearchParams(query).get("path");
|
|
8054
|
+
const projectRoot = method === "GET" ? await this.resolveProjectRoot() : null;
|
|
8055
|
+
const result = await readProjectFile(projectRoot, method, requestedPath);
|
|
8056
|
+
try {
|
|
8057
|
+
this.send({ type: "head", sid, status: result.status, headers: result.headers });
|
|
8058
|
+
for (let offset = 0; offset < result.body.length; offset += MAX_FRAME_BYTES) {
|
|
8059
|
+
const chunk = result.body.subarray(offset, offset + MAX_FRAME_BYTES);
|
|
8060
|
+
if (this.binaryFramesSupported && this.ws.readyState === WebSocket.OPEN) {
|
|
8061
|
+
this.ws.send(encodeBinaryBodyFrame(BINARY_FRAME_RES_DATA, sid, chunk));
|
|
8062
|
+
} else {
|
|
8063
|
+
this.send({ type: "res_data", sid, b64: chunk.toString("base64") });
|
|
8064
|
+
}
|
|
8065
|
+
}
|
|
8066
|
+
this.send({ type: "res_end", sid });
|
|
8067
|
+
} catch (err) {
|
|
8068
|
+
log("error", "tunnel_file_read_response_failed", { sid, ...errorFields(err) });
|
|
8069
|
+
}
|
|
8070
|
+
}
|
|
7857
8071
|
async handleOpen(frame) {
|
|
7858
8072
|
const { sid, method, path, headers, has_body } = frame;
|
|
7859
8073
|
const correlationId = headers?.[CORRELATION_ID_HEADER];
|
|
7860
8074
|
const startedAt = Date.now();
|
|
8075
|
+
const pathName = stripQuery(path);
|
|
8076
|
+
if (pathName === TUNNEL_FILE_READ_PATH) {
|
|
8077
|
+
try {
|
|
8078
|
+
await this.handleFileRead(sid, method, path);
|
|
8079
|
+
} catch (err) {
|
|
8080
|
+
log("error", "tunnel_file_read_handler_failed", { sid, ...errorFields(err) });
|
|
8081
|
+
this.send({
|
|
8082
|
+
type: "res_err",
|
|
8083
|
+
sid,
|
|
8084
|
+
message: "The runner could not read the requested file."
|
|
8085
|
+
});
|
|
8086
|
+
}
|
|
8087
|
+
return;
|
|
8088
|
+
}
|
|
7861
8089
|
if (path !== TUNNEL_DRAIN_PING_PATH && path !== TUNNEL_USAGE_REARM_PING_PATH) {
|
|
7862
8090
|
this.callbacks.onOpen?.(sid, method, path);
|
|
7863
8091
|
}
|
|
@@ -7887,12 +8115,12 @@ var StreamForwarder = class {
|
|
|
7887
8115
|
let endBody;
|
|
7888
8116
|
if (has_body) {
|
|
7889
8117
|
const chunks = [];
|
|
7890
|
-
bodyPromise = new Promise((
|
|
8118
|
+
bodyPromise = new Promise((resolve6) => {
|
|
7891
8119
|
pushBody = (buf) => {
|
|
7892
8120
|
chunks.push(buf);
|
|
7893
8121
|
};
|
|
7894
8122
|
endBody = () => {
|
|
7895
|
-
|
|
8123
|
+
resolve6(Buffer.concat(chunks));
|
|
7896
8124
|
};
|
|
7897
8125
|
});
|
|
7898
8126
|
}
|
|
@@ -8059,11 +8287,12 @@ function connectTunnel(options) {
|
|
|
8059
8287
|
onInfo,
|
|
8060
8288
|
onWarning,
|
|
8061
8289
|
onDrainPing,
|
|
8062
|
-
onUsageRearmPing
|
|
8290
|
+
onUsageRearmPing,
|
|
8291
|
+
resolveProjectRoot
|
|
8063
8292
|
} = options;
|
|
8064
8293
|
const tunnelUrl = getTunnelUrlConfig();
|
|
8065
8294
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
8066
|
-
return new Promise((
|
|
8295
|
+
return new Promise((resolve6, reject) => {
|
|
8067
8296
|
const ws = new WebSocket2(url, {
|
|
8068
8297
|
headers: {
|
|
8069
8298
|
Authorization: authHeader,
|
|
@@ -8078,7 +8307,10 @@ function connectTunnel(options) {
|
|
|
8078
8307
|
onDrainPing: () => onDrainPing?.(),
|
|
8079
8308
|
onUsageRearmPing: () => onUsageRearmPing?.()
|
|
8080
8309
|
},
|
|
8081
|
-
{
|
|
8310
|
+
{
|
|
8311
|
+
openCodePassword,
|
|
8312
|
+
...resolveProjectRoot ? { resolveProjectRoot } : {}
|
|
8313
|
+
}
|
|
8082
8314
|
);
|
|
8083
8315
|
const connectionTimeout = setTimeout(() => {
|
|
8084
8316
|
ws.close();
|
|
@@ -8174,7 +8406,7 @@ function connectTunnel(options) {
|
|
|
8174
8406
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
8175
8407
|
relayConnectionId = message.connection_id;
|
|
8176
8408
|
onConnected?.(connectedAgentId, relayConnectionId);
|
|
8177
|
-
|
|
8409
|
+
resolve6({
|
|
8178
8410
|
ws,
|
|
8179
8411
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
8180
8412
|
});
|
|
@@ -8273,6 +8505,7 @@ var RunnerConnection = class _RunnerConnection {
|
|
|
8273
8505
|
authHeader: this.opts.getAuthHeader(),
|
|
8274
8506
|
port: this.opts.port,
|
|
8275
8507
|
openCodePassword: this.opts.openCodePassword,
|
|
8508
|
+
...this.opts.resolveProjectRoot ? { resolveProjectRoot: this.opts.resolveProjectRoot } : {},
|
|
8276
8509
|
onConnected: (agentId, relayConnectionId) => {
|
|
8277
8510
|
const attempt = this.reconnectAttempt + 1;
|
|
8278
8511
|
this.reconnectAttempt = 0;
|
|
@@ -8730,28 +8963,28 @@ function createSessionStoreHealth(options = {}) {
|
|
|
8730
8963
|
}
|
|
8731
8964
|
|
|
8732
8965
|
// src/lib/channels/driver.ts
|
|
8733
|
-
import { homedir as
|
|
8966
|
+
import { homedir as homedir7 } from "node:os";
|
|
8734
8967
|
|
|
8735
8968
|
// src/lib/runner-file-sync.ts
|
|
8736
|
-
import { join as
|
|
8969
|
+
import { join as join14 } from "node:path";
|
|
8737
8970
|
|
|
8738
8971
|
// src/lib/file-push.ts
|
|
8739
8972
|
import { randomUUID } from "node:crypto";
|
|
8740
|
-
import { chmod, mkdir, open as
|
|
8741
|
-
import { basename as
|
|
8973
|
+
import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
|
|
8974
|
+
import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
|
|
8742
8975
|
var FILE_MODE = 384;
|
|
8743
8976
|
var DIRECTORY_MODE = 448;
|
|
8744
8977
|
async function writePushedFile(request3) {
|
|
8745
8978
|
const { requestedPath, content, allowedDirectories, allowedFiles, homeDir } = request3;
|
|
8746
8979
|
const bytes = content.byteLength;
|
|
8747
8980
|
if (allowedDirectories.length === 0 && allowedFiles.length === 0) {
|
|
8748
|
-
return
|
|
8981
|
+
return refuse2("file_sync_disabled", "File sync is not enabled on this runner.", {
|
|
8749
8982
|
path: requestedPath,
|
|
8750
8983
|
bytes
|
|
8751
8984
|
});
|
|
8752
8985
|
}
|
|
8753
8986
|
if (bytes > MAX_FILE_PUSH_BYTES) {
|
|
8754
|
-
return
|
|
8987
|
+
return refuse2(
|
|
8755
8988
|
"file_too_large",
|
|
8756
8989
|
`File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
|
|
8757
8990
|
{
|
|
@@ -8760,30 +8993,30 @@ async function writePushedFile(request3) {
|
|
|
8760
8993
|
}
|
|
8761
8994
|
);
|
|
8762
8995
|
}
|
|
8763
|
-
const candidate =
|
|
8996
|
+
const candidate = expandAndValidatePath(requestedPath, homeDir);
|
|
8764
8997
|
if (candidate === null) {
|
|
8765
|
-
return
|
|
8998
|
+
return refuse2("invalid_path", "The requested path is not a valid absolute file path.", {
|
|
8766
8999
|
path: requestedPath,
|
|
8767
9000
|
bytes
|
|
8768
9001
|
});
|
|
8769
9002
|
}
|
|
8770
9003
|
try {
|
|
8771
9004
|
const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
|
|
8772
|
-
|
|
9005
|
+
dirname10(candidate)
|
|
8773
9006
|
);
|
|
8774
|
-
const realTarget =
|
|
9007
|
+
const realTarget = join13(existingAncestor, ...missingSegments, basename3(candidate));
|
|
8775
9008
|
const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget) ?? await findMatchingAllowedFile(allowedFiles, realTarget);
|
|
8776
9009
|
if (allowedDirectory === null) {
|
|
8777
|
-
return
|
|
9010
|
+
return refuse2("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
8778
9011
|
path: realTarget,
|
|
8779
9012
|
bytes
|
|
8780
9013
|
});
|
|
8781
9014
|
}
|
|
8782
9015
|
if (missingSegments.length > 0) {
|
|
8783
9016
|
await createMissingDirectories(existingAncestor, missingSegments);
|
|
8784
|
-
const realParent = await
|
|
8785
|
-
if (realParent !==
|
|
8786
|
-
return
|
|
9017
|
+
const realParent = await realpath3(dirname10(realTarget));
|
|
9018
|
+
if (realParent !== dirname10(realTarget) || !isPathContained(allowedDirectory, realTarget)) {
|
|
9019
|
+
return refuse2("path_not_allowed", "The runner does not allow writing to that location.", {
|
|
8787
9020
|
path: realTarget,
|
|
8788
9021
|
bytes,
|
|
8789
9022
|
reason: "parent_changed_after_create"
|
|
@@ -8795,7 +9028,7 @@ async function writePushedFile(request3) {
|
|
|
8795
9028
|
return { ok: true, path: realTarget };
|
|
8796
9029
|
} catch (err) {
|
|
8797
9030
|
const errno = err.code ?? "UNKNOWN";
|
|
8798
|
-
return
|
|
9031
|
+
return refuse2("write_failed", `The runner could not write the file (${errno}).`, {
|
|
8799
9032
|
path: candidate,
|
|
8800
9033
|
bytes,
|
|
8801
9034
|
errno,
|
|
@@ -8803,45 +9036,14 @@ async function writePushedFile(request3) {
|
|
|
8803
9036
|
});
|
|
8804
9037
|
}
|
|
8805
9038
|
}
|
|
8806
|
-
function expandAndValidate(requestedPath, homeDir) {
|
|
8807
|
-
if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
|
|
8808
|
-
return null;
|
|
8809
|
-
}
|
|
8810
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join12(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
8811
|
-
if (expanded.split(/[/\\]/).includes("..")) {
|
|
8812
|
-
return null;
|
|
8813
|
-
}
|
|
8814
|
-
if (!isAbsolute2(expanded)) {
|
|
8815
|
-
return null;
|
|
8816
|
-
}
|
|
8817
|
-
const candidate = resolve3(expanded);
|
|
8818
|
-
const name = basename2(candidate);
|
|
8819
|
-
return name === "" || name === "." || name === ".." ? null : candidate;
|
|
8820
|
-
}
|
|
8821
|
-
async function resolveNearestExistingAncestor(directory) {
|
|
8822
|
-
const missingSegments = [];
|
|
8823
|
-
let current = directory;
|
|
8824
|
-
for (; ; ) {
|
|
8825
|
-
try {
|
|
8826
|
-
return { existingAncestor: await realpath(current), missingSegments };
|
|
8827
|
-
} catch (err) {
|
|
8828
|
-
const parent = dirname9(current);
|
|
8829
|
-
if (err.code !== "ENOENT" || parent === current) {
|
|
8830
|
-
throw err;
|
|
8831
|
-
}
|
|
8832
|
-
missingSegments.unshift(basename2(current));
|
|
8833
|
-
current = parent;
|
|
8834
|
-
}
|
|
8835
|
-
}
|
|
8836
|
-
}
|
|
8837
9039
|
async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
8838
9040
|
for (const directory of allowedDirectories) {
|
|
8839
|
-
if (!
|
|
9041
|
+
if (!isAbsolute4(directory)) {
|
|
8840
9042
|
log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
|
|
8841
9043
|
continue;
|
|
8842
9044
|
}
|
|
8843
9045
|
const realDirectory = await realpathCreatingIfMissing(directory);
|
|
8844
|
-
if (realDirectory !== null &&
|
|
9046
|
+
if (realDirectory !== null && isPathContained(realDirectory, realTarget)) {
|
|
8845
9047
|
return realDirectory;
|
|
8846
9048
|
}
|
|
8847
9049
|
}
|
|
@@ -8849,15 +9051,15 @@ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
|
|
|
8849
9051
|
}
|
|
8850
9052
|
async function findMatchingAllowedFile(allowedFiles, realTarget) {
|
|
8851
9053
|
for (const entry of allowedFiles) {
|
|
8852
|
-
if (!
|
|
9054
|
+
if (!isAbsolute4(entry)) {
|
|
8853
9055
|
log("warn", "file_push_allowed_directory_skipped", {
|
|
8854
9056
|
directory: entry,
|
|
8855
9057
|
reason: "not_absolute_file"
|
|
8856
9058
|
});
|
|
8857
9059
|
continue;
|
|
8858
9060
|
}
|
|
8859
|
-
const realParent = await realpathCreatingIfMissing(
|
|
8860
|
-
if (realParent !== null &&
|
|
9061
|
+
const realParent = await realpathCreatingIfMissing(dirname10(entry));
|
|
9062
|
+
if (realParent !== null && join13(realParent, basename3(entry)) === realTarget) {
|
|
8861
9063
|
return realParent;
|
|
8862
9064
|
}
|
|
8863
9065
|
}
|
|
@@ -8865,7 +9067,7 @@ async function findMatchingAllowedFile(allowedFiles, realTarget) {
|
|
|
8865
9067
|
}
|
|
8866
9068
|
async function realpathCreatingIfMissing(directory) {
|
|
8867
9069
|
try {
|
|
8868
|
-
return await
|
|
9070
|
+
return await realpath3(directory);
|
|
8869
9071
|
} catch (err) {
|
|
8870
9072
|
if (err.code !== "ENOENT") {
|
|
8871
9073
|
log("warn", "file_push_allowed_directory_skipped", {
|
|
@@ -8879,7 +9081,7 @@ async function realpathCreatingIfMissing(directory) {
|
|
|
8879
9081
|
try {
|
|
8880
9082
|
await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
8881
9083
|
await chmod(directory, DIRECTORY_MODE);
|
|
8882
|
-
return await
|
|
9084
|
+
return await realpath3(directory);
|
|
8883
9085
|
} catch (err) {
|
|
8884
9086
|
log("warn", "file_push_allowed_directory_skipped", {
|
|
8885
9087
|
directory,
|
|
@@ -8889,23 +9091,19 @@ async function realpathCreatingIfMissing(directory) {
|
|
|
8889
9091
|
return null;
|
|
8890
9092
|
}
|
|
8891
9093
|
}
|
|
8892
|
-
function contains(realDirectory, realTarget) {
|
|
8893
|
-
const rel = relative2(realDirectory, realTarget);
|
|
8894
|
-
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
|
|
8895
|
-
}
|
|
8896
9094
|
async function createMissingDirectories(existingAncestor, missingSegments) {
|
|
8897
9095
|
let current = existingAncestor;
|
|
8898
9096
|
for (const segment of missingSegments) {
|
|
8899
|
-
current =
|
|
9097
|
+
current = join13(current, segment);
|
|
8900
9098
|
await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
|
|
8901
9099
|
await chmod(current, DIRECTORY_MODE);
|
|
8902
9100
|
}
|
|
8903
9101
|
}
|
|
8904
9102
|
async function writeAtomically(realTarget, content) {
|
|
8905
|
-
const temporaryPath =
|
|
9103
|
+
const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
|
|
8906
9104
|
let handle;
|
|
8907
9105
|
try {
|
|
8908
|
-
handle = await
|
|
9106
|
+
handle = await open4(temporaryPath, "wx", FILE_MODE);
|
|
8909
9107
|
await handle.writeFile(content);
|
|
8910
9108
|
await handle.chmod(FILE_MODE);
|
|
8911
9109
|
await handle.close();
|
|
@@ -8931,7 +9129,7 @@ async function discardTemporaryFile(temporaryPath, handle) {
|
|
|
8931
9129
|
}
|
|
8932
9130
|
}
|
|
8933
9131
|
}
|
|
8934
|
-
function
|
|
9132
|
+
function refuse2(code, message, fields) {
|
|
8935
9133
|
log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
|
|
8936
9134
|
return { ok: false, code, message };
|
|
8937
9135
|
}
|
|
@@ -9032,12 +9230,12 @@ var NOT_APPLIED = {
|
|
|
9032
9230
|
opencodeAuthApplied: false
|
|
9033
9231
|
};
|
|
9034
9232
|
function isClaudeCredentialPath(requestedPath, homeDir) {
|
|
9035
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
9036
|
-
return expanded ===
|
|
9233
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join14(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
9234
|
+
return expanded === join14(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
|
|
9037
9235
|
}
|
|
9038
9236
|
function isOpenCodeAuthPath(requestedPath, homeDir) {
|
|
9039
|
-
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ?
|
|
9040
|
-
return expanded ===
|
|
9237
|
+
const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join14(homeDir, requestedPath.slice(2)) : requestedPath;
|
|
9238
|
+
return expanded === join14(homeDir, ...OPENCODE_AUTH_SEGMENTS);
|
|
9041
9239
|
}
|
|
9042
9240
|
async function applyOne(options, file) {
|
|
9043
9241
|
const label = `${file.id.slice(0, 8)} (${file.path})`;
|
|
@@ -9853,7 +10051,7 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9853
10051
|
this.now = config.now ?? (() => Date.now());
|
|
9854
10052
|
this.fileSyncDirectories = config.fileSyncDirectories ?? [];
|
|
9855
10053
|
this.fileSyncExactFiles = config.fileSyncExactFiles ?? [];
|
|
9856
|
-
this.homeDir = config.homeDir ??
|
|
10054
|
+
this.homeDir = config.homeDir ?? homedir7();
|
|
9857
10055
|
this.maxActiveSessions = config.maxActiveSessions;
|
|
9858
10056
|
this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
|
|
9859
10057
|
this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
|
|
@@ -9883,9 +10081,6 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
9883
10081
|
async isSessionOngoing(sessionId) {
|
|
9884
10082
|
return this.isV2 ? isV2SessionOngoing(this.openCodeClient, sessionId) : isSessionOngoing(this.port, sessionId, this.openCodeClient);
|
|
9885
10083
|
}
|
|
9886
|
-
async getOpenCodeDirectory() {
|
|
9887
|
-
return this.isV2 ? getOpenCodeDirectoryV2(this.openCodeClient) : getOpenCodeDirectory(this.port, this.openCodeClient);
|
|
9888
|
-
}
|
|
9889
10084
|
async createOpenCodeSession(directory) {
|
|
9890
10085
|
return this.isV2 ? createV2Session(this.openCodeClient, directory) : createOpenCodeSession(this.port, directory, this.openCodeClient);
|
|
9891
10086
|
}
|
|
@@ -11393,7 +11588,11 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
11393
11588
|
*/
|
|
11394
11589
|
async resolveOpenCodeDirectory() {
|
|
11395
11590
|
if (this.opencodeDirectory !== void 0) return this.opencodeDirectory;
|
|
11396
|
-
this.opencodeDirectory = await
|
|
11591
|
+
this.opencodeDirectory = await resolveOpenCodeDirectoryForVersion(
|
|
11592
|
+
this.openCodeClient.version,
|
|
11593
|
+
this.port,
|
|
11594
|
+
this.openCodeClient
|
|
11595
|
+
);
|
|
11397
11596
|
if (!this.opencodeDirectory) {
|
|
11398
11597
|
this.log({
|
|
11399
11598
|
level: "warn",
|
|
@@ -14241,14 +14440,14 @@ var ChannelDriver = class _ChannelDriver {
|
|
|
14241
14440
|
const fetchChildWithoutBlocking = async (sessionId) => {
|
|
14242
14441
|
const pending = fetchChildMessages(sessionId);
|
|
14243
14442
|
let timer;
|
|
14244
|
-
const timeout = new Promise((
|
|
14443
|
+
const timeout = new Promise((resolve6) => {
|
|
14245
14444
|
timer = setTimeout(() => {
|
|
14246
14445
|
this.log({
|
|
14247
14446
|
level: "warn",
|
|
14248
14447
|
message: `Best-effort subagent session fetch for message ${messageId.slice(0, 8)} and child session ${sessionId.slice(0, 8)} was slow \u2014 omitting invocation telemetry without delaying completion`,
|
|
14249
14448
|
message_id: messageId
|
|
14250
14449
|
});
|
|
14251
|
-
|
|
14450
|
+
resolve6(null);
|
|
14252
14451
|
}, SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS);
|
|
14253
14452
|
});
|
|
14254
14453
|
try {
|
|
@@ -15533,7 +15732,7 @@ function commandError2(result) {
|
|
|
15533
15732
|
return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
|
|
15534
15733
|
}
|
|
15535
15734
|
var runCommand2 = (command, args, opts) => {
|
|
15536
|
-
return new Promise((
|
|
15735
|
+
return new Promise((resolve6) => {
|
|
15537
15736
|
let child;
|
|
15538
15737
|
let stdout = "";
|
|
15539
15738
|
let stderr = "";
|
|
@@ -15543,7 +15742,7 @@ var runCommand2 = (command, args, opts) => {
|
|
|
15543
15742
|
if (settled) return;
|
|
15544
15743
|
settled = true;
|
|
15545
15744
|
if (timer.handle) clearTimeout(timer.handle);
|
|
15546
|
-
|
|
15745
|
+
resolve6(result);
|
|
15547
15746
|
};
|
|
15548
15747
|
try {
|
|
15549
15748
|
child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -15799,7 +15998,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
|
|
|
15799
15998
|
// src/lib/opencode/config-overlay.ts
|
|
15800
15999
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
15801
16000
|
import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
|
|
15802
|
-
import { isAbsolute as
|
|
16001
|
+
import { isAbsolute as isAbsolute5, join as join15, resolve as resolve5 } from "node:path";
|
|
15803
16002
|
function parseConfigContent(content) {
|
|
15804
16003
|
if (!content?.trim()) return {};
|
|
15805
16004
|
const parsed = JSON.parse(content);
|
|
@@ -15828,8 +16027,8 @@ function applyRunnerOpenCodeConfig({
|
|
|
15828
16027
|
log3("runner OpenCode config is not configured; using the baked project config", "debug");
|
|
15829
16028
|
return;
|
|
15830
16029
|
}
|
|
15831
|
-
const source =
|
|
15832
|
-
const target = isFile(
|
|
16030
|
+
const source = isAbsolute5(overlayPath) ? overlayPath : resolve5(cwd, overlayPath);
|
|
16031
|
+
const target = isFile(join15(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
|
|
15833
16032
|
if (!isFile(source)) {
|
|
15834
16033
|
log3(
|
|
15835
16034
|
`RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
|
|
@@ -15837,7 +16036,7 @@ function applyRunnerOpenCodeConfig({
|
|
|
15837
16036
|
);
|
|
15838
16037
|
return;
|
|
15839
16038
|
}
|
|
15840
|
-
copyFileSync(source,
|
|
16039
|
+
copyFileSync(source, join15(cwd, target));
|
|
15841
16040
|
try {
|
|
15842
16041
|
execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
|
|
15843
16042
|
stdio: "ignore"
|
|
@@ -15846,13 +16045,13 @@ function applyRunnerOpenCodeConfig({
|
|
|
15846
16045
|
const detail = error2 instanceof Error ? error2.message : String(error2);
|
|
15847
16046
|
log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
|
|
15848
16047
|
}
|
|
15849
|
-
log3(`Applied runner OpenCode config ${source} to ${
|
|
16048
|
+
log3(`Applied runner OpenCode config ${source} to ${join15(cwd, target)}`);
|
|
15850
16049
|
}
|
|
15851
16050
|
|
|
15852
16051
|
// src/lib/opencode/runtime-provenance.ts
|
|
15853
16052
|
import { readFileSync as readFileSync11, readdirSync } from "node:fs";
|
|
15854
|
-
import { homedir as
|
|
15855
|
-
import { join as
|
|
16053
|
+
import { homedir as homedir8 } from "node:os";
|
|
16054
|
+
import { join as join16 } from "node:path";
|
|
15856
16055
|
var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
|
|
15857
16056
|
var REGISTRY_SPEC = /^[a-z0-9.*+^~<>=|-]+$/i;
|
|
15858
16057
|
function errorKind(error2) {
|
|
@@ -15919,8 +16118,8 @@ function parseJsonc(value) {
|
|
|
15919
16118
|
}
|
|
15920
16119
|
return JSON.parse(output);
|
|
15921
16120
|
}
|
|
15922
|
-
function openCodeCacheRoot(env = process.env, homeDir =
|
|
15923
|
-
return
|
|
16121
|
+
function openCodeCacheRoot(env = process.env, homeDir = homedir8()) {
|
|
16122
|
+
return join16(env.XDG_CACHE_HOME ?? join16(homeDir, ".cache"), "opencode");
|
|
15924
16123
|
}
|
|
15925
16124
|
function readConfiguredPluginSpecs({
|
|
15926
16125
|
cwd = process.cwd(),
|
|
@@ -15929,10 +16128,10 @@ function readConfiguredPluginSpecs({
|
|
|
15929
16128
|
let config;
|
|
15930
16129
|
try {
|
|
15931
16130
|
try {
|
|
15932
|
-
config = parseJsonc(readFileSync11(
|
|
16131
|
+
config = parseJsonc(readFileSync11(join16(cwd, "opencode.jsonc"), "utf8"));
|
|
15933
16132
|
} catch (error2) {
|
|
15934
16133
|
if (!("code" in Object(error2)) || Object(error2).code !== "ENOENT") throw error2;
|
|
15935
|
-
config = parseJsonc(readFileSync11(
|
|
16134
|
+
config = parseJsonc(readFileSync11(join16(cwd, "opencode.json"), "utf8"));
|
|
15936
16135
|
}
|
|
15937
16136
|
} catch (error2) {
|
|
15938
16137
|
log3(`Could not read OpenCode plugin configuration: ${errorKind(error2)}`);
|
|
@@ -15957,10 +16156,10 @@ function readConfiguredPluginSpecs({
|
|
|
15957
16156
|
function resolveInstalledPluginVersions({
|
|
15958
16157
|
cacheRoot,
|
|
15959
16158
|
env = process.env,
|
|
15960
|
-
homeDir =
|
|
16159
|
+
homeDir = homedir8(),
|
|
15961
16160
|
log: log3
|
|
15962
16161
|
}) {
|
|
15963
|
-
const packagesRoot =
|
|
16162
|
+
const packagesRoot = join16(cacheRoot ?? openCodeCacheRoot(env, homeDir), "packages");
|
|
15964
16163
|
let directories;
|
|
15965
16164
|
try {
|
|
15966
16165
|
directories = readdirSync(packagesRoot, { withFileTypes: true });
|
|
@@ -15982,7 +16181,7 @@ function resolveInstalledPluginVersions({
|
|
|
15982
16181
|
try {
|
|
15983
16182
|
const packageJson = JSON.parse(
|
|
15984
16183
|
readFileSync11(
|
|
15985
|
-
|
|
16184
|
+
join16(packagesRoot, directory.name, "node_modules", parsed.name, "package.json"),
|
|
15986
16185
|
"utf8"
|
|
15987
16186
|
)
|
|
15988
16187
|
);
|
|
@@ -16017,14 +16216,14 @@ function errorMessage3(error2) {
|
|
|
16017
16216
|
return error2 instanceof Error ? error2.message : String(error2);
|
|
16018
16217
|
}
|
|
16019
16218
|
function waitForSettlement(promise, timeoutMs) {
|
|
16020
|
-
return new Promise((
|
|
16219
|
+
return new Promise((resolve6) => {
|
|
16021
16220
|
let settled = false;
|
|
16022
16221
|
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
|
|
16023
16222
|
const finish = (value) => {
|
|
16024
16223
|
if (settled) return;
|
|
16025
16224
|
settled = true;
|
|
16026
16225
|
clearTimeout(timer);
|
|
16027
|
-
|
|
16226
|
+
resolve6(value);
|
|
16028
16227
|
};
|
|
16029
16228
|
promise.then(
|
|
16030
16229
|
() => finish(true),
|
|
@@ -16568,8 +16767,8 @@ function resolveFileSyncEntry(entry, homeDir, flagName, labels) {
|
|
|
16568
16767
|
if (trimmed === "") {
|
|
16569
16768
|
throw new Error(`${flagName} requires a ${labels.noun} path (got an empty value)`);
|
|
16570
16769
|
}
|
|
16571
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
16572
|
-
if (!
|
|
16770
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join17(homeDir, trimmed.slice(2)) : trimmed;
|
|
16771
|
+
if (!isAbsolute6(expanded)) {
|
|
16573
16772
|
throw new Error(`${flagName} requires an absolute ${labels.noun} path; got "${entry}"`);
|
|
16574
16773
|
}
|
|
16575
16774
|
const normalized = resolvePath2(expanded);
|
|
@@ -16741,7 +16940,7 @@ function logActivity(state, entry) {
|
|
|
16741
16940
|
}
|
|
16742
16941
|
function reportSessionDbRecovery(state) {
|
|
16743
16942
|
try {
|
|
16744
|
-
const report = drainSessionDbRecoveryReport({ homeDir:
|
|
16943
|
+
const report = drainSessionDbRecoveryReport({ homeDir: homedir9(), env: process.env });
|
|
16745
16944
|
for (const record of report.records) {
|
|
16746
16945
|
const activity = buildSessionDbRecoveryActivity(record);
|
|
16747
16946
|
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
@@ -16822,7 +17021,7 @@ async function importOpenCodeV2CredentialsForState(state) {
|
|
|
16822
17021
|
}
|
|
16823
17022
|
const result = await importOpenCodeV2Credentials({
|
|
16824
17023
|
request: client.request,
|
|
16825
|
-
homeDir:
|
|
17024
|
+
homeDir: homedir9(),
|
|
16826
17025
|
directory,
|
|
16827
17026
|
guard: state.opencodeV2CredentialImportGuard,
|
|
16828
17027
|
log: (message, level = "info") => logActivity(state, { type: "info", level, message })
|
|
@@ -16997,7 +17196,7 @@ async function adoptCredentialGeneration(state, generation, adoption, activeSess
|
|
|
16997
17196
|
return;
|
|
16998
17197
|
}
|
|
16999
17198
|
if (attempts < CREDENTIAL_ADOPTION_PROBE_ATTEMPTS) {
|
|
17000
|
-
await new Promise((
|
|
17199
|
+
await new Promise((resolve6) => setTimeout(resolve6, CREDENTIAL_ADOPTION_PROBE_INTERVAL_MS));
|
|
17001
17200
|
}
|
|
17002
17201
|
}
|
|
17003
17202
|
logCredentialAdoptionActivity(
|
|
@@ -17198,7 +17397,7 @@ async function driveChannels(state, driver) {
|
|
|
17198
17397
|
);
|
|
17199
17398
|
}
|
|
17200
17399
|
}
|
|
17201
|
-
await new Promise((
|
|
17400
|
+
await new Promise((resolve6) => setTimeout(resolve6, CHANNEL_POLL_INTERVAL_MS));
|
|
17202
17401
|
const cycleMs = performance.now() - cycleStartedAtMs;
|
|
17203
17402
|
if (idleThisCycle) idleMs += cycleMs;
|
|
17204
17403
|
if (unreachableThisCycle) unreachableMs += cycleMs;
|
|
@@ -17243,7 +17442,7 @@ function shouldWarnForReclaimSkip(reason) {
|
|
|
17243
17442
|
return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
|
|
17244
17443
|
}
|
|
17245
17444
|
function sessionDbPath() {
|
|
17246
|
-
return
|
|
17445
|
+
return join17(homedir9(), ".local", "share", "opencode", "opencode.db");
|
|
17247
17446
|
}
|
|
17248
17447
|
function logSessionCleanupActivity(state, phase, entry) {
|
|
17249
17448
|
logActivity(state, {
|
|
@@ -17340,7 +17539,7 @@ function logSessionArchiveSummary(state, phase, summary) {
|
|
|
17340
17539
|
}
|
|
17341
17540
|
}
|
|
17342
17541
|
async function drainSessionDeletionReports(state) {
|
|
17343
|
-
const path = sessionDeletionReportPath(
|
|
17542
|
+
const path = sessionDeletionReportPath(homedir9(), process.env);
|
|
17344
17543
|
let delivered = 0;
|
|
17345
17544
|
let failure = null;
|
|
17346
17545
|
try {
|
|
@@ -17580,7 +17779,7 @@ async function runSweep(state, driver, config) {
|
|
|
17580
17779
|
if (deletionRecords.length > 0) {
|
|
17581
17780
|
try {
|
|
17582
17781
|
const dropped = appendSessionDeletionRecords(
|
|
17583
|
-
sessionDeletionReportPath(
|
|
17782
|
+
sessionDeletionReportPath(homedir9(), process.env),
|
|
17584
17783
|
deletionRecords
|
|
17585
17784
|
);
|
|
17586
17785
|
if (dropped > 0) {
|
|
@@ -17698,7 +17897,7 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
17698
17897
|
for (const warning2 of config.warnings) {
|
|
17699
17898
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
17700
17899
|
}
|
|
17701
|
-
const dbBytes = statSessionDbBytes(
|
|
17900
|
+
const dbBytes = statSessionDbBytes(homedir9());
|
|
17702
17901
|
void (async () => {
|
|
17703
17902
|
const reclaimAvailability = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
|
|
17704
17903
|
if (reclaimAvailability !== null) {
|
|
@@ -17797,7 +17996,7 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
|
|
|
17797
17996
|
return null;
|
|
17798
17997
|
}
|
|
17799
17998
|
const bindings = readSessionBindings(
|
|
17800
|
-
sessionBindingLedgerPath(
|
|
17999
|
+
sessionBindingLedgerPath(homedir9(), process.env),
|
|
17801
18000
|
(message) => logSessionArchiveActivity(state, phase, {
|
|
17802
18001
|
type: "info",
|
|
17803
18002
|
level: "warn",
|
|
@@ -17884,8 +18083,8 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
17884
18083
|
let timeout;
|
|
17885
18084
|
const settled = await Promise.race([
|
|
17886
18085
|
previousRun.then(() => true),
|
|
17887
|
-
new Promise((
|
|
17888
|
-
timeout = setTimeout(() =>
|
|
18086
|
+
new Promise((resolve6) => {
|
|
18087
|
+
timeout = setTimeout(() => resolve6(false), budgetMs);
|
|
17889
18088
|
})
|
|
17890
18089
|
]);
|
|
17891
18090
|
if (timeout) clearTimeout(timeout);
|
|
@@ -17920,7 +18119,7 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
|
|
|
17920
18119
|
function scheduleSessionArchive(state) {
|
|
17921
18120
|
const config = state.sessionArchiveConfig;
|
|
17922
18121
|
if (!config.enabled) return;
|
|
17923
|
-
state.sessionArchiveWatermarkPath = sessionArchiveWatermarkPath(
|
|
18122
|
+
state.sessionArchiveWatermarkPath = sessionArchiveWatermarkPath(homedir9(), process.env);
|
|
17924
18123
|
state.sessionArchiveWatermarks = readWatermarks(
|
|
17925
18124
|
state.sessionArchiveWatermarkPath,
|
|
17926
18125
|
(message) => logSessionArchiveActivity(state, "startup", {
|
|
@@ -18124,7 +18323,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
18124
18323
|
});
|
|
18125
18324
|
return;
|
|
18126
18325
|
}
|
|
18127
|
-
const { collect, stop } = createResourceUsageCollector(
|
|
18326
|
+
const { collect, stop } = createResourceUsageCollector(homedir9());
|
|
18128
18327
|
state.stopResourceUsageSampling = stop;
|
|
18129
18328
|
let consecutiveFailures = 0;
|
|
18130
18329
|
const tick = async () => {
|
|
@@ -18362,8 +18561,8 @@ async function beginGracefulShutdown(state, trigger) {
|
|
|
18362
18561
|
return true;
|
|
18363
18562
|
}
|
|
18364
18563
|
);
|
|
18365
|
-
const timedOut = new Promise((
|
|
18366
|
-
timer = setTimeout(() =>
|
|
18564
|
+
const timedOut = new Promise((resolve6) => {
|
|
18565
|
+
timer = setTimeout(() => resolve6(false), telemetryBudgetMs);
|
|
18367
18566
|
});
|
|
18368
18567
|
if (!await Promise.race([flushed, timedOut])) {
|
|
18369
18568
|
log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
|
|
@@ -18381,8 +18580,8 @@ async function run(options) {
|
|
|
18381
18580
|
let fileSyncExactFiles;
|
|
18382
18581
|
try {
|
|
18383
18582
|
logLevel = resolveLogLevel(options);
|
|
18384
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
18385
|
-
fileSyncExactFiles = resolveFileSyncExactFiles(options.enableFileSyncToExactFile,
|
|
18583
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir9());
|
|
18584
|
+
fileSyncExactFiles = resolveFileSyncExactFiles(options.enableFileSyncToExactFile, homedir9());
|
|
18386
18585
|
if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
|
|
18387
18586
|
throw new Error(
|
|
18388
18587
|
"--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
|
|
@@ -18692,7 +18891,7 @@ async function run(options) {
|
|
|
18692
18891
|
state.credentialSync?.arm();
|
|
18693
18892
|
const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
|
|
18694
18893
|
context: {
|
|
18695
|
-
homeDir:
|
|
18894
|
+
homeDir: homedir9(),
|
|
18696
18895
|
cwd: process.cwd(),
|
|
18697
18896
|
microvmId: process.env.MICROVM_ID?.trim(),
|
|
18698
18897
|
euid: process.getuid?.(),
|
|
@@ -18715,7 +18914,7 @@ async function run(options) {
|
|
|
18715
18914
|
dependencyInstallDiagnosticReporter
|
|
18716
18915
|
);
|
|
18717
18916
|
const openCodeLogTail = tailOpenCodeLogFile(
|
|
18718
|
-
resolveOpenCodeLogPath(
|
|
18917
|
+
resolveOpenCodeLogPath(homedir9(), process.env),
|
|
18719
18918
|
openCodeActivityForwarder
|
|
18720
18919
|
);
|
|
18721
18920
|
state.stopOpenCodeLogTail = () => {
|
|
@@ -18973,7 +19172,7 @@ async function run(options) {
|
|
|
18973
19172
|
const provenance = checkSessionDbProvenance({
|
|
18974
19173
|
dbPath: sessionDbPath(),
|
|
18975
19174
|
currentVersion: state.opencodeVersion,
|
|
18976
|
-
homeDir:
|
|
19175
|
+
homeDir: homedir9(),
|
|
18977
19176
|
env: process.env
|
|
18978
19177
|
});
|
|
18979
19178
|
if (provenance.anomaly) {
|
|
@@ -19157,7 +19356,7 @@ async function run(options) {
|
|
|
19157
19356
|
}
|
|
19158
19357
|
const tunnelSpinner = interactive && !state.json ? ora4("Connecting tunnel...").start() : null;
|
|
19159
19358
|
const recordBinding = state.sessionArchiveConfig.enabled ? (conversationId, sessionId) => appendSessionBinding(
|
|
19160
|
-
sessionBindingLedgerPath(
|
|
19359
|
+
sessionBindingLedgerPath(homedir9(), process.env),
|
|
19161
19360
|
{
|
|
19162
19361
|
conversation_id: conversationId,
|
|
19163
19362
|
opencode_session_id: sessionId,
|
|
@@ -19179,7 +19378,7 @@ async function run(options) {
|
|
|
19179
19378
|
// `file_sync_disabled` on the ack, not silently ignored.
|
|
19180
19379
|
fileSyncDirectories,
|
|
19181
19380
|
fileSyncExactFiles,
|
|
19182
|
-
homeDir:
|
|
19381
|
+
homeDir: homedir9(),
|
|
19183
19382
|
maxActiveSessions,
|
|
19184
19383
|
log: (entry) => (
|
|
19185
19384
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
@@ -19199,6 +19398,11 @@ async function run(options) {
|
|
|
19199
19398
|
getAuthHeader: () => state.authHeader,
|
|
19200
19399
|
port: state.port,
|
|
19201
19400
|
openCodePassword: state.opencodePassword,
|
|
19401
|
+
resolveProjectRoot: () => resolveOpenCodeDirectoryForVersion(
|
|
19402
|
+
state.opencodeApiVersion,
|
|
19403
|
+
state.port,
|
|
19404
|
+
state.opencodeClient
|
|
19405
|
+
),
|
|
19202
19406
|
isRunning: () => state.running,
|
|
19203
19407
|
events: {
|
|
19204
19408
|
onConnected: (agentId, isReconnect, transition) => {
|