@evident-ai/cli 3.0.1-dev.dcef26e → 3.0.1-dev.e0d3dd8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/index.js +2063 -144
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
+
import { createRequire } from "module";
|
|
4
5
|
import { Command } from "commander";
|
|
5
6
|
|
|
6
7
|
// src/commands/login.ts
|
|
@@ -284,14 +285,14 @@ function blank() {
|
|
|
284
285
|
console.log();
|
|
285
286
|
}
|
|
286
287
|
function waitForEnter(prompt = "Press Enter to continue...") {
|
|
287
|
-
return new Promise((
|
|
288
|
+
return new Promise((resolve2) => {
|
|
288
289
|
process.stdout.write(chalk.dim(prompt));
|
|
289
290
|
const handler = () => {
|
|
290
291
|
process.stdin.removeListener("data", handler);
|
|
291
292
|
process.stdin.setRawMode?.(false);
|
|
292
293
|
process.stdin.pause();
|
|
293
294
|
console.log();
|
|
294
|
-
|
|
295
|
+
resolve2();
|
|
295
296
|
};
|
|
296
297
|
if (process.stdin.isTTY) {
|
|
297
298
|
process.stdin.setRawMode?.(true);
|
|
@@ -301,7 +302,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
|
|
|
301
302
|
});
|
|
302
303
|
}
|
|
303
304
|
function sleep(ms) {
|
|
304
|
-
return new Promise((
|
|
305
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
305
306
|
}
|
|
306
307
|
|
|
307
308
|
// src/commands/login.ts
|
|
@@ -375,19 +376,19 @@ async function tokenLogin() {
|
|
|
375
376
|
console.log("Visit your Evident dashboard to generate a CLI token.");
|
|
376
377
|
blank();
|
|
377
378
|
process.stdout.write("Paste token: ");
|
|
378
|
-
const token = await new Promise((
|
|
379
|
+
const token = await new Promise((resolve2) => {
|
|
379
380
|
let data = "";
|
|
380
381
|
process.stdin.setEncoding("utf8");
|
|
381
382
|
process.stdin.on("data", (chunk) => {
|
|
382
383
|
data += chunk;
|
|
383
384
|
});
|
|
384
385
|
process.stdin.on("end", () => {
|
|
385
|
-
|
|
386
|
+
resolve2(data.trim());
|
|
386
387
|
});
|
|
387
388
|
if (process.stdin.isTTY) {
|
|
388
389
|
process.stdin.once("data", (chunk) => {
|
|
389
390
|
process.stdin.pause();
|
|
390
|
-
|
|
391
|
+
resolve2(chunk.toString().trim());
|
|
391
392
|
});
|
|
392
393
|
process.stdin.resume();
|
|
393
394
|
}
|
|
@@ -470,12 +471,6 @@ import chalk6 from "chalk";
|
|
|
470
471
|
import ora3 from "ora";
|
|
471
472
|
import { select as select3 } from "@inquirer/prompts";
|
|
472
473
|
|
|
473
|
-
// ../../packages/types/src/opencode/index.ts
|
|
474
|
-
function opencodeMessageIdFor(queuedMessageId) {
|
|
475
|
-
const sanitized = queuedMessageId.replace(/[^a-zA-Z0-9]/g, "_");
|
|
476
|
-
return `msg_${sanitized}`;
|
|
477
|
-
}
|
|
478
|
-
|
|
479
474
|
// ../../packages/types/src/telemetry/index.ts
|
|
480
475
|
var TelemetryEventTypes = {
|
|
481
476
|
// Agent activity events (shown in web UI activity log)
|
|
@@ -514,7 +509,10 @@ function stripQuery(url) {
|
|
|
514
509
|
}
|
|
515
510
|
|
|
516
511
|
// src/lib/telemetry.ts
|
|
517
|
-
var CLI_VERSION = process.env.npm_package_version
|
|
512
|
+
var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
|
|
513
|
+
function getCliVersion() {
|
|
514
|
+
return CLI_VERSION;
|
|
515
|
+
}
|
|
518
516
|
var eventBuffer = [];
|
|
519
517
|
var flushTimeout = null;
|
|
520
518
|
var isShuttingDown = false;
|
|
@@ -708,20 +706,20 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
|
|
|
708
706
|
if (health.healthy) {
|
|
709
707
|
return health;
|
|
710
708
|
}
|
|
711
|
-
await new Promise((
|
|
709
|
+
await new Promise((resolve2) => setTimeout(resolve2, 1e3));
|
|
712
710
|
}
|
|
713
711
|
return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
|
|
714
712
|
}
|
|
715
713
|
|
|
716
714
|
// src/lib/opencode/opencode-version-gate.ts
|
|
717
|
-
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11"];
|
|
718
|
-
function isQueueValidatedVersion(
|
|
719
|
-
if (!
|
|
720
|
-
return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(
|
|
721
|
-
}
|
|
722
|
-
function buildOpenCodeVersionWarning(
|
|
723
|
-
if (isQueueValidatedVersion(
|
|
724
|
-
const detected =
|
|
715
|
+
var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
|
|
716
|
+
function isQueueValidatedVersion(version2) {
|
|
717
|
+
if (!version2) return false;
|
|
718
|
+
return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
|
|
719
|
+
}
|
|
720
|
+
function buildOpenCodeVersionWarning(version2) {
|
|
721
|
+
if (isQueueValidatedVersion(version2)) return null;
|
|
722
|
+
const detected = version2 ? `v${version2}` : "unknown";
|
|
725
723
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
726
724
|
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack/WhatsApp) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
|
|
727
725
|
}
|
|
@@ -1038,7 +1036,11 @@ function roleOf(m) {
|
|
|
1038
1036
|
}
|
|
1039
1037
|
function completedOf(m) {
|
|
1040
1038
|
if (!m || typeof m !== "object") return void 0;
|
|
1041
|
-
return m.info?.time?.completed;
|
|
1039
|
+
return m.info?.time?.completed ?? m.time?.completed;
|
|
1040
|
+
}
|
|
1041
|
+
function createdOf(m) {
|
|
1042
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1043
|
+
return m.info?.time?.created ?? m.time?.created;
|
|
1042
1044
|
}
|
|
1043
1045
|
function idOf(m) {
|
|
1044
1046
|
if (!m || typeof m !== "object") return void 0;
|
|
@@ -1058,6 +1060,102 @@ function finishOf(m) {
|
|
|
1058
1060
|
const infoFinish = m.info?.finish;
|
|
1059
1061
|
return typeof infoFinish === "string" ? infoFinish : void 0;
|
|
1060
1062
|
}
|
|
1063
|
+
function errorOf(m) {
|
|
1064
|
+
if (!m || typeof m !== "object") return void 0;
|
|
1065
|
+
return m.info?.error ?? m.error;
|
|
1066
|
+
}
|
|
1067
|
+
function isAssistantInFlight(m) {
|
|
1068
|
+
if (completedOf(m) == null) return true;
|
|
1069
|
+
return finishOf(m) === "tool-calls";
|
|
1070
|
+
}
|
|
1071
|
+
async function getSessionMessages(port, sessionId) {
|
|
1072
|
+
try {
|
|
1073
|
+
const res = await fetch(`${opencodeBase(port)}/session/${sessionId}/message`);
|
|
1074
|
+
if (!res.ok) return null;
|
|
1075
|
+
const body = await res.json();
|
|
1076
|
+
return Array.isArray(body) ? body : null;
|
|
1077
|
+
} catch {
|
|
1078
|
+
return null;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
function isSessionActivelyGenerating(messages) {
|
|
1082
|
+
if (!messages || messages.length === 0) return false;
|
|
1083
|
+
const last = messages[messages.length - 1];
|
|
1084
|
+
if (roleOf(last) !== "assistant") return false;
|
|
1085
|
+
return completedOf(last) == null;
|
|
1086
|
+
}
|
|
1087
|
+
function sessionLastActivityMs(session) {
|
|
1088
|
+
const candidates = [
|
|
1089
|
+
session.time?.updated,
|
|
1090
|
+
session.time?.created,
|
|
1091
|
+
session.time_updated,
|
|
1092
|
+
session.time_created,
|
|
1093
|
+
session.updated,
|
|
1094
|
+
session.created
|
|
1095
|
+
];
|
|
1096
|
+
for (const c of candidates) {
|
|
1097
|
+
if (typeof c === "number" && Number.isFinite(c)) return c;
|
|
1098
|
+
}
|
|
1099
|
+
return null;
|
|
1100
|
+
}
|
|
1101
|
+
async function listSessions(port) {
|
|
1102
|
+
try {
|
|
1103
|
+
const res = await fetch(`${opencodeBase(port)}/session`);
|
|
1104
|
+
if (!res.ok) return null;
|
|
1105
|
+
const body = await res.json();
|
|
1106
|
+
return Array.isArray(body) ? body : null;
|
|
1107
|
+
} catch {
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
async function deleteSession(port, id) {
|
|
1112
|
+
try {
|
|
1113
|
+
const res = await fetch(`${opencodeBase(port)}/session/${id}`, { method: "DELETE" });
|
|
1114
|
+
return res.status >= 200 && res.status < 300;
|
|
1115
|
+
} catch {
|
|
1116
|
+
return false;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
async function sessionExists(port, id) {
|
|
1120
|
+
try {
|
|
1121
|
+
const res = await fetch(`${opencodeBase(port)}/session/${id}`);
|
|
1122
|
+
if (res.status >= 200 && res.status < 300) return true;
|
|
1123
|
+
if (res.status === 404) return false;
|
|
1124
|
+
return null;
|
|
1125
|
+
} catch {
|
|
1126
|
+
return null;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
async function getSessionStatuses(port) {
|
|
1130
|
+
try {
|
|
1131
|
+
const res = await fetch(`${opencodeBase(port)}/session/status`);
|
|
1132
|
+
if (!res.ok) {
|
|
1133
|
+
console.error(
|
|
1134
|
+
`[getSessionStatuses] GET /session/status returned HTTP ${res.status} (port ${port})`
|
|
1135
|
+
);
|
|
1136
|
+
return null;
|
|
1137
|
+
}
|
|
1138
|
+
const body = await res.json();
|
|
1139
|
+
if (body == null || typeof body !== "object" || Array.isArray(body)) {
|
|
1140
|
+
console.error(
|
|
1141
|
+
`[getSessionStatuses] GET /session/status body was not a plain object (port ${port})`
|
|
1142
|
+
);
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
return body;
|
|
1146
|
+
} catch (err) {
|
|
1147
|
+
console.error(
|
|
1148
|
+
`[getSessionStatuses] GET /session/status failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1149
|
+
);
|
|
1150
|
+
return null;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
async function isSessionOngoing(port, id) {
|
|
1154
|
+
const map = await getSessionStatuses(port);
|
|
1155
|
+
if (map == null) return null;
|
|
1156
|
+
const entry = map[id];
|
|
1157
|
+
return entry != null && entry.type !== "idle";
|
|
1158
|
+
}
|
|
1061
1159
|
async function createOpenCodeSession(port, directory) {
|
|
1062
1160
|
const url = new URL(`${opencodeBase(port)}/session`);
|
|
1063
1161
|
if (directory && directory.trim()) {
|
|
@@ -1075,10 +1173,113 @@ async function createOpenCodeSession(port, directory) {
|
|
|
1075
1173
|
const data = await response.json();
|
|
1076
1174
|
return data.id;
|
|
1077
1175
|
}
|
|
1078
|
-
async function
|
|
1176
|
+
async function getModelAttachmentCapability(port, model) {
|
|
1177
|
+
try {
|
|
1178
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1179
|
+
if (!res.ok) {
|
|
1180
|
+
console.error(
|
|
1181
|
+
`[getModelAttachmentCapability] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1182
|
+
);
|
|
1183
|
+
return null;
|
|
1184
|
+
}
|
|
1185
|
+
const body = await res.json();
|
|
1186
|
+
const providers = Array.isArray(body?.providers) ? body.providers : null;
|
|
1187
|
+
if (!providers) {
|
|
1188
|
+
console.error(
|
|
1189
|
+
`[getModelAttachmentCapability] GET /config/providers body had no providers array (port ${port})`
|
|
1190
|
+
);
|
|
1191
|
+
return null;
|
|
1192
|
+
}
|
|
1193
|
+
const slash = model ? model.indexOf("/") : -1;
|
|
1194
|
+
const providerId = slash > 0 ? model.slice(0, slash) : void 0;
|
|
1195
|
+
let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
|
|
1196
|
+
const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
|
|
1197
|
+
let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
|
|
1198
|
+
if (!provider && !providerId) {
|
|
1199
|
+
const defaultProviderIds = defaults2 ? Object.keys(defaults2) : [];
|
|
1200
|
+
if (defaultProviderIds.length === 1) {
|
|
1201
|
+
provider = providers.find((p) => p?.id === defaultProviderIds[0]);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (!provider || !provider.models) return null;
|
|
1205
|
+
if (!modelId && defaults2 && typeof provider.id === "string") {
|
|
1206
|
+
const def = defaults2[provider.id];
|
|
1207
|
+
if (typeof def === "string") modelId = def;
|
|
1208
|
+
}
|
|
1209
|
+
if (!modelId) {
|
|
1210
|
+
if (providerId) {
|
|
1211
|
+
const keys = Object.keys(provider.models);
|
|
1212
|
+
if (keys.length === 1) modelId = keys[0];
|
|
1213
|
+
}
|
|
1214
|
+
if (!modelId) return null;
|
|
1215
|
+
}
|
|
1216
|
+
const entry = provider.models[modelId];
|
|
1217
|
+
if (!entry || typeof entry !== "object") return null;
|
|
1218
|
+
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1219
|
+
} catch (err) {
|
|
1220
|
+
console.error(
|
|
1221
|
+
`[getModelAttachmentCapability] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1222
|
+
);
|
|
1223
|
+
return null;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
async function buildFileParts(attachments, capable) {
|
|
1227
|
+
const outcomes = [];
|
|
1228
|
+
const parts = [];
|
|
1229
|
+
const capabilityUnknown = capable === null;
|
|
1230
|
+
if (capable !== true) {
|
|
1231
|
+
for (const a of attachments.inputs) {
|
|
1232
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "skipped" });
|
|
1233
|
+
}
|
|
1234
|
+
return { parts, outcomes, capabilityUnknown };
|
|
1235
|
+
}
|
|
1236
|
+
for (const a of attachments.inputs) {
|
|
1237
|
+
let dataUrl = null;
|
|
1238
|
+
try {
|
|
1239
|
+
dataUrl = await attachments.fetchDataUrl(a.index);
|
|
1240
|
+
} catch (err) {
|
|
1241
|
+
console.error(
|
|
1242
|
+
`[buildFileParts] attachment ${a.index} (${a.mime}) fetch threw \u2014 omitting: ${err instanceof Error ? err.message : String(err)}`
|
|
1243
|
+
);
|
|
1244
|
+
dataUrl = null;
|
|
1245
|
+
}
|
|
1246
|
+
if (dataUrl == null) {
|
|
1247
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1248
|
+
continue;
|
|
1249
|
+
}
|
|
1250
|
+
parts.push({
|
|
1251
|
+
type: "file",
|
|
1252
|
+
mime: a.mime,
|
|
1253
|
+
url: dataUrl,
|
|
1254
|
+
...a.filename ? { filename: a.filename } : {}
|
|
1255
|
+
});
|
|
1256
|
+
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "sent" });
|
|
1257
|
+
}
|
|
1258
|
+
return { parts, outcomes, capabilityUnknown };
|
|
1259
|
+
}
|
|
1260
|
+
function messageText(m) {
|
|
1261
|
+
if (!m || !Array.isArray(m.parts)) return "";
|
|
1262
|
+
return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
|
|
1263
|
+
}
|
|
1264
|
+
async function sendPromptAsync(port, sessionId, content, options, attachments) {
|
|
1265
|
+
const before = await getSessionMessages(port, sessionId);
|
|
1266
|
+
const knownUserIds = new Set(
|
|
1267
|
+
(before ?? []).filter((m) => roleOf(m) === "user").map((m) => idOf(m)).filter((id) => typeof id === "string")
|
|
1268
|
+
);
|
|
1269
|
+
const parts = [{ type: "text", text: content }];
|
|
1270
|
+
let pendingOutcomes = null;
|
|
1271
|
+
if (attachments && attachments.inputs.length > 0) {
|
|
1272
|
+
const capable = await getModelAttachmentCapability(port, options?.model);
|
|
1273
|
+
const {
|
|
1274
|
+
parts: fileParts,
|
|
1275
|
+
outcomes,
|
|
1276
|
+
capabilityUnknown
|
|
1277
|
+
} = await buildFileParts(attachments, capable);
|
|
1278
|
+
parts.push(...fileParts);
|
|
1279
|
+
if (attachments.onOutcomes) pendingOutcomes = { outcomes, capabilityUnknown };
|
|
1280
|
+
}
|
|
1079
1281
|
const body = {
|
|
1080
|
-
|
|
1081
|
-
parts: [{ type: "text", text: content }]
|
|
1282
|
+
parts
|
|
1082
1283
|
};
|
|
1083
1284
|
if (options?.agent) {
|
|
1084
1285
|
body.agent = options.agent;
|
|
@@ -1101,6 +1302,32 @@ async function sendPromptAsync(port, sessionId, content, options, messageId) {
|
|
|
1101
1302
|
const text = await res.text().catch(() => "");
|
|
1102
1303
|
throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
|
|
1103
1304
|
}
|
|
1305
|
+
const READ_BACK_ATTEMPTS = 5;
|
|
1306
|
+
const READ_BACK_DELAY_MS = 150;
|
|
1307
|
+
for (let attempt = 0; attempt < READ_BACK_ATTEMPTS; attempt++) {
|
|
1308
|
+
const after = await getSessionMessages(port, sessionId);
|
|
1309
|
+
if (after) {
|
|
1310
|
+
let best = null;
|
|
1311
|
+
for (const m of after) {
|
|
1312
|
+
if (roleOf(m) !== "user") continue;
|
|
1313
|
+
const id = idOf(m);
|
|
1314
|
+
if (typeof id !== "string" || knownUserIds.has(id)) continue;
|
|
1315
|
+
if (messageText(m) !== content) continue;
|
|
1316
|
+
const created = createdOf(m) ?? 0;
|
|
1317
|
+
if (best === null || created > best.created) {
|
|
1318
|
+
best = { id, created };
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
if (best) {
|
|
1322
|
+
if (pendingOutcomes && attachments?.onOutcomes) attachments.onOutcomes(pendingOutcomes);
|
|
1323
|
+
return best.id;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (attempt < READ_BACK_ATTEMPTS - 1) {
|
|
1327
|
+
await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
return null;
|
|
1104
1331
|
}
|
|
1105
1332
|
function findAssistantReplyAfter(messages, userMessageId) {
|
|
1106
1333
|
if (!messages || messages.length === 0) return null;
|
|
@@ -1117,19 +1344,31 @@ function findAssistantReplyAfter(messages, userMessageId) {
|
|
|
1117
1344
|
}
|
|
1118
1345
|
function findLastAssistantReplyFor(messages, userMessageId) {
|
|
1119
1346
|
if (!messages || messages.length === 0) return null;
|
|
1347
|
+
let lastCorrelated = null;
|
|
1348
|
+
let lastNonErrored = null;
|
|
1120
1349
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1121
1350
|
const m = messages[i];
|
|
1122
|
-
if (roleOf(m)
|
|
1351
|
+
if (roleOf(m) !== "assistant" || parentIdOf(m) !== userMessageId) continue;
|
|
1352
|
+
if (lastCorrelated === null) lastCorrelated = m;
|
|
1353
|
+
if (errorOf(m) == null) {
|
|
1354
|
+
lastNonErrored = m;
|
|
1355
|
+
break;
|
|
1356
|
+
}
|
|
1123
1357
|
}
|
|
1358
|
+
if (lastCorrelated) return lastNonErrored ?? lastCorrelated;
|
|
1124
1359
|
const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
|
|
1125
1360
|
if (userIndex === -1) return null;
|
|
1126
1361
|
let last = null;
|
|
1362
|
+
let lastOk = null;
|
|
1127
1363
|
for (let i = userIndex + 1; i < messages.length; i++) {
|
|
1128
1364
|
const role = roleOf(messages[i]);
|
|
1129
1365
|
if (role === "user") break;
|
|
1130
|
-
if (role === "assistant")
|
|
1366
|
+
if (role === "assistant") {
|
|
1367
|
+
last = messages[i];
|
|
1368
|
+
if (errorOf(messages[i]) == null) lastOk = messages[i];
|
|
1369
|
+
}
|
|
1131
1370
|
}
|
|
1132
|
-
return last;
|
|
1371
|
+
return lastOk ?? last;
|
|
1133
1372
|
}
|
|
1134
1373
|
function messageRunState(messages, userMessageId) {
|
|
1135
1374
|
if (!messages || messages.length === 0) return "unknown";
|
|
@@ -1139,12 +1378,136 @@ function messageRunState(messages, userMessageId) {
|
|
|
1139
1378
|
if (!reply) return "unknown";
|
|
1140
1379
|
}
|
|
1141
1380
|
if (!reply) return "queued";
|
|
1142
|
-
if (
|
|
1143
|
-
|
|
1144
|
-
return "done";
|
|
1381
|
+
if (isAssistantInFlight(reply)) return "running";
|
|
1382
|
+
return errorOf(reply) != null ? "failed" : "done";
|
|
1145
1383
|
}
|
|
1146
|
-
function
|
|
1147
|
-
|
|
1384
|
+
function isPreamblePinnedRunning(messages, userMessageId) {
|
|
1385
|
+
if (messageRunState(messages, userMessageId) !== "running") return false;
|
|
1386
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1387
|
+
return completedOf(reply) != null && finishOf(reply) === "tool-calls";
|
|
1388
|
+
}
|
|
1389
|
+
function messageError(messages, userMessageId) {
|
|
1390
|
+
const reply = findLastAssistantReplyFor(messages, userMessageId);
|
|
1391
|
+
const error2 = errorOf(reply);
|
|
1392
|
+
if (error2 == null) return null;
|
|
1393
|
+
if (typeof error2 === "string") return error2;
|
|
1394
|
+
if (typeof error2 === "object") {
|
|
1395
|
+
const e = error2;
|
|
1396
|
+
const dataMessage = e.data?.message;
|
|
1397
|
+
if (typeof dataMessage === "string") return dataMessage;
|
|
1398
|
+
if (typeof e.message === "string") return e.message;
|
|
1399
|
+
}
|
|
1400
|
+
return "The agent run failed.";
|
|
1401
|
+
}
|
|
1402
|
+
function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
1403
|
+
if (!messages || messages.length === 0) return false;
|
|
1404
|
+
return messages.some(
|
|
1405
|
+
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
// src/lib/opencode/session-cleanup.ts
|
|
1410
|
+
var DURATION_UNIT_MS = {
|
|
1411
|
+
s: 1e3,
|
|
1412
|
+
m: 60 * 1e3,
|
|
1413
|
+
h: 60 * 60 * 1e3,
|
|
1414
|
+
d: 24 * 60 * 60 * 1e3
|
|
1415
|
+
};
|
|
1416
|
+
function parseDurationMs(input) {
|
|
1417
|
+
const trimmed = input.trim();
|
|
1418
|
+
const match = /^(\d+)([smhd])$/.exec(trimmed);
|
|
1419
|
+
if (!match) {
|
|
1420
|
+
throw new Error(
|
|
1421
|
+
`Invalid duration "${input}": expected <number><unit> where unit is one of s, m, h, d (e.g. "7d", "24h", "30m", "90s").`
|
|
1422
|
+
);
|
|
1423
|
+
}
|
|
1424
|
+
const value = Number(match[1]);
|
|
1425
|
+
if (value <= 0) {
|
|
1426
|
+
throw new Error(`Invalid duration "${input}": must be a positive value.`);
|
|
1427
|
+
}
|
|
1428
|
+
return value * DURATION_UNIT_MS[match[2]];
|
|
1429
|
+
}
|
|
1430
|
+
function selectSessionsToDelete(sessions, opts) {
|
|
1431
|
+
const { maxAgeMs, maxCount, nowMs, protectedIds } = opts;
|
|
1432
|
+
if (maxAgeMs === void 0 && maxCount === void 0) return [];
|
|
1433
|
+
const ageEligible = (s) => {
|
|
1434
|
+
if (maxAgeMs === void 0) return false;
|
|
1435
|
+
if (s.lastActivityMs === null) return true;
|
|
1436
|
+
return nowMs - s.lastActivityMs > maxAgeMs;
|
|
1437
|
+
};
|
|
1438
|
+
const countEligibleIds = /* @__PURE__ */ new Set();
|
|
1439
|
+
if (maxCount !== void 0) {
|
|
1440
|
+
const byActivityDesc = [...sessions].sort(
|
|
1441
|
+
(a, b) => (b.lastActivityMs ?? -Infinity) - (a.lastActivityMs ?? -Infinity)
|
|
1442
|
+
);
|
|
1443
|
+
for (const s of byActivityDesc.slice(maxCount)) {
|
|
1444
|
+
countEligibleIds.add(s.id);
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
const toDelete = [];
|
|
1448
|
+
for (const s of sessions) {
|
|
1449
|
+
if (protectedIds.has(s.id)) continue;
|
|
1450
|
+
if (ageEligible(s) || countEligibleIds.has(s.id)) {
|
|
1451
|
+
toDelete.push(s.id);
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
return toDelete;
|
|
1455
|
+
}
|
|
1456
|
+
var DEFAULT_INTERVAL = "1h";
|
|
1457
|
+
function resolve(flag, envValue, fallback) {
|
|
1458
|
+
return flag ?? envValue ?? fallback;
|
|
1459
|
+
}
|
|
1460
|
+
function parseMaxCount(input) {
|
|
1461
|
+
const trimmed = input.trim();
|
|
1462
|
+
if (!/^\d+$/.test(trimmed)) {
|
|
1463
|
+
throw new Error(`Invalid max-count "${input}": expected a positive integer.`);
|
|
1464
|
+
}
|
|
1465
|
+
const value = Number(trimmed);
|
|
1466
|
+
if (value <= 0) {
|
|
1467
|
+
throw new Error(`Invalid max-count "${input}": must be greater than 0.`);
|
|
1468
|
+
}
|
|
1469
|
+
return value;
|
|
1470
|
+
}
|
|
1471
|
+
function resolveSessionCleanupConfig(flags, env = process.env) {
|
|
1472
|
+
const warnings = [];
|
|
1473
|
+
const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
|
|
1474
|
+
const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
|
|
1475
|
+
const intervalRaw = resolve(
|
|
1476
|
+
flags.interval,
|
|
1477
|
+
env.EVIDENT_SESSION_CLEANUP_INTERVAL,
|
|
1478
|
+
DEFAULT_INTERVAL
|
|
1479
|
+
);
|
|
1480
|
+
let maxAgeMs;
|
|
1481
|
+
if (maxAgeRaw !== void 0) {
|
|
1482
|
+
try {
|
|
1483
|
+
maxAgeMs = parseDurationMs(maxAgeRaw);
|
|
1484
|
+
} catch (err) {
|
|
1485
|
+
warnings.push(
|
|
1486
|
+
`Ignoring invalid --session-cleanup-max-age: ${err instanceof Error ? err.message : String(err)}`
|
|
1487
|
+
);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
let maxCount;
|
|
1491
|
+
if (maxCountRaw !== void 0) {
|
|
1492
|
+
try {
|
|
1493
|
+
maxCount = parseMaxCount(maxCountRaw);
|
|
1494
|
+
} catch (err) {
|
|
1495
|
+
warnings.push(
|
|
1496
|
+
`Ignoring invalid --session-cleanup-max-count: ${err instanceof Error ? err.message : String(err)}`
|
|
1497
|
+
);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
let intervalMs;
|
|
1501
|
+
try {
|
|
1502
|
+
intervalMs = parseDurationMs(intervalRaw ?? DEFAULT_INTERVAL);
|
|
1503
|
+
} catch (err) {
|
|
1504
|
+
warnings.push(
|
|
1505
|
+
`Ignoring invalid --session-cleanup-interval, using default ${DEFAULT_INTERVAL}: ${err instanceof Error ? err.message : String(err)}`
|
|
1506
|
+
);
|
|
1507
|
+
intervalMs = parseDurationMs(DEFAULT_INTERVAL);
|
|
1508
|
+
}
|
|
1509
|
+
const enabled = maxAgeMs !== void 0 || maxCount !== void 0;
|
|
1510
|
+
return { enabled, maxAgeMs, maxCount, intervalMs, warnings };
|
|
1148
1511
|
}
|
|
1149
1512
|
|
|
1150
1513
|
// src/lib/tunnel/connection.ts
|
|
@@ -1223,24 +1586,26 @@ var StreamForwarder = class {
|
|
|
1223
1586
|
this.send({ type: "res_end", sid });
|
|
1224
1587
|
return;
|
|
1225
1588
|
}
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1589
|
+
if (process.env.DEBUG) {
|
|
1590
|
+
log("debug", "agent_request", {
|
|
1591
|
+
correlation_id: correlationId,
|
|
1592
|
+
sid,
|
|
1593
|
+
method,
|
|
1594
|
+
path: stripQuery(path)
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1232
1597
|
const ac = new AbortController();
|
|
1233
1598
|
let bodyPromise;
|
|
1234
1599
|
let pushBody;
|
|
1235
1600
|
let endBody;
|
|
1236
1601
|
if (has_body) {
|
|
1237
1602
|
const chunks = [];
|
|
1238
|
-
bodyPromise = new Promise((
|
|
1603
|
+
bodyPromise = new Promise((resolve2) => {
|
|
1239
1604
|
pushBody = (buf) => {
|
|
1240
1605
|
chunks.push(buf);
|
|
1241
1606
|
};
|
|
1242
1607
|
endBody = () => {
|
|
1243
|
-
|
|
1608
|
+
resolve2(Buffer.concat(chunks));
|
|
1244
1609
|
};
|
|
1245
1610
|
});
|
|
1246
1611
|
}
|
|
@@ -1275,12 +1640,14 @@ var StreamForwarder = class {
|
|
|
1275
1640
|
if (!STRIP_RES.has(key.toLowerCase())) resHeaders[key] = value;
|
|
1276
1641
|
});
|
|
1277
1642
|
this.send({ type: "head", sid, status: upstream.status, headers: resHeaders });
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1643
|
+
if (process.env.DEBUG) {
|
|
1644
|
+
log("debug", "agent_response", {
|
|
1645
|
+
correlation_id: correlationId,
|
|
1646
|
+
sid,
|
|
1647
|
+
status: upstream.status,
|
|
1648
|
+
duration_ms: Date.now() - startedAt
|
|
1649
|
+
});
|
|
1650
|
+
}
|
|
1284
1651
|
this.callbacks.onHead?.(sid, upstream.status);
|
|
1285
1652
|
try {
|
|
1286
1653
|
if (upstream.body) {
|
|
@@ -1356,7 +1723,7 @@ function connectTunnel(options) {
|
|
|
1356
1723
|
} = options;
|
|
1357
1724
|
const tunnelUrl = getTunnelUrlConfig();
|
|
1358
1725
|
const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
|
|
1359
|
-
return new Promise((
|
|
1726
|
+
return new Promise((resolve2, reject) => {
|
|
1360
1727
|
const ws = new WebSocket2(url, {
|
|
1361
1728
|
headers: {
|
|
1362
1729
|
Authorization: authHeader
|
|
@@ -1421,7 +1788,7 @@ function connectTunnel(options) {
|
|
|
1421
1788
|
clearTimeout(connectionTimeout);
|
|
1422
1789
|
const connectedAgentId = message.agent_id ?? agentId;
|
|
1423
1790
|
onConnected?.(connectedAgentId);
|
|
1424
|
-
|
|
1791
|
+
resolve2({
|
|
1425
1792
|
ws,
|
|
1426
1793
|
close: () => ws.close(1e3, "CLI shutdown")
|
|
1427
1794
|
});
|
|
@@ -1543,6 +1910,17 @@ function messageIdOf(m) {
|
|
|
1543
1910
|
const infoId = m.info?.id;
|
|
1544
1911
|
return typeof infoId === "string" ? infoId : void 0;
|
|
1545
1912
|
}
|
|
1913
|
+
function cleanImageMime(contentType) {
|
|
1914
|
+
if (!contentType) return null;
|
|
1915
|
+
const media = contentType.split(";")[0].trim().toLowerCase();
|
|
1916
|
+
return /^image\/[a-z0-9.+-]+$/.test(media) ? media : null;
|
|
1917
|
+
}
|
|
1918
|
+
var LOG_LEVELS = {
|
|
1919
|
+
debug: 0,
|
|
1920
|
+
info: 1,
|
|
1921
|
+
warn: 2,
|
|
1922
|
+
error: 3
|
|
1923
|
+
};
|
|
1546
1924
|
var DEFAULT_RETRY_POLICY = {
|
|
1547
1925
|
maxAttempts: 6,
|
|
1548
1926
|
baseDelayMs: 500,
|
|
@@ -1550,7 +1928,10 @@ var DEFAULT_RETRY_POLICY = {
|
|
|
1550
1928
|
};
|
|
1551
1929
|
var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
|
|
1552
1930
|
var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
|
|
1553
|
-
var
|
|
1931
|
+
var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
1932
|
+
var HEARTBEAT_MS = 6e4;
|
|
1933
|
+
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
1934
|
+
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
1554
1935
|
var ChannelAuthError = class extends Error {
|
|
1555
1936
|
constructor(message) {
|
|
1556
1937
|
super(message);
|
|
@@ -1585,10 +1966,18 @@ var ChannelDriver = class {
|
|
|
1585
1966
|
sleep;
|
|
1586
1967
|
pausedPollIntervalMs;
|
|
1587
1968
|
pausedMaxWaitMs;
|
|
1588
|
-
|
|
1969
|
+
stuckQueuedMs;
|
|
1589
1970
|
now;
|
|
1590
1971
|
/** Cache of conversationId → opencode sessionId. */
|
|
1591
1972
|
sessions = /* @__PURE__ */ new Map();
|
|
1973
|
+
/**
|
|
1974
|
+
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
|
+
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
1976
|
+
* "the one new user row" — which is only unambiguous if no OTHER dispatch into
|
|
1977
|
+
* the SAME session interleaves its snapshot→POST→read-back. This map chains each
|
|
1978
|
+
* session's dispatches so they run serially; distinct sessions stay concurrent.
|
|
1979
|
+
*/
|
|
1980
|
+
sessionDispatchLocks = /* @__PURE__ */ new Map();
|
|
1592
1981
|
/**
|
|
1593
1982
|
* Per-SESSION watchers (WI-3), keyed by opencode sessionId. Single-flight per
|
|
1594
1983
|
* session: one polling loop services all of that session's in-flight messages.
|
|
@@ -1605,6 +1994,72 @@ var ChannelDriver = class {
|
|
|
1605
1994
|
* a steady-state-poll re-dispatch will not double-run the message.
|
|
1606
1995
|
*/
|
|
1607
1996
|
dispatched = /* @__PURE__ */ new Set();
|
|
1997
|
+
/**
|
|
1998
|
+
* Re-adopted (ADR-0046) Evident message ids currently tracked by a watcher.
|
|
1999
|
+
* Used only to distinguish a RE-ADOPTED give-up from a normal-dispatch give-up
|
|
2000
|
+
* so the former can be parked in `dontRedispatch` (Bug 2). A row is added when
|
|
2001
|
+
* it is re-adopted and removed when its watcher settles or it is observed off
|
|
2002
|
+
* the processing list.
|
|
2003
|
+
*/
|
|
2004
|
+
readopted = /* @__PURE__ */ new Set();
|
|
2005
|
+
/**
|
|
2006
|
+
* "Don't re-DISPATCH / re-attach this orphan again" (Bug 2/5). Set when a
|
|
2007
|
+
* re-adopted running/orphan row's watcher hit its `processed_at`-anchored
|
|
2008
|
+
* deadline (or an orphan whose window already elapsed): the still-`processing`
|
|
2009
|
+
* server row would otherwise be re-adopted (and re-dispatched) on EVERY ~2s
|
|
2010
|
+
* drain until the 15-min cron resets it — spamming new turns.
|
|
2011
|
+
*
|
|
2012
|
+
* CRITICAL (Bugbot #202): this suppresses ONLY the dispatch/re-attach paths, it
|
|
2013
|
+
* does NOT suppress DONE delivery. A row parked here whose reply later COMPLETES
|
|
2014
|
+
* in opencode must still be delivered via `markDone` on the next drain — so
|
|
2015
|
+
* `readoptOne` computes `state` FIRST and this set is checked only on the
|
|
2016
|
+
* non-done path. It is cleared once the row leaves the processing list (cron
|
|
2017
|
+
* reset → it drains normally as `pending`), so it can never leak.
|
|
2018
|
+
*/
|
|
2019
|
+
dontRedispatch = /* @__PURE__ */ new Set();
|
|
2020
|
+
/**
|
|
2021
|
+
* "markDone for this row is TERMINALLY undeliverable" (Bug 4). Set ONLY when a
|
|
2022
|
+
* re-adopted DONE row's `markDone` returned a terminal 4xx (a status that will
|
|
2023
|
+
* never succeed). Checked at the TOP of the `done` branch so we do NOT re-attempt
|
|
2024
|
+
* that markDone every ~2s drain while the row stays `processing`. A TRANSIENT
|
|
2025
|
+
* markDone failure must NOT land here (it must still retry next drain). Separate
|
|
2026
|
+
* from `dontRedispatch` because the two concerns are independent: a row can need
|
|
2027
|
+
* "stop re-dispatching" without "stop delivering", and vice versa. Cleared once
|
|
2028
|
+
* the row leaves the processing list, exactly like `dontRedispatch`.
|
|
2029
|
+
*/
|
|
2030
|
+
doneUndeliverable = /* @__PURE__ */ new Set();
|
|
2031
|
+
/**
|
|
2032
|
+
* "Already emitted `readopt_poll_unresolved` for this row" (#229). The b1 /
|
|
2033
|
+
* unreadable-status re-evaluate leaf leaves the row UN-tracked so it is re-read
|
|
2034
|
+
* every ~2s drain until the status map becomes readable — but the server-visible
|
|
2035
|
+
* signal is an OUTCOME, so it must fire at most ONCE per row, not once per drain
|
|
2036
|
+
* (Bugbot "Re-adopt signals flood every drain"). Cleared when the row leaves the
|
|
2037
|
+
* processing list, exactly like `dontRedispatch`/`doneUndeliverable`.
|
|
2038
|
+
*/
|
|
2039
|
+
readoptPollUnresolvedSignalled = /* @__PURE__ */ new Set();
|
|
2040
|
+
/**
|
|
2041
|
+
* "A null-id re-adopt re-dispatch is in flight, awaiting its read-back" (WI-5
|
|
2042
|
+
* Task 5.4, High-2). Since we no longer send a caller-supplied id, a re-dispatch
|
|
2043
|
+
* is NOT idempotent: if `forceReadoptRun` dispatches on tick N but the read-back +
|
|
2044
|
+
* persist hasn't landed before tick N+1 re-reads the still-null
|
|
2045
|
+
* `row.opencode_message_id`, tick N+1 would dispatch AGAIN → duplicate user turns.
|
|
2046
|
+
* A row is added here right before its `sendPromptAsync` and `forceReadoptRun`
|
|
2047
|
+
* short-circuits while it is present, so a null-id row is re-dispatched AT MOST
|
|
2048
|
+
* ONCE per outstanding read-back. Cleared on a SUCCESSFUL dispatch+read-back (the
|
|
2049
|
+
* row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
|
|
2050
|
+
* re-entry) OR on a failed/unresolved dispatch (the message is genuinely un-sent,
|
|
2051
|
+
* so the NEXT tick may retry exactly once more).
|
|
2052
|
+
*/
|
|
2053
|
+
awaitingReadopt = /* @__PURE__ */ new Set();
|
|
2054
|
+
/**
|
|
2055
|
+
* "Already signalled `attachments_skipped` for this Evident message id" (#376).
|
|
2056
|
+
* The in-thread skip note is an OUTCOME, so it must fire AT MOST ONCE per message
|
|
2057
|
+
* — never re-post on a re-dispatch of the same row (`forceReadoptRun` or the
|
|
2058
|
+
* next-tick null-id retry both re-run `sendPromptAsync`, which re-fires
|
|
2059
|
+
* `onOutcomes`). Mirrors `readoptPollUnresolvedSignalled`: a local dedup on the
|
|
2060
|
+
* outcome, not the dispatch. Not cleared (a message is signalled once for life).
|
|
2061
|
+
*/
|
|
2062
|
+
attachmentsSkippedSignalled = /* @__PURE__ */ new Set();
|
|
1608
2063
|
/**
|
|
1609
2064
|
* Cache of the opencode root directory (from `GET /path`). Resolved lazily on
|
|
1610
2065
|
* first session creation so drain-created sessions are rooted at the project
|
|
@@ -1612,8 +2067,43 @@ var ChannelDriver = class {
|
|
|
1612
2067
|
* not yet resolved; `null` = resolved-but-unavailable (don't keep retrying).
|
|
1613
2068
|
*/
|
|
1614
2069
|
opencodeDirectory = void 0;
|
|
2070
|
+
/**
|
|
2071
|
+
* Cache of opencode `sessionId → parentID` (its parent session, or `null` when
|
|
2072
|
+
* the session is a root with no parent). Sub-agents spawned via the `task` tool
|
|
2073
|
+
* run in CHILD sessions whose `parentID` chains up to the Evident-created
|
|
2074
|
+
* (watched) session; we resolve this once per session so a child-session
|
|
2075
|
+
* question/permission can be attributed to the watched session's subtree
|
|
2076
|
+
* (`sessionBelongsTo`) instead of being dropped by an exact-id filter. A missing
|
|
2077
|
+
* entry = not yet resolved; `null` = resolved root (stop walking).
|
|
2078
|
+
*/
|
|
2079
|
+
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
|
+
/**
|
|
2081
|
+
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2082
|
+
* NON-EMPTY name is stored (terminal — a real session name won't later un-name),
|
|
2083
|
+
* so we do NOT re-GET `/session/:id` every tick. A missing entry = not yet
|
|
2084
|
+
* resolved OR resolved-but-still-empty → re-fetch on next need, since OpenCode
|
|
2085
|
+
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
|
+
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
|
+
* no watcher) can resolve the title.
|
|
2088
|
+
*/
|
|
2089
|
+
sessionTitles = /* @__PURE__ */ new Map();
|
|
1615
2090
|
/** Serialises drains so a reconnect during a drain doesn't double-process. */
|
|
1616
2091
|
draining = false;
|
|
2092
|
+
/**
|
|
2093
|
+
* The currently-executing `drainPending()` promise, or null when idle. Lets a
|
|
2094
|
+
* graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
|
|
2095
|
+
* is about to dispatch is not missed by the `hasInFlightWatchers()` check (a
|
|
2096
|
+
* drain that entered before `stop()` still registers its watcher).
|
|
2097
|
+
*/
|
|
2098
|
+
activeDrain = null;
|
|
2099
|
+
/**
|
|
2100
|
+
* Set by `stop()` on graceful shutdown. Once stopped, `drainPending` no longer
|
|
2101
|
+
* dispatches NEW work (it returns 0 immediately) — but the per-session watcher
|
|
2102
|
+
* loops already running keep going so in-flight turns can finish and deliver
|
|
2103
|
+
* their reply. `run.ts` awaits `waitForInFlight()` before it closes the tunnel
|
|
2104
|
+
* and stops opencode.
|
|
2105
|
+
*/
|
|
2106
|
+
stopped = false;
|
|
1617
2107
|
constructor(config2) {
|
|
1618
2108
|
this.agentId = config2.agentId;
|
|
1619
2109
|
this.port = config2.port;
|
|
@@ -1627,7 +2117,7 @@ var ChannelDriver = class {
|
|
|
1627
2117
|
this.sleep = config2.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1628
2118
|
this.pausedPollIntervalMs = config2.pausedPollIntervalMs ?? DEFAULT_PAUSED_POLL_INTERVAL_MS;
|
|
1629
2119
|
this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
|
|
1630
|
-
this.
|
|
2120
|
+
this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
|
|
1631
2121
|
this.now = config2.now ?? (() => Date.now());
|
|
1632
2122
|
}
|
|
1633
2123
|
/** The IPv4-loopback base URL for the local `opencode serve`. */
|
|
@@ -1645,8 +2135,21 @@ var ChannelDriver = class {
|
|
|
1645
2135
|
* @returns the number of messages NEWLY dispatched to opencode's native queue.
|
|
1646
2136
|
*/
|
|
1647
2137
|
async drainPending() {
|
|
2138
|
+
if (this.stopped) return 0;
|
|
1648
2139
|
if (this.draining) return 0;
|
|
1649
2140
|
this.draining = true;
|
|
2141
|
+
const run2 = this.runDrain();
|
|
2142
|
+
this.activeDrain = run2.then(
|
|
2143
|
+
() => {
|
|
2144
|
+
this.activeDrain = null;
|
|
2145
|
+
},
|
|
2146
|
+
() => {
|
|
2147
|
+
this.activeDrain = null;
|
|
2148
|
+
}
|
|
2149
|
+
);
|
|
2150
|
+
return run2;
|
|
2151
|
+
}
|
|
2152
|
+
async runDrain() {
|
|
1650
2153
|
let dispatched = 0;
|
|
1651
2154
|
try {
|
|
1652
2155
|
const conversations = await this.getPendingConversations();
|
|
@@ -1658,8 +2161,10 @@ var ChannelDriver = class {
|
|
|
1658
2161
|
});
|
|
1659
2162
|
}
|
|
1660
2163
|
for (const conv of conversations) {
|
|
2164
|
+
if (this.stopped) break;
|
|
1661
2165
|
dispatched += await this.processConversation(conv);
|
|
1662
2166
|
}
|
|
2167
|
+
await this.readoptProcessing();
|
|
1663
2168
|
} finally {
|
|
1664
2169
|
this.draining = false;
|
|
1665
2170
|
}
|
|
@@ -1677,6 +2182,73 @@ var ChannelDriver = class {
|
|
|
1677
2182
|
}
|
|
1678
2183
|
return false;
|
|
1679
2184
|
}
|
|
2185
|
+
/**
|
|
2186
|
+
* OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
|
|
2187
|
+
* exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
|
|
2188
|
+
* `watchers` entry whose `inFlight` set is non-empty — the same predicate
|
|
2189
|
+
* `hasInFlightWatchers()` uses, lifted to return the ids.
|
|
2190
|
+
*
|
|
2191
|
+
* Deliberately does NOT include `this.sessions` (the permanent, never-pruned
|
|
2192
|
+
* conversation→session cache). Protecting every bound-but-idle session there
|
|
2193
|
+
* would shield nearly every session and defeat cleanup — AND it is unnecessary:
|
|
2194
|
+
* `ensureSession` is self-healing (it recreates a session whose id no longer
|
|
2195
|
+
* exists), so deleting an idle bound session is harmless — the conversation's
|
|
2196
|
+
* next turn transparently rebinds a fresh one. The only thing worth protecting
|
|
2197
|
+
* is a session with a turn ACTIVELY in flight right now: tearing that down
|
|
2198
|
+
* mid-turn would strand the running `prompt_async`. Idle sessions are fair game.
|
|
2199
|
+
*/
|
|
2200
|
+
protectedSessionIds() {
|
|
2201
|
+
const ids = /* @__PURE__ */ new Set();
|
|
2202
|
+
for (const [sessionId, watcher] of this.watchers) {
|
|
2203
|
+
if (watcher.inFlight.size > 0) ids.add(sessionId);
|
|
2204
|
+
}
|
|
2205
|
+
return ids;
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2208
|
+
* Begin a graceful stop: stop accepting NEW channel work. Idempotent. After
|
|
2209
|
+
* this, `drainPending()` is a no-op (returns 0), so no new message is dispatched
|
|
2210
|
+
* — but the watcher loops already tracking in-flight turns keep running, so a
|
|
2211
|
+
* turn that has finished (or is about to) still fires `markDone` and delivers
|
|
2212
|
+
* its reply. Pair with `waitForInFlight()` to bound how long shutdown waits.
|
|
2213
|
+
*/
|
|
2214
|
+
stop() {
|
|
2215
|
+
this.stopped = true;
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
|
|
2219
|
+
* graceful shutdown, so a turn whose reply is ready — or completes within the
|
|
2220
|
+
* window — is delivered before the process exits, instead of being cut off and
|
|
2221
|
+
* left for the ADR-0046 restart-recovery path.
|
|
2222
|
+
*
|
|
2223
|
+
* Bounded on purpose: the watcher's own give-up deadline is up to 10 minutes,
|
|
2224
|
+
* far longer than a shutdown grace period (e.g. Fargate's SIGTERM→SIGKILL
|
|
2225
|
+
* window). We poll `hasInFlightWatchers()` and return as soon as the in-flight
|
|
2226
|
+
* set empties OR the timeout elapses. Anything still in flight at the timeout is
|
|
2227
|
+
* safe to abandon — it stays `processing` server-side and is re-adopted on the
|
|
2228
|
+
* next runner start (ADR-0046).
|
|
2229
|
+
*
|
|
2230
|
+
* @returns true if all in-flight work settled within the window; false if the
|
|
2231
|
+
* timeout elapsed with work still in flight.
|
|
2232
|
+
*/
|
|
2233
|
+
async waitForInFlight(timeoutMs) {
|
|
2234
|
+
const deadline = this.now() + timeoutMs;
|
|
2235
|
+
const step = Math.min(this.pausedPollIntervalMs, 250);
|
|
2236
|
+
if (this.activeDrain) {
|
|
2237
|
+
let drainSettled = false;
|
|
2238
|
+
void this.activeDrain.then(() => {
|
|
2239
|
+
drainSettled = true;
|
|
2240
|
+
});
|
|
2241
|
+
while (!drainSettled) {
|
|
2242
|
+
if (this.now() >= deadline) return false;
|
|
2243
|
+
await this.sleep(step);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
while (this.hasInFlightWatchers()) {
|
|
2247
|
+
if (this.now() >= deadline) return false;
|
|
2248
|
+
await this.sleep(step);
|
|
2249
|
+
}
|
|
2250
|
+
return true;
|
|
2251
|
+
}
|
|
1680
2252
|
/**
|
|
1681
2253
|
* Await all outstanding per-session watchers (WI-3).
|
|
1682
2254
|
*
|
|
@@ -1713,15 +2285,16 @@ var ChannelDriver = class {
|
|
|
1713
2285
|
let dispatched = 0;
|
|
1714
2286
|
let skippedAlreadyDispatched = 0;
|
|
1715
2287
|
for (const message of messages) {
|
|
2288
|
+
if (this.stopped) break;
|
|
1716
2289
|
if (this.dispatched.has(message.id)) {
|
|
1717
2290
|
skippedAlreadyDispatched += 1;
|
|
1718
2291
|
continue;
|
|
1719
2292
|
}
|
|
1720
|
-
const opencodeMessageId = opencodeMessageIdFor2(message.id);
|
|
1721
2293
|
const options = {
|
|
1722
2294
|
agent: message.opencode_agent ?? void 0,
|
|
1723
2295
|
model: message.opencode_model ?? void 0
|
|
1724
2296
|
};
|
|
2297
|
+
let opencodeMessageId;
|
|
1725
2298
|
try {
|
|
1726
2299
|
this.log({
|
|
1727
2300
|
level: "info",
|
|
@@ -1729,10 +2302,24 @@ var ChannelDriver = class {
|
|
|
1729
2302
|
conversation_id: conv.id,
|
|
1730
2303
|
message_id: message.id
|
|
1731
2304
|
});
|
|
1732
|
-
|
|
2305
|
+
const sendAttachments = this.buildSendAttachments(conv, message);
|
|
2306
|
+
opencodeMessageId = await this.dispatchLocked(
|
|
2307
|
+
sessionId,
|
|
2308
|
+
() => sendPromptAsync(this.port, sessionId, message.content, options, sendAttachments)
|
|
2309
|
+
);
|
|
1733
2310
|
} catch (err) {
|
|
1734
2311
|
if (err instanceof ChannelAuthError) throw err;
|
|
1735
2312
|
this.dispatched.delete(message.id);
|
|
2313
|
+
if (await sessionExists(this.port, sessionId) === false) {
|
|
2314
|
+
this.sessions.delete(conv.id);
|
|
2315
|
+
this.log({
|
|
2316
|
+
level: "warn",
|
|
2317
|
+
message: `Message ${message.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch (cleanup race) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick (recreated then, in order). Already-dispatched turns keep their watcher.`,
|
|
2318
|
+
conversation_id: conv.id,
|
|
2319
|
+
message_id: message.id
|
|
2320
|
+
});
|
|
2321
|
+
break;
|
|
2322
|
+
}
|
|
1736
2323
|
await this.markFailed(conv.id, message.id).catch(() => {
|
|
1737
2324
|
});
|
|
1738
2325
|
this.log({
|
|
@@ -1743,13 +2330,23 @@ var ChannelDriver = class {
|
|
|
1743
2330
|
});
|
|
1744
2331
|
continue;
|
|
1745
2332
|
}
|
|
2333
|
+
if (opencodeMessageId === null) {
|
|
2334
|
+
this.log({
|
|
2335
|
+
level: "warn",
|
|
2336
|
+
message: `Message ${message.id.slice(0, 8)} dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next tick`,
|
|
2337
|
+
conversation_id: conv.id,
|
|
2338
|
+
message_id: message.id
|
|
2339
|
+
});
|
|
2340
|
+
continue;
|
|
2341
|
+
}
|
|
1746
2342
|
this.dispatched.add(message.id);
|
|
1747
2343
|
this.registerInFlight(conv, sessionId, message, opencodeMessageId);
|
|
1748
2344
|
dispatched += 1;
|
|
2345
|
+
void this.postSignal(conv.id, message.id, "dispatched");
|
|
1749
2346
|
}
|
|
1750
2347
|
if (messages.length > 0 && dispatched === 0 && skippedAlreadyDispatched === messages.length) {
|
|
1751
2348
|
this.log({
|
|
1752
|
-
level: "
|
|
2349
|
+
level: "warn",
|
|
1753
2350
|
message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode this tick. If this repeats, a message may be stuck acknowledged-but-never-dispatched (its watcher never settled).`,
|
|
1754
2351
|
conversation_id: conv.id
|
|
1755
2352
|
});
|
|
@@ -1758,16 +2355,33 @@ var ChannelDriver = class {
|
|
|
1758
2355
|
return dispatched;
|
|
1759
2356
|
}
|
|
1760
2357
|
async ensureSession(conv) {
|
|
1761
|
-
const
|
|
1762
|
-
if (
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
2358
|
+
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
2359
|
+
if (bound) {
|
|
2360
|
+
const exists = await sessionExists(this.port, bound);
|
|
2361
|
+
if (exists === false) {
|
|
2362
|
+
this.log({
|
|
2363
|
+
level: "debug",
|
|
2364
|
+
message: `OpenCode session ${bound} for conversation ${conv.id.slice(0, 8)} no longer exists (deleted or DB reset) \u2014 creating a fresh session and rebinding.`,
|
|
2365
|
+
conversation_id: conv.id
|
|
2366
|
+
});
|
|
2367
|
+
this.sessions.delete(conv.id);
|
|
2368
|
+
return this.createAndBindSession(conv.id);
|
|
2369
|
+
}
|
|
2370
|
+
this.sessions.set(conv.id, bound);
|
|
2371
|
+
return bound;
|
|
1766
2372
|
}
|
|
2373
|
+
return this.createAndBindSession(conv.id);
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
2377
|
+
* best-effort persist it server-side. Shared by the first-ever bind and the
|
|
2378
|
+
* self-heal recreate path in `ensureSession`.
|
|
2379
|
+
*/
|
|
2380
|
+
async createAndBindSession(conversationId) {
|
|
1767
2381
|
const directory = await this.resolveOpenCodeDirectory();
|
|
1768
2382
|
const sessionId = await createOpenCodeSession(this.port, directory);
|
|
1769
|
-
this.sessions.set(
|
|
1770
|
-
await this.persistSession(
|
|
2383
|
+
this.sessions.set(conversationId, sessionId);
|
|
2384
|
+
await this.persistSession(conversationId, sessionId).catch(() => {
|
|
1771
2385
|
});
|
|
1772
2386
|
return sessionId;
|
|
1773
2387
|
}
|
|
@@ -1781,7 +2395,7 @@ var ChannelDriver = class {
|
|
|
1781
2395
|
this.opencodeDirectory = await getOpenCodeDirectory(this.port);
|
|
1782
2396
|
if (!this.opencodeDirectory) {
|
|
1783
2397
|
this.log({
|
|
1784
|
-
level: "
|
|
2398
|
+
level: "warn",
|
|
1785
2399
|
message: "Could not determine opencode directory (GET /path) \u2014 new sessions may not appear in opencode web"
|
|
1786
2400
|
});
|
|
1787
2401
|
}
|
|
@@ -1790,6 +2404,124 @@ var ChannelDriver = class {
|
|
|
1790
2404
|
// -------------------------------------------------------------------------
|
|
1791
2405
|
// Per-session watcher (WI-3)
|
|
1792
2406
|
// -------------------------------------------------------------------------
|
|
2407
|
+
/**
|
|
2408
|
+
* Run one dispatch (`sendPromptAsync` snapshot→POST→read-back) serialized per
|
|
2409
|
+
* opencode session (Task 2.1a), so two dispatches into the SAME session can
|
|
2410
|
+
* never interleave and mis-correlate their read-backs. Distinct sessions run
|
|
2411
|
+
* concurrently. The chained tail intentionally ignores the prior result/error
|
|
2412
|
+
* (each dispatch reports its own outcome to its caller).
|
|
2413
|
+
*/
|
|
2414
|
+
dispatchLocked(sessionId, fn) {
|
|
2415
|
+
const prior = this.sessionDispatchLocks.get(sessionId) ?? Promise.resolve();
|
|
2416
|
+
const run2 = prior.then(fn, fn);
|
|
2417
|
+
this.sessionDispatchLocks.set(
|
|
2418
|
+
sessionId,
|
|
2419
|
+
run2.then(
|
|
2420
|
+
() => void 0,
|
|
2421
|
+
() => void 0
|
|
2422
|
+
)
|
|
2423
|
+
);
|
|
2424
|
+
return run2;
|
|
2425
|
+
}
|
|
2426
|
+
// -------------------------------------------------------------------------
|
|
2427
|
+
// Inbound image attachments (#255, WI-8)
|
|
2428
|
+
// -------------------------------------------------------------------------
|
|
2429
|
+
/**
|
|
2430
|
+
* Build the `SendAttachmentsInput` for a message's inbound images, or
|
|
2431
|
+
* `undefined` when the message has none (so a text-only turn is unchanged).
|
|
2432
|
+
*
|
|
2433
|
+
* The driver OWNS the two channel-facing concerns the session module cannot:
|
|
2434
|
+
* - the AUTHENTICATED byte fetch through Evident's WI-6 endpoint
|
|
2435
|
+
* (`fetchAttachmentDataUrl`), using the SAME `getAuthHeader()` as every
|
|
2436
|
+
* other combinedAuth callback — the CLI NEVER talks to Slack directly;
|
|
2437
|
+
* - the in-thread SKIP NOTE (`signalAttachmentsSkipped`) posted over the
|
|
2438
|
+
* existing callback surface when any image was skipped/failed.
|
|
2439
|
+
* `sendPromptAsync` applies the capability gate + appends the `file` parts and
|
|
2440
|
+
* reports outcomes back via `onOutcomes`.
|
|
2441
|
+
*/
|
|
2442
|
+
buildSendAttachments(conv, message) {
|
|
2443
|
+
const refs = message.attachments;
|
|
2444
|
+
if (!refs || refs.length === 0) return void 0;
|
|
2445
|
+
return {
|
|
2446
|
+
inputs: refs.map((a, index) => ({
|
|
2447
|
+
index,
|
|
2448
|
+
mime: a.mime,
|
|
2449
|
+
...a.filename ? { filename: a.filename } : {}
|
|
2450
|
+
})),
|
|
2451
|
+
fetchDataUrl: (index) => this.fetchAttachmentDataUrl(message.id, index, refs[index].mime),
|
|
2452
|
+
onOutcomes: ({ outcomes, capabilityUnknown }) => this.signalAttachmentsSkipped(conv.id, message.id, outcomes, capabilityUnknown)
|
|
2453
|
+
};
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2457
|
+
* (`GET {apiUrl}/agents/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2458
|
+
* existing authenticated fetch, and base64-encode into a
|
|
2459
|
+
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2460
|
+
*
|
|
2461
|
+
* The endpoint streams the source bytes verbatim (200), or returns 404
|
|
2462
|
+
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2463
|
+
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2464
|
+
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2465
|
+
* Failures are logged with context (no silent swallow).
|
|
2466
|
+
*/
|
|
2467
|
+
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2468
|
+
try {
|
|
2469
|
+
const res = await this.fetchImpl(
|
|
2470
|
+
`${this.apiUrl}/agents/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2471
|
+
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2472
|
+
);
|
|
2473
|
+
if (!res.ok) {
|
|
2474
|
+
this.log({
|
|
2475
|
+
level: "error",
|
|
2476
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
2477
|
+
message_id: messageId
|
|
2478
|
+
});
|
|
2479
|
+
return null;
|
|
2480
|
+
}
|
|
2481
|
+
const buf = await res.arrayBuffer();
|
|
2482
|
+
const base64 = Buffer.from(buf).toString("base64");
|
|
2483
|
+
const dataMime = cleanImageMime(res.headers.get("content-type")) || mime;
|
|
2484
|
+
return `data:${dataMime};base64,${base64}`;
|
|
2485
|
+
} catch (err) {
|
|
2486
|
+
this.log({
|
|
2487
|
+
level: "error",
|
|
2488
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} failed \u2014 omitting this image (text turn proceeds): ${err instanceof Error ? err.message : String(err)}`,
|
|
2489
|
+
message_id: messageId
|
|
2490
|
+
});
|
|
2491
|
+
return null;
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* On any skipped/failed image, post an in-thread note to Evident over the
|
|
2496
|
+
* EXISTING combinedAuth callback surface — the CLI NEVER posts to Slack directly.
|
|
2497
|
+
* Evident routes the note to source via `conversation.deliver`.
|
|
2498
|
+
*
|
|
2499
|
+
* The `POST .../messages/:id/signal` route accepts `attachments_skipped` (in
|
|
2500
|
+
* `messageSignalSchema`) and turns it into an in-thread note delivered through
|
|
2501
|
+
* `conversation.deliver` (e.g. "N image(s) couldn't be forwarded"), so the note
|
|
2502
|
+
* reaches the channel.
|
|
2503
|
+
*
|
|
2504
|
+
* Fire-and-forget: never throws into the send/tick (logs its own failure).
|
|
2505
|
+
*/
|
|
2506
|
+
signalAttachmentsSkipped(conversationId, messageId, outcomes, capabilityUnknown) {
|
|
2507
|
+
const skipped = outcomes.filter((o) => o.status === "skipped").length;
|
|
2508
|
+
const failed = outcomes.filter((o) => o.status === "failed").length;
|
|
2509
|
+
if (skipped === 0 && failed === 0) return;
|
|
2510
|
+
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2511
|
+
this.attachmentsSkippedSignalled.add(messageId);
|
|
2512
|
+
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
2513
|
+
this.log({
|
|
2514
|
+
level: "info",
|
|
2515
|
+
message: `Message ${messageId.slice(0, 8)}: ${skipped} image(s) skipped (${capabilityUnknown ? "capability was unreadable \u2014 failed open to text-only" : "model not attachment-capable"}), ${failed} image(s) unavailable (deleted-at-source or fetch failure) \u2014 noting to Evident`,
|
|
2516
|
+
conversation_id: conversationId,
|
|
2517
|
+
message_id: messageId
|
|
2518
|
+
});
|
|
2519
|
+
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2520
|
+
skipped,
|
|
2521
|
+
failed,
|
|
2522
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
1793
2525
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
1794
2526
|
registerInFlight(conv, sessionId, message, opencodeMessageId) {
|
|
1795
2527
|
let watcher = this.watchers.get(sessionId);
|
|
@@ -1799,7 +2531,9 @@ var ChannelDriver = class {
|
|
|
1799
2531
|
inFlight: /* @__PURE__ */ new Map(),
|
|
1800
2532
|
loop: null,
|
|
1801
2533
|
reportedQuestions: /* @__PURE__ */ new Set(),
|
|
1802
|
-
reportedPermissions: /* @__PURE__ */ new Set()
|
|
2534
|
+
reportedPermissions: /* @__PURE__ */ new Set(),
|
|
2535
|
+
lastGoodPollAt: this.now(),
|
|
2536
|
+
hadUsablePoll: false
|
|
1803
2537
|
};
|
|
1804
2538
|
this.watchers.set(sessionId, watcher);
|
|
1805
2539
|
}
|
|
@@ -1809,17 +2543,100 @@ var ChannelDriver = class {
|
|
|
1809
2543
|
opencodeMessageId,
|
|
1810
2544
|
message,
|
|
1811
2545
|
dispatchedAt: now,
|
|
2546
|
+
processingAnchorMs: now,
|
|
1812
2547
|
deadline: now + this.pausedMaxWaitMs,
|
|
1813
2548
|
started: false,
|
|
1814
|
-
done: false
|
|
2549
|
+
done: false,
|
|
2550
|
+
stuckReported: false,
|
|
2551
|
+
lastAliveAt: 0,
|
|
2552
|
+
aliveInFlight: false,
|
|
2553
|
+
awaitingHumanLatched: false,
|
|
2554
|
+
pausedOnQuestion: false,
|
|
2555
|
+
pausedOnPermission: false,
|
|
2556
|
+
pausedClearConfirmed: false,
|
|
2557
|
+
pausedInFlight: false,
|
|
2558
|
+
deliveryDeadlineAnchored: false
|
|
1815
2559
|
});
|
|
1816
2560
|
}
|
|
1817
2561
|
/**
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
1820
|
-
*
|
|
1821
|
-
*
|
|
1822
|
-
*
|
|
2562
|
+
* Register a RE-ADOPTED `processing` message with its session watcher
|
|
2563
|
+
* (ADR-0046, WI-4). Mirrors `registerInFlight` but anchors the give-up
|
|
2564
|
+
* `deadline` to the row's SERVER-SIDE `processed_at` (Invariant 1), NEVER to
|
|
2565
|
+
* `now`, so the paused/queued/unreachable cases settle on the same wall-clock a
|
|
2566
|
+
* fresh dispatch would (10 min after `processed_at`, not 10 min from now).
|
|
2567
|
+
*
|
|
2568
|
+
* This re-attaches into the SAME watcher, so the ADR-0047 progressing-vs-paused
|
|
2569
|
+
* give-up (`serviceInFlightMessage`) applies unchanged: a re-adopted turn
|
|
2570
|
+
* opencode reports ACTIVELY `running` is watched to completion (its liveness
|
|
2571
|
+
* heartbeat keeps the cron off its row), while a re-adopted turn that is paused
|
|
2572
|
+
* awaiting a human — or queued/unreachable — is still bounded by `deadline` and
|
|
2573
|
+
* handed to the cron. The old "the `deadline` must settle before the ~15-min
|
|
2574
|
+
* cron or they double-drive" reasoning is superseded: liveness now settles the
|
|
2575
|
+
* actively-running case; `deadline` settles the rest. `dispatchedAt` stays `now`
|
|
2576
|
+
* (only the appear-guard uses it).
|
|
2577
|
+
*
|
|
2578
|
+
* `evidentMessageId` addresses the SERVER row (for markProcessing/markDone);
|
|
2579
|
+
* `opencodeMessageId` is the id the watcher polls for a reply — for the orphan
|
|
2580
|
+
* fresh-run path these differ (a fresh opencode id under the same server row).
|
|
2581
|
+
*
|
|
2582
|
+
* `started` is set true so the watcher does NOT re-`markProcessing` a row the
|
|
2583
|
+
* server already flipped to `processing`; the running/done transitions still
|
|
2584
|
+
* fire from the watcher's normal branches.
|
|
2585
|
+
*/
|
|
2586
|
+
registerReadopted(conv, sessionId, message, opencodeMessageId, processedAtMs) {
|
|
2587
|
+
let watcher = this.watchers.get(sessionId);
|
|
2588
|
+
if (!watcher) {
|
|
2589
|
+
watcher = {
|
|
2590
|
+
conv,
|
|
2591
|
+
inFlight: /* @__PURE__ */ new Map(),
|
|
2592
|
+
loop: null,
|
|
2593
|
+
reportedQuestions: /* @__PURE__ */ new Set(),
|
|
2594
|
+
reportedPermissions: /* @__PURE__ */ new Set(),
|
|
2595
|
+
lastGoodPollAt: this.now(),
|
|
2596
|
+
hadUsablePoll: false
|
|
2597
|
+
};
|
|
2598
|
+
this.watchers.set(sessionId, watcher);
|
|
2599
|
+
}
|
|
2600
|
+
watcher.inFlight.set(message.id, {
|
|
2601
|
+
evidentMessageId: message.id,
|
|
2602
|
+
opencodeMessageId,
|
|
2603
|
+
message,
|
|
2604
|
+
dispatchedAt: this.now(),
|
|
2605
|
+
// Anchor the absolute-age ceiling to the SERVER-SIDE `processed_at` (the same
|
|
2606
|
+
// value seeding `deadline`), NOT `dispatchedAt` — so a re-adopted zombie's age
|
|
2607
|
+
// reflects the real turn duration and the ceiling fires on the ORIGINAL turn.
|
|
2608
|
+
processingAnchorMs: processedAtMs,
|
|
2609
|
+
deadline: processedAtMs + this.pausedMaxWaitMs,
|
|
2610
|
+
// The server row is ALREADY `processing`; do not re-fire markProcessing.
|
|
2611
|
+
started: true,
|
|
2612
|
+
done: false,
|
|
2613
|
+
// Not yet reported stuck-queued. The once-guard (`stuckReported`) applies,
|
|
2614
|
+
// AND the stuck-queued observer INCLUDES re-adopted queued wedges: it gates
|
|
2615
|
+
// on `state === 'queued'` (turn produced no reply), not on `started`, so a
|
|
2616
|
+
// re-adopted row left wedged in `queued` still emits the signal once
|
|
2617
|
+
// (#210/#220 observability).
|
|
2618
|
+
stuckReported: false,
|
|
2619
|
+
// Task 5.2: a re-adopted actively-running row re-attaches into the SAME
|
|
2620
|
+
// watcher and so hits the SAME actively-running heartbeat branch in
|
|
2621
|
+
// `serviceInFlightMessage` as a fresh dispatch — monitoring observes "runner
|
|
2622
|
+
// re-adopted and is confirming this row alive" via that `alive` heartbeat,
|
|
2623
|
+
// with no extra `re_adopted` signal needed (folds old WI-6).
|
|
2624
|
+
lastAliveAt: 0,
|
|
2625
|
+
aliveInFlight: false,
|
|
2626
|
+
awaitingHumanLatched: false,
|
|
2627
|
+
pausedOnQuestion: false,
|
|
2628
|
+
pausedOnPermission: false,
|
|
2629
|
+
pausedClearConfirmed: false,
|
|
2630
|
+
pausedInFlight: false,
|
|
2631
|
+
deliveryDeadlineAnchored: false
|
|
2632
|
+
});
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Start (but do NOT await) the per-session watcher loop if it has in-flight
|
|
2636
|
+
* work and is not already running. Single-flight per session. The loop is
|
|
2637
|
+
* tracked on the watcher and cleared when it settles; it never rejects (fully
|
|
2638
|
+
* guarded), so a failed poll/callback can never crash the run loop — the cron
|
|
2639
|
+
* stays as the safety net.
|
|
1823
2640
|
*/
|
|
1824
2641
|
ensureWatcherRunning(sessionId) {
|
|
1825
2642
|
const watcher = this.watchers.get(sessionId);
|
|
@@ -1862,12 +2679,30 @@ var ChannelDriver = class {
|
|
|
1862
2679
|
messages = Array.isArray(body) ? body : null;
|
|
1863
2680
|
}
|
|
1864
2681
|
} catch {
|
|
1865
|
-
continue;
|
|
1866
2682
|
}
|
|
2683
|
+
if (messages != null && messages.length > 0) {
|
|
2684
|
+
watcher.lastGoodPollAt = this.now();
|
|
2685
|
+
watcher.hadUsablePoll = true;
|
|
2686
|
+
} else {
|
|
2687
|
+
const emptyButReachable = messages != null;
|
|
2688
|
+
const graceApplies = !emptyButReachable || watcher.hadUsablePoll;
|
|
2689
|
+
if (graceApplies && this.now() - watcher.lastGoodPollAt < POLL_MISS_GRACE_MS) {
|
|
2690
|
+
continue;
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
const { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk } = await this.pollInteractions(sessionId, watcher, messages);
|
|
1867
2694
|
for (const inFlight of [...watcher.inFlight.values()]) {
|
|
1868
|
-
await this.serviceInFlightMessage(
|
|
2695
|
+
await this.serviceInFlightMessage(
|
|
2696
|
+
sessionId,
|
|
2697
|
+
watcher,
|
|
2698
|
+
inFlight,
|
|
2699
|
+
messages,
|
|
2700
|
+
openQuestions,
|
|
2701
|
+
openPermissions,
|
|
2702
|
+
questionsPolledOk,
|
|
2703
|
+
permissionsPolledOk
|
|
2704
|
+
);
|
|
1869
2705
|
}
|
|
1870
|
-
await this.pollInteractions(sessionId, watcher, messages);
|
|
1871
2706
|
}
|
|
1872
2707
|
} catch (err) {
|
|
1873
2708
|
if (err instanceof ChannelAuthError) {
|
|
@@ -1877,6 +2712,7 @@ var ChannelDriver = class {
|
|
|
1877
2712
|
conversation_id: watcher.conv.id
|
|
1878
2713
|
});
|
|
1879
2714
|
for (const evidentMessageId of [...watcher.inFlight.keys()]) {
|
|
2715
|
+
this.readopted.delete(evidentMessageId);
|
|
1880
2716
|
this.removeInFlight(watcher, evidentMessageId);
|
|
1881
2717
|
}
|
|
1882
2718
|
return;
|
|
@@ -1888,23 +2724,55 @@ var ChannelDriver = class {
|
|
|
1888
2724
|
});
|
|
1889
2725
|
}
|
|
1890
2726
|
}
|
|
2727
|
+
/**
|
|
2728
|
+
* On FIRST observing a terminal (done/failed) state, ensure the delivery
|
|
2729
|
+
* (markDone/markFailed) transient-retry path has a real window. A long
|
|
2730
|
+
* ACTIVELY-running turn is kept past its original `deadline`, so by completion
|
|
2731
|
+
* `now >= deadline` already holds and the retry bound below would fire on the
|
|
2732
|
+
* first transient PATCH failure — dropping the message before its reply lands
|
|
2733
|
+
* (Bugbot "Stale deadline aborts long-turn delivery"). Re-anchor once (latched)
|
|
2734
|
+
* to a fresh `pausedMaxWaitMs` window; only extend if the current deadline is at
|
|
2735
|
+
* or past now, so a still-ample window is left untouched.
|
|
2736
|
+
*/
|
|
2737
|
+
anchorDeliveryDeadline(inFlight) {
|
|
2738
|
+
if (inFlight.deliveryDeadlineAnchored) return;
|
|
2739
|
+
inFlight.deliveryDeadlineAnchored = true;
|
|
2740
|
+
if (this.now() >= inFlight.deadline) {
|
|
2741
|
+
inFlight.deadline = this.now() + this.pausedMaxWaitMs;
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
1891
2744
|
/**
|
|
1892
2745
|
* Drive ONE in-flight message's lifecycle from the tick's message snapshot.
|
|
1893
2746
|
* Fires markProcessing on queued→running and markDone on done (each once),
|
|
1894
2747
|
* applies the idle-path re-dispatch guard, and removes the message from the
|
|
1895
2748
|
* in-flight set on completion or timeout.
|
|
1896
2749
|
*/
|
|
1897
|
-
async serviceInFlightMessage(sessionId, watcher, inFlight, messages) {
|
|
2750
|
+
async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk) {
|
|
1898
2751
|
const conv = watcher.conv;
|
|
1899
2752
|
const state = messageRunState(messages, inFlight.opencodeMessageId);
|
|
1900
|
-
|
|
2753
|
+
const id = inFlight.evidentMessageId;
|
|
2754
|
+
if (openQuestions.has(id)) inFlight.pausedOnQuestion = true;
|
|
2755
|
+
else if (questionsPolledOk) inFlight.pausedOnQuestion = false;
|
|
2756
|
+
if (openPermissions.has(id)) inFlight.pausedOnPermission = true;
|
|
2757
|
+
else if (permissionsPolledOk) inFlight.pausedOnPermission = false;
|
|
2758
|
+
const observedOpen = openQuestions.has(id) || openPermissions.has(id);
|
|
2759
|
+
const latchedPaused = inFlight.pausedOnQuestion || inFlight.pausedOnPermission;
|
|
2760
|
+
const awaitingHuman = observedOpen || latchedPaused;
|
|
2761
|
+
if ((state === "running" || state === "done" || state === "failed") && !inFlight.started) {
|
|
2762
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
1901
2763
|
let claimed;
|
|
1902
2764
|
try {
|
|
1903
|
-
claimed = await this.markProcessing(
|
|
2765
|
+
claimed = await this.markProcessing(
|
|
2766
|
+
conv.id,
|
|
2767
|
+
inFlight.evidentMessageId,
|
|
2768
|
+
sessionId,
|
|
2769
|
+
inFlight.opencodeMessageId,
|
|
2770
|
+
title
|
|
2771
|
+
);
|
|
1904
2772
|
} catch (err) {
|
|
1905
2773
|
if (err instanceof ChannelAuthError) throw err;
|
|
1906
2774
|
this.log({
|
|
1907
|
-
level: "
|
|
2775
|
+
level: "warn",
|
|
1908
2776
|
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} processing (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
1909
2777
|
conversation_id: conv.id,
|
|
1910
2778
|
message_id: inFlight.evidentMessageId
|
|
@@ -1914,7 +2782,7 @@ var ChannelDriver = class {
|
|
|
1914
2782
|
inFlight.started = true;
|
|
1915
2783
|
if (!claimed) {
|
|
1916
2784
|
this.log({
|
|
1917
|
-
level: "
|
|
2785
|
+
level: "debug",
|
|
1918
2786
|
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} already marked processing \u2014 continuing`,
|
|
1919
2787
|
conversation_id: conv.id,
|
|
1920
2788
|
message_id: inFlight.evidentMessageId
|
|
@@ -1922,6 +2790,7 @@ var ChannelDriver = class {
|
|
|
1922
2790
|
}
|
|
1923
2791
|
}
|
|
1924
2792
|
if (state === "done") {
|
|
2793
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
1925
2794
|
if (!inFlight.done) {
|
|
1926
2795
|
this.log({
|
|
1927
2796
|
level: "info",
|
|
@@ -1929,13 +2798,20 @@ var ChannelDriver = class {
|
|
|
1929
2798
|
conversation_id: conv.id,
|
|
1930
2799
|
message_id: inFlight.evidentMessageId
|
|
1931
2800
|
});
|
|
2801
|
+
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
1932
2802
|
try {
|
|
1933
|
-
await this.markDone(
|
|
2803
|
+
await this.markDone(
|
|
2804
|
+
conv.id,
|
|
2805
|
+
inFlight.evidentMessageId,
|
|
2806
|
+
sessionId,
|
|
2807
|
+
inFlight.opencodeMessageId,
|
|
2808
|
+
title
|
|
2809
|
+
);
|
|
1934
2810
|
} catch (err) {
|
|
1935
2811
|
if (err instanceof ChannelAuthError) throw err;
|
|
1936
2812
|
if (err instanceof ChannelTerminalError) {
|
|
1937
2813
|
this.log({
|
|
1938
|
-
level: "
|
|
2814
|
+
level: "warn",
|
|
1939
2815
|
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
1940
2816
|
conversation_id: conv.id,
|
|
1941
2817
|
message_id: inFlight.evidentMessageId
|
|
@@ -1945,7 +2821,7 @@ var ChannelDriver = class {
|
|
|
1945
2821
|
}
|
|
1946
2822
|
if (this.now() >= inFlight.deadline) {
|
|
1947
2823
|
this.log({
|
|
1948
|
-
level: "
|
|
2824
|
+
level: "warn",
|
|
1949
2825
|
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
1950
2826
|
conversation_id: conv.id,
|
|
1951
2827
|
message_id: inFlight.evidentMessageId
|
|
@@ -1954,7 +2830,7 @@ var ChannelDriver = class {
|
|
|
1954
2830
|
return;
|
|
1955
2831
|
}
|
|
1956
2832
|
this.log({
|
|
1957
|
-
level: "
|
|
2833
|
+
level: "warn",
|
|
1958
2834
|
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} done (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
1959
2835
|
conversation_id: conv.id,
|
|
1960
2836
|
message_id: inFlight.evidentMessageId
|
|
@@ -1966,60 +2842,585 @@ var ChannelDriver = class {
|
|
|
1966
2842
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1967
2843
|
return;
|
|
1968
2844
|
}
|
|
1969
|
-
if (state === "
|
|
1970
|
-
|
|
1971
|
-
|
|
2845
|
+
if (state === "failed") {
|
|
2846
|
+
this.anchorDeliveryDeadline(inFlight);
|
|
2847
|
+
if (!inFlight.done) {
|
|
2848
|
+
const error2 = messageError(messages, inFlight.opencodeMessageId) ?? void 0;
|
|
2849
|
+
this.log({
|
|
2850
|
+
level: "error",
|
|
2851
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} errored \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
2852
|
+
conversation_id: conv.id,
|
|
2853
|
+
message_id: inFlight.evidentMessageId
|
|
2854
|
+
});
|
|
2855
|
+
try {
|
|
2856
|
+
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
|
|
2857
|
+
} catch (err) {
|
|
2858
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
2859
|
+
if (err instanceof ChannelTerminalError) {
|
|
2860
|
+
this.log({
|
|
2861
|
+
level: "warn",
|
|
2862
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (terminal HTTP ${err.status}) \u2014 leaving for the cron safety net: ${err.message}`,
|
|
2863
|
+
conversation_id: conv.id,
|
|
2864
|
+
message_id: inFlight.evidentMessageId
|
|
2865
|
+
});
|
|
2866
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2867
|
+
return;
|
|
2868
|
+
}
|
|
2869
|
+
if (this.now() >= inFlight.deadline) {
|
|
2870
|
+
this.log({
|
|
2871
|
+
level: "warn",
|
|
2872
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed within the watch window \u2014 leaving for the cron safety net: ${err instanceof Error ? err.message : String(err)}`,
|
|
2873
|
+
conversation_id: conv.id,
|
|
2874
|
+
message_id: inFlight.evidentMessageId
|
|
2875
|
+
});
|
|
2876
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2877
|
+
return;
|
|
2878
|
+
}
|
|
2879
|
+
this.log({
|
|
2880
|
+
level: "warn",
|
|
2881
|
+
message: `Failed to mark message ${inFlight.evidentMessageId.slice(0, 8)} failed (will retry next tick): ${err instanceof Error ? err.message : String(err)}`,
|
|
2882
|
+
conversation_id: conv.id,
|
|
2883
|
+
message_id: inFlight.evidentMessageId
|
|
2884
|
+
});
|
|
2885
|
+
return;
|
|
2886
|
+
}
|
|
2887
|
+
inFlight.done = true;
|
|
1972
2888
|
}
|
|
2889
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2890
|
+
return;
|
|
1973
2891
|
}
|
|
1974
|
-
|
|
2892
|
+
const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
|
|
2893
|
+
const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
|
|
2894
|
+
if (state === "queued" && pastStuckBound && sessionIdle && !inFlight.stuckReported) {
|
|
2895
|
+
inFlight.stuckReported = true;
|
|
2896
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "stuck_queued", {
|
|
2897
|
+
stuck_for_ms: this.now() - inFlight.dispatchedAt
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
2900
|
+
const activelyRunning = state === "running" && !awaitingHuman;
|
|
2901
|
+
if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
|
|
1975
2902
|
this.log({
|
|
1976
|
-
level: "
|
|
2903
|
+
level: "warn",
|
|
2904
|
+
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} exceeded the absolute processing ceiling (${Math.round((this.now() - inFlight.processingAnchorMs) / 6e4)}min, session ${sessionId}) while still actively running \u2014 releasing so the cron can reclaim it`,
|
|
2905
|
+
conversation_id: conv.id,
|
|
2906
|
+
message_id: inFlight.evidentMessageId
|
|
2907
|
+
});
|
|
2908
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
|
|
2909
|
+
watched_for_ms: this.now() - inFlight.processingAnchorMs
|
|
2910
|
+
});
|
|
2911
|
+
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
2912
|
+
return;
|
|
2913
|
+
}
|
|
2914
|
+
if (activelyRunning && !inFlight.awaitingHumanLatched && !inFlight.aliveInFlight && this.now() - inFlight.lastAliveAt >= HEARTBEAT_MS) {
|
|
2915
|
+
inFlight.aliveInFlight = true;
|
|
2916
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "alive").then((ok) => {
|
|
2917
|
+
inFlight.aliveInFlight = false;
|
|
2918
|
+
if (ok) inFlight.lastAliveAt = this.now();
|
|
2919
|
+
});
|
|
2920
|
+
}
|
|
2921
|
+
if (awaitingHuman) {
|
|
2922
|
+
if (!inFlight.awaitingHumanLatched) {
|
|
2923
|
+
inFlight.deadline = this.now() + this.pausedMaxWaitMs;
|
|
2924
|
+
inFlight.awaitingHumanLatched = true;
|
|
2925
|
+
}
|
|
2926
|
+
if (!inFlight.pausedClearConfirmed && !inFlight.pausedInFlight) {
|
|
2927
|
+
inFlight.pausedInFlight = true;
|
|
2928
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "paused").then((ok) => {
|
|
2929
|
+
inFlight.pausedInFlight = false;
|
|
2930
|
+
if (ok && inFlight.awaitingHumanLatched) inFlight.pausedClearConfirmed = true;
|
|
2931
|
+
});
|
|
2932
|
+
}
|
|
2933
|
+
} else if (inFlight.awaitingHumanLatched) {
|
|
2934
|
+
inFlight.awaitingHumanLatched = false;
|
|
2935
|
+
inFlight.pausedOnQuestion = false;
|
|
2936
|
+
inFlight.pausedOnPermission = false;
|
|
2937
|
+
inFlight.pausedClearConfirmed = false;
|
|
2938
|
+
}
|
|
2939
|
+
const siblingPaused = (sib) => openQuestions.has(sib.evidentMessageId) || openPermissions.has(sib.evidentMessageId) || sib.awaitingHumanLatched || sib.pausedOnQuestion || sib.pausedOnPermission;
|
|
2940
|
+
const hasActivelyRunningSibling = [...watcher.inFlight.values()].some(
|
|
2941
|
+
(sib) => sib.evidentMessageId !== inFlight.evidentMessageId && messageRunState(messages, sib.opencodeMessageId) === "running" && !siblingPaused(sib)
|
|
2942
|
+
);
|
|
2943
|
+
const queuedBehindRunningSibling = state === "queued" && hasActivelyRunningSibling;
|
|
2944
|
+
if (!activelyRunning && !queuedBehindRunningSibling && this.now() >= inFlight.deadline) {
|
|
2945
|
+
this.log({
|
|
2946
|
+
level: "debug",
|
|
1977
2947
|
message: `Message ${inFlight.evidentMessageId.slice(0, 8)} did not complete within the watch window \u2014 leaving for the cron safety net`,
|
|
1978
2948
|
conversation_id: conv.id,
|
|
1979
2949
|
message_id: inFlight.evidentMessageId
|
|
1980
2950
|
});
|
|
2951
|
+
void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
|
|
2952
|
+
watched_for_ms: this.now() - inFlight.dispatchedAt
|
|
2953
|
+
});
|
|
1981
2954
|
this.removeInFlight(watcher, inFlight.evidentMessageId);
|
|
1982
2955
|
}
|
|
1983
2956
|
}
|
|
2957
|
+
// -------------------------------------------------------------------------
|
|
2958
|
+
// Restart recovery: re-adopt `processing` messages (ADR-0046, WI-3/4/5)
|
|
2959
|
+
// -------------------------------------------------------------------------
|
|
2960
|
+
/**
|
|
2961
|
+
* Re-adopt this agent's `processing` messages on drain (ADR-0046 Decision §1).
|
|
2962
|
+
*
|
|
2963
|
+
* The pending drain only re-drives `pending` rows; a message already flipped to
|
|
2964
|
+
* `processing` before the runner died is watched by nobody until the 15-min
|
|
2965
|
+
* cron resets it. Here we fetch those rows, and per row resolve its correlated
|
|
2966
|
+
* reply against opencode's OWN session store — completing, re-attaching, or
|
|
2967
|
+
* (for an orphan) forcing a genuine fresh run. Runs on EVERY drain tick, so it
|
|
2968
|
+
* is idempotent per message (Invariant 2): a row a watcher already tracks is
|
|
2969
|
+
* skipped in `readoptOne` — one driver, no double-drive.
|
|
2970
|
+
*
|
|
2971
|
+
* Only `ChannelAuthError` propagates (to `drainPending`, like the pending
|
|
2972
|
+
* path); every other early return LOGS a reason with context — no silent drop.
|
|
2973
|
+
*/
|
|
2974
|
+
async readoptProcessing() {
|
|
2975
|
+
const rows = await this.getProcessingMessages();
|
|
2976
|
+
if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
|
|
2977
|
+
const stillProcessing = new Set(rows.map((r) => r.id));
|
|
2978
|
+
for (const id of [
|
|
2979
|
+
...this.dontRedispatch,
|
|
2980
|
+
...this.doneUndeliverable,
|
|
2981
|
+
...this.readoptPollUnresolvedSignalled
|
|
2982
|
+
]) {
|
|
2983
|
+
if (!stillProcessing.has(id)) {
|
|
2984
|
+
const cleared = this.dontRedispatch.delete(id);
|
|
2985
|
+
const clearedUndeliverable = this.doneUndeliverable.delete(id);
|
|
2986
|
+
this.readoptPollUnresolvedSignalled.delete(id);
|
|
2987
|
+
if (cleared || clearedUndeliverable) {
|
|
2988
|
+
this.log({
|
|
2989
|
+
level: "debug",
|
|
2990
|
+
message: `Re-adopt: message ${id.slice(0, 8)} left the processing list (cron reset) \u2014 cleared gave-up marker`,
|
|
2991
|
+
message_id: id
|
|
2992
|
+
});
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
if (rows.length === 0) return;
|
|
2998
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
2999
|
+
for (const row of rows) {
|
|
3000
|
+
if (!row.opencode_session_id) {
|
|
3001
|
+
this.log({
|
|
3002
|
+
level: "warn",
|
|
3003
|
+
message: `Cannot re-adopt processing message ${row.id.slice(0, 8)} \u2014 no opencode session id; leaving for the cron safety net`,
|
|
3004
|
+
conversation_id: row.conversation_id,
|
|
3005
|
+
message_id: row.id
|
|
3006
|
+
});
|
|
3007
|
+
continue;
|
|
3008
|
+
}
|
|
3009
|
+
const list = bySession.get(row.opencode_session_id) ?? [];
|
|
3010
|
+
list.push(row);
|
|
3011
|
+
bySession.set(row.opencode_session_id, list);
|
|
3012
|
+
}
|
|
3013
|
+
for (const [sessionId, sessionRows] of bySession) {
|
|
3014
|
+
let messages;
|
|
3015
|
+
try {
|
|
3016
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}/message`);
|
|
3017
|
+
if (!res.ok) {
|
|
3018
|
+
this.log({
|
|
3019
|
+
level: "warn",
|
|
3020
|
+
message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned HTTP ${res.status} \u2014 skipping this session this tick`
|
|
3021
|
+
});
|
|
3022
|
+
continue;
|
|
3023
|
+
}
|
|
3024
|
+
const body = await res.json();
|
|
3025
|
+
if (!Array.isArray(body)) {
|
|
3026
|
+
this.log({
|
|
3027
|
+
level: "warn",
|
|
3028
|
+
message: `Re-adopt: polling session ${sessionId.slice(0, 8)} returned a non-array message body \u2014 skipping this session this tick`
|
|
3029
|
+
});
|
|
3030
|
+
continue;
|
|
3031
|
+
}
|
|
3032
|
+
messages = body;
|
|
3033
|
+
} catch (err) {
|
|
3034
|
+
this.log({
|
|
3035
|
+
level: "warn",
|
|
3036
|
+
message: `Re-adopt: failed to poll session ${sessionId.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`
|
|
3037
|
+
});
|
|
3038
|
+
continue;
|
|
3039
|
+
}
|
|
3040
|
+
const anyUntracked = sessionRows.some((row) => !this.isTracked(sessionId, row.id));
|
|
3041
|
+
const sessionOngoing = anyUntracked ? await isSessionOngoing(this.port, sessionId) : null;
|
|
3042
|
+
for (const row of sessionRows) {
|
|
3043
|
+
await this.readoptOne(sessionId, row, messages, sessionOngoing);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
1984
3047
|
/**
|
|
1985
|
-
* Re-
|
|
1986
|
-
*
|
|
1987
|
-
*
|
|
1988
|
-
*
|
|
3048
|
+
* Re-adopt ONE `processing` row against the tick's session message snapshot
|
|
3049
|
+
* (ADR-0046 Decision §1/§2). Idempotent: skips a row already being driven.
|
|
3050
|
+
*
|
|
3051
|
+
* Branches on `messageRunState(messages, row.opencode_message_id)` — the
|
|
3052
|
+
* opencode-assigned user-message id persisted on the first `processing` PATCH
|
|
3053
|
+
* (#218). A row with a NULL stored id (dispatched but the read-back never landed
|
|
3054
|
+
* before the restart) has no id to correlate → treated as an orphan and
|
|
3055
|
+
* re-dispatched (at most once, see `forceReadoptRun`):
|
|
3056
|
+
* - `done` → `markDone` now (guarded like the watcher's done branch);
|
|
3057
|
+
* - `failed` → `markFailed` with the surfaced error (issue #182), so an
|
|
3058
|
+
* errored turn is reported failed on restart, NOT re-dispatched;
|
|
3059
|
+
* - `running`/`queued` → re-attach a watcher via `registerReadopted` (no re-dispatch),
|
|
3060
|
+
* tracking the stored id so the reply correlates by it;
|
|
3061
|
+
* - `unknown`/null id → re-dispatch (opencode assigns a fresh id) + attach a watcher.
|
|
3062
|
+
*
|
|
3063
|
+
* Only `ChannelAuthError` propagates.
|
|
3064
|
+
*/
|
|
3065
|
+
async readoptOne(sessionId, row, messages, sessionOngoing) {
|
|
3066
|
+
if (this.isTracked(sessionId, row.id)) {
|
|
3067
|
+
this.log({
|
|
3068
|
+
level: "debug",
|
|
3069
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} already tracked in-flight \u2014 skipping (owned by the watcher loop)`,
|
|
3070
|
+
conversation_id: row.conversation_id,
|
|
3071
|
+
message_id: row.id
|
|
3072
|
+
});
|
|
3073
|
+
return;
|
|
3074
|
+
}
|
|
3075
|
+
const ocId = row.opencode_message_id;
|
|
3076
|
+
const state = messageRunState(messages, ocId ?? "");
|
|
3077
|
+
if (state === "done") {
|
|
3078
|
+
if (this.doneUndeliverable.has(row.id)) {
|
|
3079
|
+
this.log({
|
|
3080
|
+
level: "debug",
|
|
3081
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} markDone is terminally undeliverable \u2014 left to the cron; skipping until it leaves processing`,
|
|
3082
|
+
conversation_id: row.conversation_id,
|
|
3083
|
+
message_id: row.id
|
|
3084
|
+
});
|
|
3085
|
+
return;
|
|
3086
|
+
}
|
|
3087
|
+
this.log({
|
|
3088
|
+
level: "info",
|
|
3089
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} completed while unwatched \u2014 marking done`,
|
|
3090
|
+
conversation_id: row.conversation_id,
|
|
3091
|
+
message_id: row.id
|
|
3092
|
+
});
|
|
3093
|
+
try {
|
|
3094
|
+
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3095
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title);
|
|
3096
|
+
} catch (err) {
|
|
3097
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3098
|
+
if (err instanceof ChannelTerminalError) {
|
|
3099
|
+
this.doneUndeliverable.add(row.id);
|
|
3100
|
+
this.log({
|
|
3101
|
+
level: "warn",
|
|
3102
|
+
message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} done (terminal HTTP ${err.status}) \u2014 parking until it leaves processing; leaving for the cron safety net: ${err.message}`,
|
|
3103
|
+
conversation_id: row.conversation_id,
|
|
3104
|
+
message_id: row.id
|
|
3105
|
+
});
|
|
3106
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
|
|
3107
|
+
return;
|
|
3108
|
+
}
|
|
3109
|
+
this.log({
|
|
3110
|
+
level: "warn",
|
|
3111
|
+
message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} done (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
3112
|
+
conversation_id: row.conversation_id,
|
|
3113
|
+
message_id: row.id
|
|
3114
|
+
});
|
|
3115
|
+
return;
|
|
3116
|
+
}
|
|
3117
|
+
this.dontRedispatch.delete(row.id);
|
|
3118
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_done");
|
|
3119
|
+
return;
|
|
3120
|
+
}
|
|
3121
|
+
if (state === "failed") {
|
|
3122
|
+
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3123
|
+
this.log({
|
|
3124
|
+
level: "error",
|
|
3125
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
3126
|
+
conversation_id: row.conversation_id,
|
|
3127
|
+
message_id: row.id
|
|
3128
|
+
});
|
|
3129
|
+
try {
|
|
3130
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
3131
|
+
} catch (err) {
|
|
3132
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
3133
|
+
if (err instanceof ChannelTerminalError) {
|
|
3134
|
+
this.doneUndeliverable.add(row.id);
|
|
3135
|
+
this.log({
|
|
3136
|
+
level: "warn",
|
|
3137
|
+
message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} failed (terminal HTTP ${err.status}) \u2014 parking until it leaves processing; leaving for the cron safety net: ${err.message}`,
|
|
3138
|
+
conversation_id: row.conversation_id,
|
|
3139
|
+
message_id: row.id
|
|
3140
|
+
});
|
|
3141
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_undeliverable");
|
|
3142
|
+
return;
|
|
3143
|
+
}
|
|
3144
|
+
this.log({
|
|
3145
|
+
level: "warn",
|
|
3146
|
+
message: `Re-adopt: failed to mark message ${row.id.slice(0, 8)} failed (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
3147
|
+
conversation_id: row.conversation_id,
|
|
3148
|
+
message_id: row.id
|
|
3149
|
+
});
|
|
3150
|
+
return;
|
|
3151
|
+
}
|
|
3152
|
+
this.dontRedispatch.delete(row.id);
|
|
3153
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_failed");
|
|
3154
|
+
return;
|
|
3155
|
+
}
|
|
3156
|
+
if (this.dontRedispatch.has(row.id)) {
|
|
3157
|
+
this.log({
|
|
3158
|
+
level: "debug",
|
|
3159
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} already gave up \u2014 left to the cron; skipping until it leaves processing`,
|
|
3160
|
+
conversation_id: row.conversation_id,
|
|
3161
|
+
message_id: row.id
|
|
3162
|
+
});
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
3165
|
+
let statusReadableOngoing = null;
|
|
3166
|
+
if (state === "running" && ocId) {
|
|
3167
|
+
const reply = findLastAssistantReplyFor(messages, ocId);
|
|
3168
|
+
const shape = this.replyCompletionShape(reply);
|
|
3169
|
+
const ongoing = sessionOngoing;
|
|
3170
|
+
statusReadableOngoing = ongoing;
|
|
3171
|
+
if (ongoing === false) {
|
|
3172
|
+
this.log({
|
|
3173
|
+
level: "info",
|
|
3174
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} but session ${sessionId.slice(0, 8)} is not-ongoing per GET /session/status (absent/idle) \u2014 re-dispatching from scratch (status-gated recovery)`,
|
|
3175
|
+
conversation_id: row.conversation_id,
|
|
3176
|
+
message_id: row.id
|
|
3177
|
+
});
|
|
3178
|
+
await this.forceReadoptRun(sessionId, row);
|
|
3179
|
+
return;
|
|
3180
|
+
}
|
|
3181
|
+
if (ongoing === true) {
|
|
3182
|
+
this.log({
|
|
3183
|
+
level: "debug",
|
|
3184
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} and session ${sessionId.slice(0, 8)} is ongoing per GET /session/status (busy/retry) \u2014 re-attaching watcher (no re-dispatch)`,
|
|
3185
|
+
conversation_id: row.conversation_id,
|
|
3186
|
+
message_id: row.id
|
|
3187
|
+
});
|
|
3188
|
+
} else {
|
|
3189
|
+
if (shape === "b1") {
|
|
3190
|
+
this.log({
|
|
3191
|
+
level: "debug",
|
|
3192
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} running/b1 but GET /session/status was unreadable (null) for session ${sessionId.slice(0, 8)} \u2014 NOT latching a b1 row on a transient status blip; leaving it un-tracked to re-evaluate on the next drain`,
|
|
3193
|
+
conversation_id: row.conversation_id,
|
|
3194
|
+
message_id: row.id
|
|
3195
|
+
});
|
|
3196
|
+
if (!this.readoptPollUnresolvedSignalled.has(row.id)) {
|
|
3197
|
+
this.readoptPollUnresolvedSignalled.add(row.id);
|
|
3198
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_poll_unresolved");
|
|
3199
|
+
}
|
|
3200
|
+
return;
|
|
3201
|
+
}
|
|
3202
|
+
this.log({
|
|
3203
|
+
level: "debug",
|
|
3204
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} running/${shape} but GET /session/status was unreadable (null) for session ${sessionId.slice(0, 8)} \u2014 falling back to the #253 preamble + descendant cross-check`,
|
|
3205
|
+
conversation_id: row.conversation_id,
|
|
3206
|
+
message_id: row.id
|
|
3207
|
+
});
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
if (statusReadableOngoing === null && state === "running" && ocId && isPreamblePinnedRunning(messages, ocId)) {
|
|
3211
|
+
const descendantAlive = await this.isAnyDescendantSessionAlive(sessionId);
|
|
3212
|
+
if (descendantAlive === true) {
|
|
3213
|
+
this.log({
|
|
3214
|
+
level: "debug",
|
|
3215
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} preamble-pinned running (root ${sessionId.slice(0, 8)}) but a live descendant sub-agent session was found \u2014 treating as still running, re-attaching watcher (no re-dispatch)`,
|
|
3216
|
+
conversation_id: row.conversation_id,
|
|
3217
|
+
message_id: row.id
|
|
3218
|
+
});
|
|
3219
|
+
} else {
|
|
3220
|
+
this.log({
|
|
3221
|
+
level: "info",
|
|
3222
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} preamble-pinned on recovery (root ${sessionId.slice(0, 8)}), no live descendant runner \u2014 re-dispatching from scratch${descendantAlive === null ? " (descendant liveness indeterminate; a restart guarantees no live runner, so this does NOT block the re-dispatch)" : ""}`,
|
|
3223
|
+
conversation_id: row.conversation_id,
|
|
3224
|
+
message_id: row.id
|
|
3225
|
+
});
|
|
3226
|
+
await this.forceReadoptRun(sessionId, row);
|
|
3227
|
+
return;
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
if ((state === "running" || state === "queued") && ocId) {
|
|
3231
|
+
const conv = this.convForRow(sessionId, row);
|
|
3232
|
+
const message = this.queuedMessageForRow(row);
|
|
3233
|
+
this.registerReadopted(conv, sessionId, message, ocId, this.processedAtMs(row));
|
|
3234
|
+
this.dispatched.add(row.id);
|
|
3235
|
+
this.readopted.add(row.id);
|
|
3236
|
+
this.ensureWatcherRunning(sessionId);
|
|
3237
|
+
this.log({
|
|
3238
|
+
level: "debug",
|
|
3239
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} ${state} \u2014 re-attached watcher (stored id, no re-dispatch)`,
|
|
3240
|
+
conversation_id: row.conversation_id,
|
|
3241
|
+
message_id: row.id
|
|
3242
|
+
});
|
|
3243
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_reattached");
|
|
3244
|
+
return;
|
|
3245
|
+
}
|
|
3246
|
+
await this.forceReadoptRun(sessionId, row);
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* Re-dispatch an orphaned (`unknown`/null-id) `processing` row (ADR-0046 §2).
|
|
3250
|
+
*
|
|
3251
|
+
* #218/WI-5: the row's user message is absent (never kept, or a null stored id),
|
|
3252
|
+
* so we re-`prompt_async` WITHOUT a caller id (opencode assigns a monotonic one),
|
|
3253
|
+
* read it back, and register the watcher under the assigned id so the reply
|
|
3254
|
+
* correlates server-side.
|
|
3255
|
+
*
|
|
3256
|
+
* ⚠️ AT-MOST-ONCE (High-2): dispatch is no longer idempotent (no caller-supplied
|
|
3257
|
+
* id). Without a guard, if this dispatches on tick N but the read-back+persist
|
|
3258
|
+
* hasn't landed before tick N+1 re-reads the still-null `opencode_message_id`,
|
|
3259
|
+
* tick N+1 would dispatch AGAIN → duplicate user turns. The `awaitingReadopt`
|
|
3260
|
+
* latch makes a null-id row re-dispatched AT MOST ONCE per outstanding read-back:
|
|
3261
|
+
* short-circuit while the row is latched; clear it on a successful dispatch (the
|
|
3262
|
+
* row is then tracked in `dispatched`, so `readoptOne`'s early skip prevents
|
|
3263
|
+
* re-entry) OR on a failed/unresolved dispatch (genuinely un-sent → the next tick
|
|
3264
|
+
* may retry exactly once more).
|
|
3265
|
+
*
|
|
3266
|
+
* `evidentMessageId = row.id` addresses the SERVER row. Deadline anchored to
|
|
3267
|
+
* `processed_at` (Invariant 1).
|
|
1989
3268
|
*/
|
|
1990
|
-
async
|
|
3269
|
+
async forceReadoptRun(sessionId, row) {
|
|
3270
|
+
if (this.stopped) {
|
|
3271
|
+
this.log({
|
|
3272
|
+
level: "debug",
|
|
3273
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned but the runner is stopping \u2014 not starting a fresh turn; leaving for restart recovery`,
|
|
3274
|
+
conversation_id: row.conversation_id,
|
|
3275
|
+
message_id: row.id
|
|
3276
|
+
});
|
|
3277
|
+
return;
|
|
3278
|
+
}
|
|
3279
|
+
if (this.awaitingReadopt.has(row.id)) {
|
|
3280
|
+
this.log({
|
|
3281
|
+
level: "debug",
|
|
3282
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} already has a re-dispatch awaiting read-back \u2014 skipping (at most once)`,
|
|
3283
|
+
conversation_id: row.conversation_id,
|
|
3284
|
+
message_id: row.id
|
|
3285
|
+
});
|
|
3286
|
+
return;
|
|
3287
|
+
}
|
|
3288
|
+
if (this.processedAtMs(row) + this.pausedMaxWaitMs <= this.now()) {
|
|
3289
|
+
this.dontRedispatch.add(row.id);
|
|
3290
|
+
this.log({
|
|
3291
|
+
level: "debug",
|
|
3292
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned but its re-adopt window has already elapsed \u2014 not dispatching an unwatchable turn; parking until it leaves processing (cron will reset it)`,
|
|
3293
|
+
conversation_id: row.conversation_id,
|
|
3294
|
+
message_id: row.id
|
|
3295
|
+
});
|
|
3296
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_window_elapsed");
|
|
3297
|
+
return;
|
|
3298
|
+
}
|
|
1991
3299
|
const options = {
|
|
1992
|
-
agent:
|
|
1993
|
-
model:
|
|
3300
|
+
agent: row.opencode_agent ?? void 0,
|
|
3301
|
+
model: row.opencode_model ?? void 0
|
|
1994
3302
|
};
|
|
1995
3303
|
this.log({
|
|
1996
3304
|
level: "info",
|
|
1997
|
-
message: `
|
|
1998
|
-
|
|
3305
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} orphaned (user message absent) \u2014 re-dispatching (opencode assigns a fresh id)`,
|
|
3306
|
+
conversation_id: row.conversation_id,
|
|
3307
|
+
message_id: row.id
|
|
1999
3308
|
});
|
|
3309
|
+
this.awaitingReadopt.add(row.id);
|
|
3310
|
+
const readoptConv = this.convForRow(sessionId, row);
|
|
3311
|
+
const readoptMessage = this.queuedMessageForRow(row);
|
|
3312
|
+
const sendAttachments = this.buildSendAttachments(readoptConv, readoptMessage);
|
|
3313
|
+
let ocId;
|
|
2000
3314
|
try {
|
|
2001
|
-
await
|
|
2002
|
-
this.port,
|
|
3315
|
+
ocId = await this.dispatchLocked(
|
|
2003
3316
|
sessionId,
|
|
2004
|
-
|
|
2005
|
-
options,
|
|
2006
|
-
inFlight.opencodeMessageId
|
|
3317
|
+
() => sendPromptAsync(this.port, sessionId, row.content, options, sendAttachments)
|
|
2007
3318
|
);
|
|
2008
3319
|
} catch (err) {
|
|
3320
|
+
this.awaitingReadopt.delete(row.id);
|
|
3321
|
+
if (err instanceof ChannelAuthError) throw err;
|
|
2009
3322
|
this.log({
|
|
2010
|
-
level: "
|
|
2011
|
-
message: `Re-dispatch failed for message ${
|
|
2012
|
-
|
|
3323
|
+
level: "warn",
|
|
3324
|
+
message: `Re-adopt: re-dispatch failed for message ${row.id.slice(0, 8)} (will retry next drain): ${err instanceof Error ? err.message : String(err)}`,
|
|
3325
|
+
conversation_id: row.conversation_id,
|
|
3326
|
+
message_id: row.id
|
|
2013
3327
|
});
|
|
3328
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
3329
|
+
return;
|
|
2014
3330
|
}
|
|
2015
|
-
|
|
3331
|
+
if (ocId === null) {
|
|
3332
|
+
this.awaitingReadopt.delete(row.id);
|
|
3333
|
+
this.log({
|
|
3334
|
+
level: "warn",
|
|
3335
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} re-dispatched but its opencode id could not be read back \u2014 leaving un-tracked to retry next drain`,
|
|
3336
|
+
conversation_id: row.conversation_id,
|
|
3337
|
+
message_id: row.id
|
|
3338
|
+
});
|
|
3339
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_orphan_unsent");
|
|
3340
|
+
return;
|
|
3341
|
+
}
|
|
3342
|
+
this.registerReadopted(readoptConv, sessionId, readoptMessage, ocId, this.processedAtMs(row));
|
|
3343
|
+
this.dispatched.add(row.id);
|
|
3344
|
+
this.readopted.add(row.id);
|
|
3345
|
+
this.awaitingReadopt.delete(row.id);
|
|
3346
|
+
this.ensureWatcherRunning(sessionId);
|
|
3347
|
+
void this.postSignal(row.conversation_id, row.id, "readopt_redispatched");
|
|
3348
|
+
}
|
|
3349
|
+
/**
|
|
3350
|
+
* True if `evidentMessageId` is already being driven — either in the
|
|
3351
|
+
* authoritative `dispatched` set or a live watcher's in-flight set for this
|
|
3352
|
+
* session (Invariant 2, WI-5). Either signal means a watcher owns the row.
|
|
3353
|
+
*/
|
|
3354
|
+
isTracked(sessionId, evidentMessageId) {
|
|
3355
|
+
if (this.dispatched.has(evidentMessageId)) return true;
|
|
3356
|
+
const watcher = this.watchers.get(sessionId);
|
|
3357
|
+
return watcher?.inFlight.has(evidentMessageId) ?? false;
|
|
3358
|
+
}
|
|
3359
|
+
/**
|
|
3360
|
+
* Parse a re-adopt row's `processed_at` (ISO string) to epoch ms for the
|
|
3361
|
+
* deadline anchor (Invariant 1). The endpoint guarantees `processed_at` is set
|
|
3362
|
+
* for `processing` rows, but if it is somehow null/unparseable fall back to
|
|
3363
|
+
* `now` (defensive) AND log — a fallback means the anchor is weaker than
|
|
3364
|
+
* intended, which is worth surfacing.
|
|
3365
|
+
*/
|
|
3366
|
+
processedAtMs(row) {
|
|
3367
|
+
const parsed = row.processed_at ? Date.parse(row.processed_at) : NaN;
|
|
3368
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
3369
|
+
this.log({
|
|
3370
|
+
level: "error",
|
|
3371
|
+
message: `Re-adopt: message ${row.id.slice(0, 8)} has null/unparseable processed_at (${String(row.processed_at)}) \u2014 anchoring deadline to now (defensive)`,
|
|
3372
|
+
conversation_id: row.conversation_id,
|
|
3373
|
+
message_id: row.id
|
|
3374
|
+
});
|
|
3375
|
+
return this.now();
|
|
3376
|
+
}
|
|
3377
|
+
/** Build the `PendingConversation` shape the watcher needs from a re-adopt row. */
|
|
3378
|
+
convForRow(sessionId, row) {
|
|
3379
|
+
return {
|
|
3380
|
+
id: row.conversation_id,
|
|
3381
|
+
agent_id: this.agentId,
|
|
3382
|
+
opencode_session_id: sessionId,
|
|
3383
|
+
pending_message_count: 0,
|
|
3384
|
+
oldest_pending_at: row.processed_at
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
/** Build the `QueuedMessage` shape the watcher/re-dispatch needs from a re-adopt row. */
|
|
3388
|
+
queuedMessageForRow(row) {
|
|
3389
|
+
return {
|
|
3390
|
+
id: row.id,
|
|
3391
|
+
content: row.content,
|
|
3392
|
+
status: "processing",
|
|
3393
|
+
opencode_agent: row.opencode_agent,
|
|
3394
|
+
opencode_model: row.opencode_model,
|
|
3395
|
+
source_message_id: row.source_message_id,
|
|
3396
|
+
slack_user_id: row.slack_user_id,
|
|
3397
|
+
attachments: row.attachments ?? null
|
|
3398
|
+
};
|
|
2016
3399
|
}
|
|
2017
3400
|
/**
|
|
2018
3401
|
* Remove a message from the in-flight set AND the authoritative dispatched
|
|
2019
3402
|
* set. Once the in-flight set empties, the watcher loop's `while` guard exits
|
|
2020
3403
|
* and its `.finally` removes the session entry from `this.watchers`.
|
|
3404
|
+
*
|
|
3405
|
+
* Bug 2: if a RE-ADOPTED message is removed WITHOUT having completed
|
|
3406
|
+
* (`!inFlight.done` — i.e. a give-up: deadline reached, or markDone left to the
|
|
3407
|
+
* cron), park it in `dontRedispatch` so the next drain does NOT re-adopt (and
|
|
3408
|
+
* re-dispatch) the still-`processing` row every ~2s until the 15-min cron. A
|
|
3409
|
+
* re-adopted message that completed (`done`) needs no marker — it's leaving
|
|
3410
|
+
* `processing`. This suppresses only re-dispatch: if its reply later completes,
|
|
3411
|
+
* the done branch still delivers it (Bugbot #202).
|
|
2021
3412
|
*/
|
|
2022
3413
|
removeInFlight(watcher, evidentMessageId) {
|
|
3414
|
+
const inFlight = watcher.inFlight.get(evidentMessageId);
|
|
3415
|
+
if (this.readopted.delete(evidentMessageId) && inFlight && !inFlight.done) {
|
|
3416
|
+
this.dontRedispatch.add(evidentMessageId);
|
|
3417
|
+
this.log({
|
|
3418
|
+
level: "debug",
|
|
3419
|
+
message: `Re-adopt: message ${evidentMessageId.slice(0, 8)} gave up \u2014 parking until it leaves the processing list (cron reset)`,
|
|
3420
|
+
conversation_id: watcher.conv.id,
|
|
3421
|
+
message_id: evidentMessageId
|
|
3422
|
+
});
|
|
3423
|
+
}
|
|
2023
3424
|
watcher.inFlight.delete(evidentMessageId);
|
|
2024
3425
|
this.dispatched.delete(evidentMessageId);
|
|
2025
3426
|
}
|
|
@@ -2036,21 +3437,41 @@ var ChannelDriver = class {
|
|
|
2036
3437
|
* RUNNING (not done) is the one that paused. With one running message that is
|
|
2037
3438
|
* unambiguous; with several we prefer an explicit messageID match, else the
|
|
2038
3439
|
* oldest running message.
|
|
3440
|
+
*
|
|
3441
|
+
* Returns the set of in-flight Evident message ids that are paused awaiting a
|
|
3442
|
+
* human — an outstanding (still-open) question/permission is attributed to them.
|
|
3443
|
+
* `serviceInFlightMessage` uses this to keep an actively-running turn watched
|
|
3444
|
+
* forever (ADR-0047) while still bounding a turn merely blocked on a person who
|
|
3445
|
+
* may never answer. Attribution here covers ALL open interactions, not just
|
|
3446
|
+
* NEW (un-deduped) ones — a question stays "awaiting a human" until answered,
|
|
3447
|
+
* even after it was already surfaced to the channel.
|
|
2039
3448
|
*/
|
|
2040
3449
|
async pollInteractions(sessionId, watcher, messages) {
|
|
3450
|
+
const openQuestions = /* @__PURE__ */ new Set();
|
|
3451
|
+
const openPermissions = /* @__PURE__ */ new Set();
|
|
3452
|
+
let questionsPolledOk = true;
|
|
3453
|
+
let permissionsPolledOk = true;
|
|
2041
3454
|
let questions = [];
|
|
2042
3455
|
try {
|
|
2043
3456
|
const res = await this.fetchImpl(`${this.opencodeBase}/question`);
|
|
2044
3457
|
if (res.ok) {
|
|
2045
3458
|
const body = await res.json();
|
|
2046
|
-
|
|
3459
|
+
if (Array.isArray(body)) {
|
|
3460
|
+
questions = body;
|
|
3461
|
+
} else {
|
|
3462
|
+
questionsPolledOk = false;
|
|
3463
|
+
}
|
|
3464
|
+
} else {
|
|
3465
|
+
questionsPolledOk = false;
|
|
2047
3466
|
}
|
|
2048
3467
|
} catch {
|
|
3468
|
+
questionsPolledOk = false;
|
|
2049
3469
|
}
|
|
2050
3470
|
for (const q of questions) {
|
|
2051
|
-
if (q.sessionID
|
|
2052
|
-
if (watcher.reportedQuestions.has(q.id)) continue;
|
|
3471
|
+
if (!await this.sessionBelongsTo(q.sessionID, sessionId)) continue;
|
|
2053
3472
|
const paused = this.attributeInteraction(watcher, q.tool?.messageID, messages);
|
|
3473
|
+
if (paused) openQuestions.add(paused.evidentMessageId);
|
|
3474
|
+
if (watcher.reportedQuestions.has(q.id)) continue;
|
|
2054
3475
|
const reported = await this.reportInteraction(
|
|
2055
3476
|
watcher.conv.id,
|
|
2056
3477
|
"question",
|
|
@@ -2064,14 +3485,22 @@ var ChannelDriver = class {
|
|
|
2064
3485
|
const res = await this.fetchImpl(`${this.opencodeBase}/permission`);
|
|
2065
3486
|
if (res.ok) {
|
|
2066
3487
|
const body = await res.json();
|
|
2067
|
-
|
|
3488
|
+
if (Array.isArray(body)) {
|
|
3489
|
+
permissions = body;
|
|
3490
|
+
} else {
|
|
3491
|
+
permissionsPolledOk = false;
|
|
3492
|
+
}
|
|
3493
|
+
} else {
|
|
3494
|
+
permissionsPolledOk = false;
|
|
2068
3495
|
}
|
|
2069
3496
|
} catch {
|
|
3497
|
+
permissionsPolledOk = false;
|
|
2070
3498
|
}
|
|
2071
3499
|
for (const p of permissions) {
|
|
2072
|
-
if (p.sessionID
|
|
2073
|
-
if (watcher.reportedPermissions.has(p.id)) continue;
|
|
3500
|
+
if (!await this.sessionBelongsTo(p.sessionID, sessionId)) continue;
|
|
2074
3501
|
const paused = this.attributeInteraction(watcher, p.messageID, messages);
|
|
3502
|
+
if (paused) openPermissions.add(paused.evidentMessageId);
|
|
3503
|
+
if (watcher.reportedPermissions.has(p.id)) continue;
|
|
2075
3504
|
const reported = await this.reportInteraction(
|
|
2076
3505
|
watcher.conv.id,
|
|
2077
3506
|
"permission",
|
|
@@ -2080,6 +3509,173 @@ var ChannelDriver = class {
|
|
|
2080
3509
|
);
|
|
2081
3510
|
if (reported) watcher.reportedPermissions.add(p.id);
|
|
2082
3511
|
}
|
|
3512
|
+
return { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk };
|
|
3513
|
+
}
|
|
3514
|
+
/**
|
|
3515
|
+
* True when `sessionId` is the `rootSessionId` itself OR a descendant of it —
|
|
3516
|
+
* i.e. its `parentID` chain (resolved via `GET /session/:id`) reaches the
|
|
3517
|
+
* watched root. Sub-agents spawned via the `task` tool run in child sessions,
|
|
3518
|
+
* so their questions/permissions live under a different `sessionID` that must
|
|
3519
|
+
* still be attributed to the root conversation the watcher owns.
|
|
3520
|
+
*
|
|
3521
|
+
* Parents are cached in `sessionParents` so we walk each session at most once;
|
|
3522
|
+
* a bounded depth cap guards against a cycle or a pathological chain, and any
|
|
3523
|
+
* fetch failure is treated as "not a descendant" (best-effort — the interaction
|
|
3524
|
+
* simply isn't surfaced this tick and is retried next tick once resolvable).
|
|
3525
|
+
*/
|
|
3526
|
+
async sessionBelongsTo(sessionId, rootSessionId) {
|
|
3527
|
+
let current = sessionId;
|
|
3528
|
+
for (let depth = 0; current && depth < 32; depth++) {
|
|
3529
|
+
if (current === rootSessionId) return true;
|
|
3530
|
+
const parent = await this.resolveSessionParent(current);
|
|
3531
|
+
if (parent === null || parent === void 0) return false;
|
|
3532
|
+
current = parent;
|
|
3533
|
+
}
|
|
3534
|
+
return false;
|
|
3535
|
+
}
|
|
3536
|
+
/**
|
|
3537
|
+
* Resolve (and cache) a session's `parentID` via `GET /session/:id`. Returns
|
|
3538
|
+
* `null` for a root session (no parent) and `undefined` when opencode is
|
|
3539
|
+
* unreachable / the session can't be read (so the caller stops walking without
|
|
3540
|
+
* caching a wrong answer — the next tick retries).
|
|
3541
|
+
*/
|
|
3542
|
+
async resolveSessionParent(sessionId) {
|
|
3543
|
+
const cached = this.sessionParents.get(sessionId);
|
|
3544
|
+
if (cached !== void 0) return cached;
|
|
3545
|
+
let parent = void 0;
|
|
3546
|
+
try {
|
|
3547
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
|
|
3548
|
+
if (res.ok) {
|
|
3549
|
+
const body = await res.json();
|
|
3550
|
+
parent = body && typeof body.parentID === "string" ? body.parentID : null;
|
|
3551
|
+
}
|
|
3552
|
+
} catch {
|
|
3553
|
+
parent = void 0;
|
|
3554
|
+
}
|
|
3555
|
+
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3556
|
+
return parent;
|
|
3557
|
+
}
|
|
3558
|
+
/**
|
|
3559
|
+
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3560
|
+
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3561
|
+
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3562
|
+
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3563
|
+
* Best-effort:
|
|
3564
|
+
* - a resolved NON-EMPTY title is cached and terminal (a real session name
|
|
3565
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3566
|
+
* - while the title is still absent/empty we do NOT latch it — OpenCode names
|
|
3567
|
+
* sessions asynchronously mid-turn, so an early call (e.g. at `processing`)
|
|
3568
|
+
* must leave the cache unresolved and re-fetch on the next need so a later
|
|
3569
|
+
* call (e.g. at `done`) picks up the name assigned in the meantime. Such a
|
|
3570
|
+
* call returns `null` (omit the title on THIS PATCH) without caching;
|
|
3571
|
+
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3572
|
+
* and returns `null` — it must NEVER throw or block completion.
|
|
3573
|
+
* A failure is logged with agent/session context (no silent catch).
|
|
3574
|
+
*/
|
|
3575
|
+
async resolveSessionTitle(sessionId, conversationId) {
|
|
3576
|
+
const cached = this.sessionTitles.get(sessionId);
|
|
3577
|
+
if (cached != null) return cached;
|
|
3578
|
+
try {
|
|
3579
|
+
const res = await this.fetchImpl(`${this.opencodeBase}/session/${sessionId}`);
|
|
3580
|
+
if (res.ok) {
|
|
3581
|
+
const body = await res.json();
|
|
3582
|
+
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3583
|
+
if (title.length > 0) {
|
|
3584
|
+
this.sessionTitles.set(sessionId, title);
|
|
3585
|
+
return title;
|
|
3586
|
+
}
|
|
3587
|
+
return null;
|
|
3588
|
+
}
|
|
3589
|
+
this.log({
|
|
3590
|
+
level: "debug",
|
|
3591
|
+
message: `Session title fetch for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) returned HTTP ${res.status} \u2014 omitting title`,
|
|
3592
|
+
conversation_id: conversationId
|
|
3593
|
+
});
|
|
3594
|
+
} catch (err) {
|
|
3595
|
+
this.log({
|
|
3596
|
+
level: "debug",
|
|
3597
|
+
message: `Best-effort session title fetch failed for session ${sessionId.slice(0, 8)} (agent ${this.agentId.slice(0, 8)}) \u2014 omitting title: ${err instanceof Error ? err.message : String(err)}`,
|
|
3598
|
+
conversation_id: conversationId
|
|
3599
|
+
});
|
|
3600
|
+
}
|
|
3601
|
+
return null;
|
|
3602
|
+
}
|
|
3603
|
+
/**
|
|
3604
|
+
* DEFENSIVE cross-check for the restart-recovery path (WI-2): is any descendant
|
|
3605
|
+
* (`task` sub-agent) session under `rootSessionId` still genuinely doing work?
|
|
3606
|
+
*
|
|
3607
|
+
* The PRIMARY recovery trigger is "preamble-pinned on recovery ⇒ idle" — a
|
|
3608
|
+
* runner restart wipes OpenCode's in-memory `SessionStatus`/`Runner`, so a
|
|
3609
|
+
* completed `finish: "tool-calls"` root reply encountered during re-adoption is
|
|
3610
|
+
* idle by OpenCode's own definition and is re-dispatched. This method exists only
|
|
3611
|
+
* so the WI-3 caller can VETO that re-dispatch in the rare case a descendant is
|
|
3612
|
+
* provably in flight at the exact moment of recovery.
|
|
3613
|
+
*
|
|
3614
|
+
* "Alive" criterion (TIGHTENED): a descendant is alive only when it is PROVABLY,
|
|
3615
|
+
* ACTIVELY generating — its LAST message is an assistant still mid-generation
|
|
3616
|
+
* (`completed == null`, via `isSessionActivelyGenerating`). An
|
|
3617
|
+
* INCOMPLETE-BUT-NOT-GENERATING child — last message a user message, or a
|
|
3618
|
+
* completed `finish: "tool-calls"` step — is NOT alive after a restart (nothing
|
|
3619
|
+
* is generating once the runner is gone), so it does NOT veto. (This is
|
|
3620
|
+
* deliberately NOT `!isTurnComplete`, which also matches those dead-but-non-terminal
|
|
3621
|
+
* shapes and would falsely veto — re-hanging the very turn this path recovers.)
|
|
3622
|
+
*
|
|
3623
|
+
* Return contract (encoded so WI-3 need not re-derive it):
|
|
3624
|
+
* - `true` → a descendant is provably, actively generating (veto re-dispatch).
|
|
3625
|
+
* - `false` → descendants exist but none is actively generating (the restart
|
|
3626
|
+
* case), OR no descendant is found at all.
|
|
3627
|
+
* - `null` → liveness is INDETERMINATE (enumeration via `listSessions` failed).
|
|
3628
|
+
*
|
|
3629
|
+
* ⚠️ `null` (UNKNOWN) MUST NOT be treated as "alive": WI-3 treats `null` the same
|
|
3630
|
+
* as `false` and does NOT veto — a restart guarantees no live runner, so an
|
|
3631
|
+
* indeterminate cross-check almost always means "couldn't reach a child that no
|
|
3632
|
+
* longer exists". The inversion lives in the caller; this method just reports
|
|
3633
|
+
* true/false/null faithfully.
|
|
3634
|
+
*
|
|
3635
|
+
* VERIFY-BEFORE-DEPEND: we depend ONLY on (a) `parentID` from `GET /session/:id`
|
|
3636
|
+
* (already proven by the existing child-session interaction tests, via
|
|
3637
|
+
* `resolveSessionParent`/`sessionBelongsTo`) and (b) the child's own message-list
|
|
3638
|
+
* terminal state. We do NOT depend on any session-level `busy`/`idle` field —
|
|
3639
|
+
* there is none on `GET /session/:id`; OpenCode's busy state is in-memory
|
|
3640
|
+
* `SessionStatus` only.
|
|
3641
|
+
*/
|
|
3642
|
+
async isAnyDescendantSessionAlive(rootSessionId) {
|
|
3643
|
+
const sessions = await listSessions(this.port);
|
|
3644
|
+
if (!sessions) {
|
|
3645
|
+
this.log({
|
|
3646
|
+
level: "warn",
|
|
3647
|
+
message: `Re-adopt: could not enumerate sessions to cross-check descendant liveness for root ${rootSessionId} (listSessions failed) \u2014 treating child liveness as indeterminate`
|
|
3648
|
+
});
|
|
3649
|
+
return null;
|
|
3650
|
+
}
|
|
3651
|
+
for (const candidate of sessions) {
|
|
3652
|
+
if (!candidate?.id || candidate.id === rootSessionId) continue;
|
|
3653
|
+
if (!await this.sessionBelongsTo(candidate.id, rootSessionId)) continue;
|
|
3654
|
+
const childMsgs = await getSessionMessages(this.port, candidate.id);
|
|
3655
|
+
if (isSessionActivelyGenerating(childMsgs)) {
|
|
3656
|
+
return true;
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
return false;
|
|
3660
|
+
}
|
|
3661
|
+
/**
|
|
3662
|
+
* Cheap decision-telemetry label for a running row's LAST correlated reply
|
|
3663
|
+
* (WI-2 Task 2.2): which running SHAPE it is, for the status-gated recovery log.
|
|
3664
|
+
* - `b1` — the reply itself is still in flight (`time.completed == null`) —
|
|
3665
|
+
* the aborted-in-flight production bug after a restart.
|
|
3666
|
+
* - `b2` — a COMPLETED reply pinned running only by `finish === "tool-calls"`
|
|
3667
|
+
* (the sub-agent preamble — #253's shape).
|
|
3668
|
+
* - `other` — any other shape (defensive; a running row is normally b1 or b2).
|
|
3669
|
+
* Reads `info.time.completed` / `info.finish` (tolerating the legacy top-level
|
|
3670
|
+
* shape) directly rather than re-importing the module-private `completedOf`/
|
|
3671
|
+
* `finishOf` — this is a display label only, not a correctness predicate.
|
|
3672
|
+
*/
|
|
3673
|
+
replyCompletionShape(reply) {
|
|
3674
|
+
if (!reply) return "other";
|
|
3675
|
+
const completed = reply.info?.time?.completed ?? reply.time?.completed;
|
|
3676
|
+
if (completed == null) return "b1";
|
|
3677
|
+
const finish = reply.info?.finish ?? reply.finish;
|
|
3678
|
+
return finish === "tool-calls" ? "b2" : "other";
|
|
2083
3679
|
}
|
|
2084
3680
|
/**
|
|
2085
3681
|
* Attribute a surfaced interaction to the in-flight message it paused on (M-1).
|
|
@@ -2163,6 +3759,35 @@ var ChannelDriver = class {
|
|
|
2163
3759
|
}
|
|
2164
3760
|
return await res.json();
|
|
2165
3761
|
}
|
|
3762
|
+
/**
|
|
3763
|
+
* Fetch this agent's `processing` messages for re-adoption (ADR-0046, WI-1).
|
|
3764
|
+
* The pending path (`getPendingConversations`/`getPendingMessages`) only
|
|
3765
|
+
* surfaces `pending` rows, so a message already `processing` when the runner
|
|
3766
|
+
* died is invisible to it — this dedicated endpoint returns exactly those rows
|
|
3767
|
+
* with the fields the re-adopt path needs (`processed_at`,
|
|
3768
|
+
* `opencode_session_id`, routing).
|
|
3769
|
+
*
|
|
3770
|
+
* Response is an OBJECT WRAPPER `{ messages: [...] }` (snake_case) — NOT a bare
|
|
3771
|
+
* array. Propagates `ChannelAuthError` on 401/403; throws a plain `Error` on
|
|
3772
|
+
* other non-ok so `drainPending`'s try/finally leaves `draining` false and the
|
|
3773
|
+
* next tick retries.
|
|
3774
|
+
*/
|
|
3775
|
+
async getProcessingMessages() {
|
|
3776
|
+
const res = await this.fetchImpl(
|
|
3777
|
+
`${this.apiUrl}/agents/${this.agentId}/conversations/processing`,
|
|
3778
|
+
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3779
|
+
);
|
|
3780
|
+
this.assertAuth(res, "fetching processing messages");
|
|
3781
|
+
if (!res.ok) {
|
|
3782
|
+
throw new Error(`Failed to get processing messages: HTTP ${res.status}`);
|
|
3783
|
+
}
|
|
3784
|
+
const data = await res.json();
|
|
3785
|
+
let messages = data.messages ?? [];
|
|
3786
|
+
if (this.conversationFilter) {
|
|
3787
|
+
messages = messages.filter((m) => m.conversation_id === this.conversationFilter);
|
|
3788
|
+
}
|
|
3789
|
+
return messages;
|
|
3790
|
+
}
|
|
2166
3791
|
/**
|
|
2167
3792
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
2168
3793
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -2184,13 +3809,18 @@ var ChannelDriver = class {
|
|
|
2184
3809
|
* A single attempt (no internal retry): the watcher's per-tick loop is the
|
|
2185
3810
|
* retry vehicle for the swap-to-running.
|
|
2186
3811
|
*/
|
|
2187
|
-
async markProcessing(conversationId, messageId, sessionId) {
|
|
3812
|
+
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
2188
3813
|
const res = await this.fetchImpl(
|
|
2189
3814
|
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
2190
3815
|
{
|
|
2191
3816
|
method: "PATCH",
|
|
2192
3817
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
2193
|
-
body: JSON.stringify({
|
|
3818
|
+
body: JSON.stringify({
|
|
3819
|
+
status: "processing",
|
|
3820
|
+
opencode_session_id: sessionId,
|
|
3821
|
+
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3822
|
+
...title ? { title } : {}
|
|
3823
|
+
})
|
|
2194
3824
|
}
|
|
2195
3825
|
);
|
|
2196
3826
|
this.assertAuth(res, "marking message as processing");
|
|
@@ -2228,13 +3858,18 @@ var ChannelDriver = class {
|
|
|
2228
3858
|
* watcher retries next tick within the
|
|
2229
3859
|
* deadline, Finding 4).
|
|
2230
3860
|
*/
|
|
2231
|
-
async markDone(conversationId, messageId, sessionId) {
|
|
3861
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
2232
3862
|
const res = await this.fetchImpl(
|
|
2233
3863
|
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
2234
3864
|
{
|
|
2235
3865
|
method: "PATCH",
|
|
2236
3866
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
2237
|
-
body: JSON.stringify({
|
|
3867
|
+
body: JSON.stringify({
|
|
3868
|
+
status: "done",
|
|
3869
|
+
opencode_session_id: sessionId,
|
|
3870
|
+
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3871
|
+
...title ? { title } : {}
|
|
3872
|
+
})
|
|
2238
3873
|
}
|
|
2239
3874
|
);
|
|
2240
3875
|
this.assertAuth(res, "marking message as done");
|
|
@@ -2244,7 +3879,17 @@ var ChannelDriver = class {
|
|
|
2244
3879
|
}
|
|
2245
3880
|
throw new ChannelTerminalError(`marking message as done: HTTP ${res.status}`, res.status);
|
|
2246
3881
|
}
|
|
2247
|
-
|
|
3882
|
+
/**
|
|
3883
|
+
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3884
|
+
* when provided (issue #182): a bare `markFailed(conv, msg)` sends
|
|
3885
|
+
* `{status:'failed'}` unchanged (the dispatch-failure path), while an errored
|
|
3886
|
+
* OpenCode turn sends `{status:'failed', opencode_session_id, error}` so the
|
|
3887
|
+
* failure reason reaches the channel.
|
|
3888
|
+
*/
|
|
3889
|
+
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
3890
|
+
const body = { status: "failed" };
|
|
3891
|
+
if (sessionId !== void 0) body.opencode_session_id = sessionId;
|
|
3892
|
+
if (error2 !== void 0) body.error = error2;
|
|
2248
3893
|
await this.callWithRetry(
|
|
2249
3894
|
"marking message as failed",
|
|
2250
3895
|
() => this.fetchImpl(
|
|
@@ -2252,11 +3897,56 @@ var ChannelDriver = class {
|
|
|
2252
3897
|
{
|
|
2253
3898
|
method: "PATCH",
|
|
2254
3899
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
2255
|
-
body: JSON.stringify(
|
|
3900
|
+
body: JSON.stringify(body)
|
|
2256
3901
|
}
|
|
2257
3902
|
)
|
|
2258
3903
|
);
|
|
2259
3904
|
}
|
|
3905
|
+
/**
|
|
3906
|
+
* Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
|
|
3907
|
+
* (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
|
|
3908
|
+
* — the server records it via `log()` (no DB write, no notification). This is
|
|
3909
|
+
* fire-and-forget: it MUST NEVER throw into the drain or the watcher tick, and
|
|
3910
|
+
* MUST NOT use `callWithRetry` (a telemetry ping must not block the sequential
|
|
3911
|
+
* watcher tick — one attempt is enough). A failure is SWALLOWED but LOGGED with
|
|
3912
|
+
* context (no silent catch, per development-workflow).
|
|
3913
|
+
*
|
|
3914
|
+
* Returns whether the POST SUCCEEDED (2xx). Most callers ignore this (pure
|
|
3915
|
+
* telemetry), but the `paused` liveness-clear uses it to know whether to
|
|
3916
|
+
* RE-ASSERT on a later tick — a single dropped `paused` POST must not leave a
|
|
3917
|
+
* stale `last_seen_alive_at` on a still-paused row (Bugbot "Failed paused signal
|
|
3918
|
+
* leaves liveness").
|
|
3919
|
+
*/
|
|
3920
|
+
async postSignal(conversationId, messageId, signal, extra) {
|
|
3921
|
+
try {
|
|
3922
|
+
const res = await this.fetchImpl(
|
|
3923
|
+
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3924
|
+
{
|
|
3925
|
+
method: "POST",
|
|
3926
|
+
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3927
|
+
body: JSON.stringify({ signal, ...extra })
|
|
3928
|
+
}
|
|
3929
|
+
);
|
|
3930
|
+
if (!res.ok) {
|
|
3931
|
+
this.log({
|
|
3932
|
+
level: "warn",
|
|
3933
|
+
message: `Signal '${signal}' for message ${messageId.slice(0, 8)} returned HTTP ${res.status} (telemetry-only, ignored)`,
|
|
3934
|
+
conversation_id: conversationId,
|
|
3935
|
+
message_id: messageId
|
|
3936
|
+
});
|
|
3937
|
+
return false;
|
|
3938
|
+
}
|
|
3939
|
+
return true;
|
|
3940
|
+
} catch (err) {
|
|
3941
|
+
this.log({
|
|
3942
|
+
level: "warn",
|
|
3943
|
+
message: `Signal '${signal}' for message ${messageId.slice(0, 8)} failed (telemetry-only, ignored): ${err instanceof Error ? err.message : String(err)}`,
|
|
3944
|
+
conversation_id: conversationId,
|
|
3945
|
+
message_id: messageId
|
|
3946
|
+
});
|
|
3947
|
+
return false;
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
2260
3950
|
async persistSession(conversationId, sessionId) {
|
|
2261
3951
|
const res = await this.fetchImpl(
|
|
2262
3952
|
`${this.apiUrl}/agents/${this.agentId}/threads/${conversationId}`,
|
|
@@ -2527,6 +4217,25 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
2527
4217
|
return { error: `Failed to resolve agent from key: ${message}` };
|
|
2528
4218
|
}
|
|
2529
4219
|
}
|
|
4220
|
+
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4221
|
+
const apiUrl = getApiUrlConfig();
|
|
4222
|
+
try {
|
|
4223
|
+
const response = await fetch(`${apiUrl}/agents/${agentId}/disconnect`, {
|
|
4224
|
+
method: "POST",
|
|
4225
|
+
headers: { Authorization: authHeader }
|
|
4226
|
+
});
|
|
4227
|
+
if (!response.ok) {
|
|
4228
|
+
const serverMessage = await readErrorMessage(response);
|
|
4229
|
+
return {
|
|
4230
|
+
ok: false,
|
|
4231
|
+
error: `HTTP ${response.status}${serverMessage ? `: ${serverMessage}` : ""}`
|
|
4232
|
+
};
|
|
4233
|
+
}
|
|
4234
|
+
return { ok: true };
|
|
4235
|
+
} catch (error2) {
|
|
4236
|
+
return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
|
|
4237
|
+
}
|
|
4238
|
+
}
|
|
2530
4239
|
async function getAgentInfo(agentId, authHeader) {
|
|
2531
4240
|
const apiUrl = getApiUrlConfig();
|
|
2532
4241
|
try {
|
|
@@ -2572,23 +4281,55 @@ async function getAgentInfo(agentId, authHeader) {
|
|
|
2572
4281
|
// src/commands/run.ts
|
|
2573
4282
|
var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
2574
4283
|
var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
|
|
2575
|
-
|
|
4284
|
+
var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
|
|
4285
|
+
var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
|
|
4286
|
+
function resolveLogLevel(options) {
|
|
4287
|
+
const accepted = Object.keys(LOG_LEVELS);
|
|
4288
|
+
const validate = (value, source) => {
|
|
4289
|
+
const normalized = value.trim().toLowerCase();
|
|
4290
|
+
if (!accepted.includes(normalized)) {
|
|
4291
|
+
throw new Error(
|
|
4292
|
+
`Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
|
|
4293
|
+
);
|
|
4294
|
+
}
|
|
4295
|
+
return normalized;
|
|
4296
|
+
};
|
|
4297
|
+
if (options.logLevel !== void 0) {
|
|
4298
|
+
return validate(options.logLevel, " (--log-level)");
|
|
4299
|
+
}
|
|
4300
|
+
if (options.verbose) {
|
|
4301
|
+
return "debug";
|
|
4302
|
+
}
|
|
4303
|
+
const env = process.env.EVIDENT_LOG_LEVEL;
|
|
4304
|
+
if (env !== void 0 && env !== "") {
|
|
4305
|
+
return validate(env, " (EVIDENT_LOG_LEVEL)");
|
|
4306
|
+
}
|
|
4307
|
+
return "info";
|
|
4308
|
+
}
|
|
4309
|
+
function meetsThreshold(state, level) {
|
|
4310
|
+
return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
|
|
4311
|
+
}
|
|
4312
|
+
function log2(state, message, level = "info") {
|
|
4313
|
+
if (!meetsThreshold(state, level)) return;
|
|
2576
4314
|
if (state.json) {
|
|
2577
4315
|
console.log(
|
|
2578
4316
|
JSON.stringify({
|
|
2579
4317
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2580
|
-
level
|
|
4318
|
+
level,
|
|
2581
4319
|
message
|
|
2582
4320
|
})
|
|
2583
4321
|
);
|
|
2584
4322
|
} else if (!state.interactive) {
|
|
2585
|
-
const prefix =
|
|
4323
|
+
const prefix = level === "error" ? chalk6.red("\u2717") : level === "warn" ? chalk6.yellow("!") : level === "debug" ? chalk6.dim("\xB7") : chalk6.green("\u2022");
|
|
2586
4324
|
console.log(`${prefix} ${message}`);
|
|
2587
4325
|
}
|
|
2588
4326
|
}
|
|
2589
4327
|
function logActivity(state, entry) {
|
|
4328
|
+
const level = entry.level ?? (entry.type === "error" ? "error" : "info");
|
|
4329
|
+
if (!meetsThreshold(state, level)) return;
|
|
2590
4330
|
const fullEntry = {
|
|
2591
4331
|
...entry,
|
|
4332
|
+
level,
|
|
2592
4333
|
timestamp: /* @__PURE__ */ new Date()
|
|
2593
4334
|
};
|
|
2594
4335
|
state.activityLog.push(fullEntry);
|
|
@@ -2597,9 +4338,9 @@ function logActivity(state, entry) {
|
|
|
2597
4338
|
}
|
|
2598
4339
|
if (!state.interactive) {
|
|
2599
4340
|
if (entry.type === "error") {
|
|
2600
|
-
log2(state, entry.error ?? "Unknown error",
|
|
2601
|
-
} else if (entry.
|
|
2602
|
-
log2(state, entry.message);
|
|
4341
|
+
log2(state, entry.error ?? "Unknown error", level);
|
|
4342
|
+
} else if (entry.message) {
|
|
4343
|
+
log2(state, entry.message, level);
|
|
2603
4344
|
}
|
|
2604
4345
|
}
|
|
2605
4346
|
}
|
|
@@ -2685,6 +4426,7 @@ async function handleAuthError(state, error2) {
|
|
|
2685
4426
|
}
|
|
2686
4427
|
async function driveChannels(state, driver) {
|
|
2687
4428
|
let idlePolls = 0;
|
|
4429
|
+
let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
2688
4430
|
while (state.running) {
|
|
2689
4431
|
if (state.connection?.reconnecting && state.connection.reconnectPromise) {
|
|
2690
4432
|
logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
|
|
@@ -2694,7 +4436,9 @@ async function driveChannels(state, driver) {
|
|
|
2694
4436
|
try {
|
|
2695
4437
|
const processed = await driver.drainPending();
|
|
2696
4438
|
state.messageCount += processed;
|
|
2697
|
-
|
|
4439
|
+
const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
|
|
4440
|
+
lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
|
|
4441
|
+
if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
|
|
2698
4442
|
idlePolls = 0;
|
|
2699
4443
|
if (processed > 0 && state.interactive) displayStatus(state);
|
|
2700
4444
|
} else if (state.idleTimeout !== null) {
|
|
@@ -2723,7 +4467,7 @@ async function driveChannels(state, driver) {
|
|
|
2723
4467
|
logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
|
|
2724
4468
|
if (state.interactive) displayStatus(state);
|
|
2725
4469
|
}
|
|
2726
|
-
await new Promise((
|
|
4470
|
+
await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
|
|
2727
4471
|
if (state.idleTimeout !== null && idlePolls >= 2) {
|
|
2728
4472
|
const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
|
|
2729
4473
|
if (idleMs > state.idleTimeout * 1e3) {
|
|
@@ -2734,8 +4478,122 @@ async function driveChannels(state, driver) {
|
|
|
2734
4478
|
}
|
|
2735
4479
|
}
|
|
2736
4480
|
}
|
|
2737
|
-
|
|
4481
|
+
var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
|
|
4482
|
+
async function runSweep(state, driver, config2) {
|
|
4483
|
+
const mode = `age=${config2.maxAgeMs ?? "\u2014"} count=${config2.maxCount ?? "\u2014"}`;
|
|
4484
|
+
try {
|
|
4485
|
+
const sessions = await listSessions(state.port);
|
|
4486
|
+
if (sessions === null) {
|
|
4487
|
+
logActivity(state, {
|
|
4488
|
+
type: "info",
|
|
4489
|
+
message: `Session cleanup: could not list sessions (opencode unreachable); skipping this sweep (${mode})`
|
|
4490
|
+
});
|
|
4491
|
+
return;
|
|
4492
|
+
}
|
|
4493
|
+
const toDelete = selectSessionsToDelete(
|
|
4494
|
+
sessions.map((s) => ({ id: s.id, lastActivityMs: sessionLastActivityMs(s) })),
|
|
4495
|
+
{
|
|
4496
|
+
maxAgeMs: config2.maxAgeMs,
|
|
4497
|
+
maxCount: config2.maxCount,
|
|
4498
|
+
nowMs: Date.now(),
|
|
4499
|
+
protectedIds: driver.protectedSessionIds()
|
|
4500
|
+
}
|
|
4501
|
+
);
|
|
4502
|
+
const protectedNow = driver.protectedSessionIds();
|
|
4503
|
+
let deleted = 0;
|
|
4504
|
+
let failed = 0;
|
|
4505
|
+
let skippedNewlyActive = 0;
|
|
4506
|
+
for (const id of toDelete) {
|
|
4507
|
+
if (protectedNow.has(id)) {
|
|
4508
|
+
skippedNewlyActive++;
|
|
4509
|
+
logActivity(state, {
|
|
4510
|
+
type: "info",
|
|
4511
|
+
message: `Session cleanup: skipping ${id} \u2014 became active/bound after selection (${mode})`
|
|
4512
|
+
});
|
|
4513
|
+
continue;
|
|
4514
|
+
}
|
|
4515
|
+
if (await deleteSession(state.port, id)) deleted++;
|
|
4516
|
+
else failed++;
|
|
4517
|
+
}
|
|
4518
|
+
const failedNote = failed > 0 ? `, failed ${failed}` : "";
|
|
4519
|
+
const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
|
|
4520
|
+
logActivity(state, {
|
|
4521
|
+
type: "info",
|
|
4522
|
+
message: `Session cleanup: inspected ${sessions.length}, deleted ${deleted}${failedNote}${skippedNote} (${mode})`
|
|
4523
|
+
});
|
|
4524
|
+
} catch (error2) {
|
|
4525
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4526
|
+
logActivity(state, {
|
|
4527
|
+
type: "error",
|
|
4528
|
+
error: `Session cleanup sweep failed (non-fatal, ${mode}): ${message}`
|
|
4529
|
+
});
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
function scheduleSessionCleanup(state, driver, options) {
|
|
4533
|
+
const config2 = resolveSessionCleanupConfig(
|
|
4534
|
+
{
|
|
4535
|
+
maxAge: options.sessionCleanupMaxAge,
|
|
4536
|
+
maxCount: options.sessionCleanupMaxCount,
|
|
4537
|
+
interval: options.sessionCleanupInterval
|
|
4538
|
+
},
|
|
4539
|
+
process.env
|
|
4540
|
+
);
|
|
4541
|
+
for (const warning2 of config2.warnings) {
|
|
4542
|
+
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
4543
|
+
}
|
|
4544
|
+
if (!config2.enabled) return;
|
|
4545
|
+
logActivity(state, {
|
|
4546
|
+
type: "info",
|
|
4547
|
+
message: `Session cleanup enabled (age=${config2.maxAgeMs ?? "\u2014"}, count=${config2.maxCount ?? "\u2014"}, interval=${config2.intervalMs}ms)`
|
|
4548
|
+
});
|
|
4549
|
+
const interval = setInterval(() => void runSweep(state, driver, config2), config2.intervalMs);
|
|
4550
|
+
const firstSweep = setTimeout(
|
|
4551
|
+
() => void runSweep(state, driver, config2),
|
|
4552
|
+
SESSION_CLEANUP_FIRST_SWEEP_MS
|
|
4553
|
+
);
|
|
4554
|
+
state.sessionCleanupTimers.push(interval, firstSweep);
|
|
4555
|
+
}
|
|
4556
|
+
async function notifyOffline(state) {
|
|
4557
|
+
if (!state.agentId || !state.authHeader) return;
|
|
4558
|
+
if (!state.connected) {
|
|
4559
|
+
log2(state, "Skipping offline signal \u2014 this runner does not hold the live tunnel");
|
|
4560
|
+
return;
|
|
4561
|
+
}
|
|
4562
|
+
const result = await notifyAgentDisconnected(state.agentId, state.authHeader);
|
|
4563
|
+
if (result.ok) {
|
|
4564
|
+
log2(state, "Notified Evident the agent is going offline");
|
|
4565
|
+
} else {
|
|
4566
|
+
logActivity(state, {
|
|
4567
|
+
type: "error",
|
|
4568
|
+
error: `Could not notify Evident of offline status (relay will still report it): ${result.error}`
|
|
4569
|
+
});
|
|
4570
|
+
if (state.interactive) displayStatus(state);
|
|
4571
|
+
}
|
|
4572
|
+
}
|
|
4573
|
+
async function cleanup(state, opts = {}) {
|
|
2738
4574
|
state.running = false;
|
|
4575
|
+
for (const timer of state.sessionCleanupTimers) {
|
|
4576
|
+
clearInterval(timer);
|
|
4577
|
+
clearTimeout(timer);
|
|
4578
|
+
}
|
|
4579
|
+
state.sessionCleanupTimers = [];
|
|
4580
|
+
if (opts.graceful && state.channelDriver) {
|
|
4581
|
+
state.channelDriver.stop();
|
|
4582
|
+
log2(state, "Draining in-flight channel work before shutdown...");
|
|
4583
|
+
if (state.interactive) {
|
|
4584
|
+
logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
|
|
4585
|
+
displayStatus(state);
|
|
4586
|
+
}
|
|
4587
|
+
const settled = await state.channelDriver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS);
|
|
4588
|
+
if (!settled) {
|
|
4589
|
+
logActivity(state, {
|
|
4590
|
+
type: "info",
|
|
4591
|
+
message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
|
|
4592
|
+
});
|
|
4593
|
+
if (state.interactive) displayStatus(state);
|
|
4594
|
+
}
|
|
4595
|
+
}
|
|
4596
|
+
await notifyOffline(state);
|
|
2739
4597
|
if (state.connection) {
|
|
2740
4598
|
state.connection.close();
|
|
2741
4599
|
state.connection = null;
|
|
@@ -2753,6 +4611,20 @@ async function cleanup(state) {
|
|
|
2753
4611
|
}
|
|
2754
4612
|
async function run(options) {
|
|
2755
4613
|
const interactive = isInteractive(options.json);
|
|
4614
|
+
let logLevel;
|
|
4615
|
+
try {
|
|
4616
|
+
logLevel = resolveLogLevel(options);
|
|
4617
|
+
} catch (error2) {
|
|
4618
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
4619
|
+
if (options.json) {
|
|
4620
|
+
console.log(JSON.stringify({ status: "error", error: message }));
|
|
4621
|
+
} else {
|
|
4622
|
+
printError(message);
|
|
4623
|
+
}
|
|
4624
|
+
await shutdownTelemetry();
|
|
4625
|
+
process.exit(1);
|
|
4626
|
+
return;
|
|
4627
|
+
}
|
|
2756
4628
|
const state = {
|
|
2757
4629
|
agentId: options.agent || "",
|
|
2758
4630
|
agentName: null,
|
|
@@ -2761,31 +4633,38 @@ async function run(options) {
|
|
|
2761
4633
|
idleTimeout: options.idleTimeout ?? null,
|
|
2762
4634
|
json: options.json ?? false,
|
|
2763
4635
|
interactive,
|
|
4636
|
+
logLevel,
|
|
2764
4637
|
connected: false,
|
|
2765
4638
|
opencodeConnected: false,
|
|
2766
4639
|
opencodeVersion: null,
|
|
2767
4640
|
opencodeProcess: null,
|
|
2768
4641
|
connection: null,
|
|
4642
|
+
channelDriver: null,
|
|
2769
4643
|
running: true,
|
|
4644
|
+
shuttingDown: false,
|
|
2770
4645
|
activityLog: [],
|
|
2771
4646
|
messageCount: 0,
|
|
4647
|
+
lastProxiedActivityAt: null,
|
|
4648
|
+
sessionCleanupTimers: [],
|
|
2772
4649
|
authHeader: ""
|
|
2773
4650
|
};
|
|
2774
4651
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
2775
4652
|
log2(
|
|
2776
4653
|
state,
|
|
2777
|
-
"
|
|
2778
|
-
|
|
4654
|
+
"No --idle-timeout set in CI environment. The runner will poll indefinitely until the job times out. Consider adding --idle-timeout 30 to avoid wasting runner minutes.",
|
|
4655
|
+
"warn"
|
|
2779
4656
|
);
|
|
2780
4657
|
}
|
|
2781
4658
|
const handleSignal = async () => {
|
|
4659
|
+
if (state.shuttingDown) return;
|
|
4660
|
+
state.shuttingDown = true;
|
|
2782
4661
|
if (state.interactive) {
|
|
2783
4662
|
logActivity(state, { type: "info", message: "Shutting down..." });
|
|
2784
4663
|
displayStatus(state);
|
|
2785
4664
|
} else {
|
|
2786
4665
|
log2(state, "Shutting down...");
|
|
2787
4666
|
}
|
|
2788
|
-
await cleanup(state);
|
|
4667
|
+
await cleanup(state, { graceful: true });
|
|
2789
4668
|
await shutdownTelemetry();
|
|
2790
4669
|
process.exit(0);
|
|
2791
4670
|
};
|
|
@@ -2885,13 +4764,13 @@ async function run(options) {
|
|
|
2885
4764
|
state.opencodeProcess = oc.process;
|
|
2886
4765
|
state.opencodeVersion = oc.version;
|
|
2887
4766
|
state.opencodeConnected = oc.process !== null || oc.version !== null;
|
|
2888
|
-
const
|
|
2889
|
-
ocSpinner?.succeed(`OpenCode running on port ${state.port}${
|
|
4767
|
+
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
4768
|
+
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
2890
4769
|
const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
|
|
2891
4770
|
if (versionWarning) {
|
|
2892
|
-
log2(state, versionWarning,
|
|
4771
|
+
log2(state, versionWarning, "warn");
|
|
2893
4772
|
if (state.interactive && !state.json) {
|
|
2894
|
-
logActivity(state, { type: "info", message: versionWarning });
|
|
4773
|
+
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
2895
4774
|
}
|
|
2896
4775
|
}
|
|
2897
4776
|
} catch (error2) {
|
|
@@ -2905,12 +4784,20 @@ async function run(options) {
|
|
|
2905
4784
|
apiUrl: getApiUrlConfig(),
|
|
2906
4785
|
getAuthHeader: () => state.authHeader,
|
|
2907
4786
|
conversationFilter: state.conversationFilter,
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
4787
|
+
stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
|
|
4788
|
+
log: (entry) => (
|
|
4789
|
+
// Thread the driver's real level straight through so `debug`/`warn`
|
|
4790
|
+
// survive the sink filter (they no longer collapse to info). `type`
|
|
4791
|
+
// stays the coarse error/non-error split the activity log renders with.
|
|
4792
|
+
logActivity(state, {
|
|
4793
|
+
type: entry.level === "error" ? "error" : "info",
|
|
4794
|
+
level: entry.level,
|
|
4795
|
+
message: entry.message,
|
|
4796
|
+
error: entry.level === "error" ? entry.message : void 0
|
|
4797
|
+
})
|
|
4798
|
+
)
|
|
2913
4799
|
});
|
|
4800
|
+
state.channelDriver = channelDriver;
|
|
2914
4801
|
const connection = new RunnerConnection({
|
|
2915
4802
|
agentId: state.agentId,
|
|
2916
4803
|
getAuthHeader: () => state.authHeader,
|
|
@@ -2924,7 +4811,11 @@ async function run(options) {
|
|
|
2924
4811
|
type: "info",
|
|
2925
4812
|
message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (agent: ${agentId})`
|
|
2926
4813
|
});
|
|
2927
|
-
emitAgentConnected(state.agentId, {
|
|
4814
|
+
emitAgentConnected(state.agentId, {
|
|
4815
|
+
port: state.port,
|
|
4816
|
+
cli_version: getCliVersion(),
|
|
4817
|
+
opencode_version: state.opencodeVersion
|
|
4818
|
+
});
|
|
2928
4819
|
if (!isReconnect) tunnelSpinner?.succeed("Tunnel connected");
|
|
2929
4820
|
if (state.interactive) displayStatus(state);
|
|
2930
4821
|
channelDriver.drainPending().then((processed) => {
|
|
@@ -2958,9 +4849,14 @@ async function run(options) {
|
|
|
2958
4849
|
logActivity(state, { type: "error", error: error2 });
|
|
2959
4850
|
if (state.interactive) displayStatus(state);
|
|
2960
4851
|
},
|
|
2961
|
-
// Web traffic is proxied transparently;
|
|
4852
|
+
// Web traffic is proxied transparently; note opencode is live and stamp
|
|
4853
|
+
// proxied activity so the idle loop treats interactive proxy use as work.
|
|
4854
|
+
// Fires per forwarded response head (incl. every SSE open) and excludes
|
|
4855
|
+
// the internal drain-ping, so an actively-used proxy keeps the timer
|
|
4856
|
+
// fresh while a lone idle SSE with no follow-up requests still ages out.
|
|
2962
4857
|
onResponse: () => {
|
|
2963
4858
|
state.opencodeConnected = true;
|
|
4859
|
+
state.lastProxiedActivityAt = Date.now();
|
|
2964
4860
|
},
|
|
2965
4861
|
// A channel message was queued and the api-worker pinged us over the
|
|
2966
4862
|
// tunnel to drain immediately instead of waiting for the next poll tick.
|
|
@@ -2998,10 +4894,12 @@ async function run(options) {
|
|
|
2998
4894
|
if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
|
|
2999
4895
|
throw error2;
|
|
3000
4896
|
}
|
|
4897
|
+
scheduleSessionCleanup(state, channelDriver, options);
|
|
3001
4898
|
if (!interactive || state.json) {
|
|
3002
4899
|
log2(state, "Driving channel messages...");
|
|
3003
4900
|
}
|
|
3004
4901
|
await driveChannels(state, channelDriver);
|
|
4902
|
+
if (state.shuttingDown) return;
|
|
3005
4903
|
await cleanup(state);
|
|
3006
4904
|
if (state.json) {
|
|
3007
4905
|
console.log(
|
|
@@ -3016,6 +4914,7 @@ async function run(options) {
|
|
|
3016
4914
|
await shutdownTelemetry();
|
|
3017
4915
|
process.exit(0);
|
|
3018
4916
|
} catch (error2) {
|
|
4917
|
+
if (state.shuttingDown) return;
|
|
3019
4918
|
await cleanup(state);
|
|
3020
4919
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
3021
4920
|
if (state.json) {
|
|
@@ -3033,8 +4932,9 @@ async function run(options) {
|
|
|
3033
4932
|
}
|
|
3034
4933
|
|
|
3035
4934
|
// src/index.ts
|
|
4935
|
+
var { version } = createRequire(import.meta.url)("../package.json");
|
|
3036
4936
|
var program = new Command();
|
|
3037
|
-
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(
|
|
4937
|
+
program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
|
|
3038
4938
|
"--endpoint <url>",
|
|
3039
4939
|
"Evident API base URL (default: production; e.g. http://localhost:3001)"
|
|
3040
4940
|
).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
|
|
@@ -3049,15 +4949,34 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
3049
4949
|
program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
|
|
3050
4950
|
program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
|
|
3051
4951
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
3052
|
-
program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Agent ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4952
|
+
program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Agent ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4953
|
+
"--log-level <level>",
|
|
4954
|
+
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4955
|
+
).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").option(
|
|
4956
|
+
"--session-cleanup-max-age <duration>",
|
|
4957
|
+
"Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
|
|
4958
|
+
).option(
|
|
4959
|
+
"--session-cleanup-max-count <n>",
|
|
4960
|
+
"Keep only the newest N OpenCode sessions. Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_COUNT"
|
|
4961
|
+
).option(
|
|
4962
|
+
"--session-cleanup-interval <duration>",
|
|
4963
|
+
"How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
|
|
4964
|
+
).action(
|
|
3053
4965
|
(options) => {
|
|
3054
4966
|
run({
|
|
3055
4967
|
agent: options.agent,
|
|
3056
4968
|
port: parseInt(options.port, 10),
|
|
4969
|
+
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4970
|
+
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|
|
4971
|
+
logLevel: options.logLevel,
|
|
3057
4972
|
verbose: options.verbose,
|
|
3058
4973
|
conversation: options.conversation,
|
|
3059
4974
|
idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
|
|
3060
|
-
json: options.json
|
|
4975
|
+
json: options.json,
|
|
4976
|
+
// Raw strings — the resolver in run.ts single-sources parsing (M1).
|
|
4977
|
+
sessionCleanupMaxAge: options.sessionCleanupMaxAge,
|
|
4978
|
+
sessionCleanupMaxCount: options.sessionCleanupMaxCount,
|
|
4979
|
+
sessionCleanupInterval: options.sessionCleanupInterval
|
|
3061
4980
|
});
|
|
3062
4981
|
}
|
|
3063
4982
|
);
|