@evident-ai/cli 3.1.1-dev.702ee74 → 3.1.1-dev.7a5732a
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 +10 -4
- package/dist/index.js +445 -72
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -499,6 +499,12 @@ function log(level, event, fields) {
|
|
|
499
499
|
);
|
|
500
500
|
}
|
|
501
501
|
}
|
|
502
|
+
function errorFields(err) {
|
|
503
|
+
if (err instanceof Error) {
|
|
504
|
+
return { error: err.message, error_name: err.name };
|
|
505
|
+
}
|
|
506
|
+
return { error: String(err) };
|
|
507
|
+
}
|
|
502
508
|
function stripQuery(url) {
|
|
503
509
|
try {
|
|
504
510
|
return new URL(url).pathname;
|
|
@@ -645,14 +651,27 @@ var EventTypes = {
|
|
|
645
651
|
// CLI lifecycle
|
|
646
652
|
CLI_STARTED: "cli.started",
|
|
647
653
|
CLI_COMMAND: "cli.command",
|
|
648
|
-
CLI_ERROR: "cli.error"
|
|
654
|
+
CLI_ERROR: "cli.error",
|
|
655
|
+
// Deprecation telemetry (#412) — usage of the old `--agent`/`EVIDENT_AGENT_KEY`
|
|
656
|
+
// names instead of the preferred `--runner`/`EVIDENT_RUNNER_KEY` (#409).
|
|
657
|
+
DEPRECATED_AGENT_FLAG_USED: "cli.deprecated_agent_flag_used",
|
|
658
|
+
DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
|
|
649
659
|
};
|
|
650
660
|
|
|
651
661
|
// src/lib/auth.ts
|
|
652
662
|
async function getAuthCredentials() {
|
|
663
|
+
const runnerKey = process.env.EVIDENT_RUNNER_KEY;
|
|
653
664
|
const agentKey = process.env.EVIDENT_AGENT_KEY;
|
|
665
|
+
if (runnerKey) {
|
|
666
|
+
return {
|
|
667
|
+
token: runnerKey,
|
|
668
|
+
authType: "agent_key",
|
|
669
|
+
keySource: "runner_key",
|
|
670
|
+
notice: agentKey ? "Both EVIDENT_RUNNER_KEY and EVIDENT_AGENT_KEY are set; using EVIDENT_RUNNER_KEY." : void 0
|
|
671
|
+
};
|
|
672
|
+
}
|
|
654
673
|
if (agentKey) {
|
|
655
|
-
return { token: agentKey, authType: "agent_key" };
|
|
674
|
+
return { token: agentKey, authType: "agent_key", keySource: "agent_key" };
|
|
656
675
|
}
|
|
657
676
|
const userToken = process.env.EVIDENT_TOKEN;
|
|
658
677
|
if (userToken) {
|
|
@@ -721,7 +740,7 @@ function buildOpenCodeVersionWarning(version2) {
|
|
|
721
740
|
if (isQueueValidatedVersion(version2)) return null;
|
|
722
741
|
const detected = version2 ? `v${version2}` : "unknown";
|
|
723
742
|
const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
|
|
724
|
-
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack
|
|
743
|
+
return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) 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.`;
|
|
725
744
|
}
|
|
726
745
|
|
|
727
746
|
// src/lib/opencode/process.ts
|
|
@@ -1013,6 +1032,12 @@ async function promptOpenCodeInstall(interactive) {
|
|
|
1013
1032
|
return action;
|
|
1014
1033
|
}
|
|
1015
1034
|
|
|
1035
|
+
// src/lib/opencode/provider-check.ts
|
|
1036
|
+
function buildNoProviderWarning(hasProvider) {
|
|
1037
|
+
if (hasProvider !== false) return null;
|
|
1038
|
+
return "Warning: opencode has no authenticated model provider configured, so it won't be able to answer prompts. Run `opencode auth login` to set one up (see https://opencode.ai for details).";
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1016
1041
|
// src/lib/opencode/session.ts
|
|
1017
1042
|
function opencodeBase(port) {
|
|
1018
1043
|
return `http://127.0.0.1:${port}`;
|
|
@@ -1215,6 +1240,11 @@ async function getModelAttachmentCapability(port, model) {
|
|
|
1215
1240
|
}
|
|
1216
1241
|
const entry = provider.models[modelId];
|
|
1217
1242
|
if (!entry || typeof entry !== "object") return null;
|
|
1243
|
+
if (entry.capabilities && typeof entry.capabilities === "object") {
|
|
1244
|
+
if (typeof entry.capabilities.attachment === "boolean") {
|
|
1245
|
+
return entry.capabilities.attachment;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1218
1248
|
return typeof entry.attachment === "boolean" ? entry.attachment : null;
|
|
1219
1249
|
} catch (err) {
|
|
1220
1250
|
console.error(
|
|
@@ -1243,6 +1273,16 @@ async function buildFileParts(attachments, capable) {
|
|
|
1243
1273
|
);
|
|
1244
1274
|
dataUrl = null;
|
|
1245
1275
|
}
|
|
1276
|
+
if (dataUrl !== null && typeof dataUrl === "object") {
|
|
1277
|
+
outcomes.push({
|
|
1278
|
+
index: a.index,
|
|
1279
|
+
mime: a.mime,
|
|
1280
|
+
filename: a.filename,
|
|
1281
|
+
status: "failed",
|
|
1282
|
+
reason: "needs_reauth"
|
|
1283
|
+
});
|
|
1284
|
+
continue;
|
|
1285
|
+
}
|
|
1246
1286
|
if (dataUrl == null) {
|
|
1247
1287
|
outcomes.push({ index: a.index, mime: a.mime, filename: a.filename, status: "failed" });
|
|
1248
1288
|
continue;
|
|
@@ -1370,6 +1410,72 @@ function findLastAssistantReplyFor(messages, userMessageId) {
|
|
|
1370
1410
|
}
|
|
1371
1411
|
return lastOk ?? last;
|
|
1372
1412
|
}
|
|
1413
|
+
function messageUsage(messages, userMessageId) {
|
|
1414
|
+
if (!messages || messages.length === 0) return null;
|
|
1415
|
+
const byParentAll = messages.filter(
|
|
1416
|
+
(m) => roleOf(m) === "assistant" && parentIdOf(m) === userMessageId
|
|
1417
|
+
);
|
|
1418
|
+
const byParentNonErrored = byParentAll.filter((m) => errorOf(m) == null);
|
|
1419
|
+
const byParent = byParentNonErrored.length > 0 ? byParentNonErrored : byParentAll;
|
|
1420
|
+
let correlated;
|
|
1421
|
+
if (byParent.length > 0) {
|
|
1422
|
+
correlated = byParent;
|
|
1423
|
+
} else {
|
|
1424
|
+
const reply = findAssistantReplyAfter(messages, userMessageId);
|
|
1425
|
+
correlated = reply ? [reply] : [];
|
|
1426
|
+
}
|
|
1427
|
+
if (correlated.length === 0) return null;
|
|
1428
|
+
let sawAnyUsage = false;
|
|
1429
|
+
let inputSum = 0;
|
|
1430
|
+
let outputSum = 0;
|
|
1431
|
+
let reasoningSum = 0;
|
|
1432
|
+
let cacheReadSum = 0;
|
|
1433
|
+
let cacheWriteSum = 0;
|
|
1434
|
+
let costSum = 0;
|
|
1435
|
+
let sawCost = false;
|
|
1436
|
+
let modelId = null;
|
|
1437
|
+
let providerId = null;
|
|
1438
|
+
for (const m of correlated) {
|
|
1439
|
+
const info = m.info;
|
|
1440
|
+
if (!info) continue;
|
|
1441
|
+
const tokens = info.tokens;
|
|
1442
|
+
if (tokens) {
|
|
1443
|
+
sawAnyUsage = true;
|
|
1444
|
+
inputSum += tokens.input ?? 0;
|
|
1445
|
+
outputSum += tokens.output ?? 0;
|
|
1446
|
+
reasoningSum += tokens.reasoning ?? 0;
|
|
1447
|
+
cacheReadSum += tokens.cache?.read ?? 0;
|
|
1448
|
+
cacheWriteSum += tokens.cache?.write ?? 0;
|
|
1449
|
+
}
|
|
1450
|
+
if (typeof info.cost === "number") {
|
|
1451
|
+
sawAnyUsage = true;
|
|
1452
|
+
sawCost = true;
|
|
1453
|
+
costSum += info.cost;
|
|
1454
|
+
}
|
|
1455
|
+
if (typeof info.modelID === "string") {
|
|
1456
|
+
sawAnyUsage = true;
|
|
1457
|
+
modelId = info.modelID;
|
|
1458
|
+
}
|
|
1459
|
+
if (typeof info.providerID === "string") {
|
|
1460
|
+
sawAnyUsage = true;
|
|
1461
|
+
providerId = info.providerID;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (!sawAnyUsage) return null;
|
|
1465
|
+
return {
|
|
1466
|
+
usage_provider_id: providerId,
|
|
1467
|
+
usage_model_id: modelId,
|
|
1468
|
+
usage_tokens_input: inputSum,
|
|
1469
|
+
usage_tokens_output: outputSum,
|
|
1470
|
+
usage_tokens_reasoning: reasoningSum,
|
|
1471
|
+
usage_tokens_cache_read: cacheReadSum,
|
|
1472
|
+
usage_tokens_cache_write: cacheWriteSum,
|
|
1473
|
+
// NULL means "OpenCode never reported a cost" (never inferred from
|
|
1474
|
+
// tokens) — distinct from a genuine 0-cost turn, which would set
|
|
1475
|
+
// `sawCost` true with `costSum === 0`.
|
|
1476
|
+
usage_cost_usd: sawCost ? costSum : null
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1373
1479
|
function messageRunState(messages, userMessageId) {
|
|
1374
1480
|
if (!messages || messages.length === 0) return "unknown";
|
|
1375
1481
|
const hasUser = messages.some((m) => idOf(m) === userMessageId);
|
|
@@ -1405,6 +1511,37 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
|
|
|
1405
1511
|
(m) => roleOf(m) === "assistant" && parentIdOf(m) !== exceptUserMessageId && isAssistantInFlight(m)
|
|
1406
1512
|
);
|
|
1407
1513
|
}
|
|
1514
|
+
async function hasAnyConfiguredProvider(port) {
|
|
1515
|
+
try {
|
|
1516
|
+
const res = await fetch(`${opencodeBase(port)}/config/providers`);
|
|
1517
|
+
if (!res.ok) {
|
|
1518
|
+
console.error(
|
|
1519
|
+
`[hasAnyConfiguredProvider] GET /config/providers returned HTTP ${res.status} (port ${port})`
|
|
1520
|
+
);
|
|
1521
|
+
return null;
|
|
1522
|
+
}
|
|
1523
|
+
const body = await res.json();
|
|
1524
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1525
|
+
console.error(
|
|
1526
|
+
`[hasAnyConfiguredProvider] GET /config/providers body was not a plain object (port ${port})`
|
|
1527
|
+
);
|
|
1528
|
+
return null;
|
|
1529
|
+
}
|
|
1530
|
+
const defaults2 = body.default;
|
|
1531
|
+
if (!defaults2 || typeof defaults2 !== "object" || Array.isArray(defaults2)) {
|
|
1532
|
+
console.error(
|
|
1533
|
+
`[hasAnyConfiguredProvider] GET /config/providers body had no \`default\` object (port ${port})`
|
|
1534
|
+
);
|
|
1535
|
+
return null;
|
|
1536
|
+
}
|
|
1537
|
+
return Object.keys(defaults2).length > 0;
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
console.error(
|
|
1540
|
+
`[hasAnyConfiguredProvider] GET /config/providers failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
|
|
1541
|
+
);
|
|
1542
|
+
return null;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1408
1545
|
|
|
1409
1546
|
// src/lib/opencode/session-cleanup.ts
|
|
1410
1547
|
var DURATION_UNIT_MS = {
|
|
@@ -1563,10 +1700,11 @@ var StreamForwarder = class {
|
|
|
1563
1700
|
* Abort every in-flight stream (e.g. on WebSocket close).
|
|
1564
1701
|
*/
|
|
1565
1702
|
abortAll() {
|
|
1566
|
-
for (const stream of this.inflight.
|
|
1703
|
+
for (const [sid, stream] of this.inflight.entries()) {
|
|
1567
1704
|
try {
|
|
1568
1705
|
stream.abort();
|
|
1569
|
-
} catch {
|
|
1706
|
+
} catch (err) {
|
|
1707
|
+
log("error", "forwarder_abort_failed", { sid, ...errorFields(err) });
|
|
1570
1708
|
}
|
|
1571
1709
|
}
|
|
1572
1710
|
this.inflight.clear();
|
|
@@ -1716,7 +1854,6 @@ function connectTunnel(options) {
|
|
|
1716
1854
|
onConnected,
|
|
1717
1855
|
onDisconnected,
|
|
1718
1856
|
onError,
|
|
1719
|
-
onRequest,
|
|
1720
1857
|
onResponse,
|
|
1721
1858
|
onInfo,
|
|
1722
1859
|
onDrainPing
|
|
@@ -1729,18 +1866,8 @@ function connectTunnel(options) {
|
|
|
1729
1866
|
Authorization: authHeader
|
|
1730
1867
|
}
|
|
1731
1868
|
});
|
|
1732
|
-
const streamStartTimes = /* @__PURE__ */ new Map();
|
|
1733
1869
|
const forwarder = new StreamForwarder(ws, port, {
|
|
1734
|
-
|
|
1735
|
-
if (path === TUNNEL_DRAIN_PING_PATH) return;
|
|
1736
|
-
streamStartTimes.set(sid, Date.now());
|
|
1737
|
-
onRequest?.(method, path, sid);
|
|
1738
|
-
},
|
|
1739
|
-
onHead: (sid, status) => {
|
|
1740
|
-
const startedAt = streamStartTimes.get(sid);
|
|
1741
|
-
streamStartTimes.delete(sid);
|
|
1742
|
-
onResponse?.(status, startedAt ? Date.now() - startedAt : 0, sid);
|
|
1743
|
-
},
|
|
1870
|
+
onHead: () => onResponse?.(),
|
|
1744
1871
|
onDrainPing: () => onDrainPing?.()
|
|
1745
1872
|
});
|
|
1746
1873
|
const connectionTimeout = setTimeout(() => {
|
|
@@ -1816,7 +1943,6 @@ function connectTunnel(options) {
|
|
|
1816
1943
|
ws.on("close", (code, reason) => {
|
|
1817
1944
|
const reasonStr = reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
|
|
1818
1945
|
forwarder.abortAll();
|
|
1819
|
-
streamStartTimes.clear();
|
|
1820
1946
|
onDisconnected?.(code, reasonStr);
|
|
1821
1947
|
});
|
|
1822
1948
|
});
|
|
@@ -1851,7 +1977,11 @@ var RunnerConnection = class {
|
|
|
1851
1977
|
if (this.connection) {
|
|
1852
1978
|
try {
|
|
1853
1979
|
this.connection.close();
|
|
1854
|
-
} catch {
|
|
1980
|
+
} catch (err) {
|
|
1981
|
+
log("error", "runner_connection_close_failed", {
|
|
1982
|
+
agent_id: this.resolvedAgentId,
|
|
1983
|
+
...errorFields(err)
|
|
1984
|
+
});
|
|
1855
1985
|
}
|
|
1856
1986
|
this.connection = null;
|
|
1857
1987
|
}
|
|
@@ -1932,6 +2062,7 @@ var DEFAULT_STUCK_QUEUED_MS = 6e4;
|
|
|
1932
2062
|
var HEARTBEAT_MS = 6e4;
|
|
1933
2063
|
var ABSOLUTE_MAX_PROCESSING_MS = 6 * 60 * 60 * 1e3;
|
|
1934
2064
|
var POLL_MISS_GRACE_MS = HEARTBEAT_MS;
|
|
2065
|
+
var MAX_SUPERSEDED_CONVERSATIONS = 256;
|
|
1935
2066
|
var ChannelAuthError = class extends Error {
|
|
1936
2067
|
constructor(message) {
|
|
1937
2068
|
super(message);
|
|
@@ -1954,7 +2085,7 @@ function backoffDelay(attempt, policy) {
|
|
|
1954
2085
|
function isRetryableStatus(status) {
|
|
1955
2086
|
return status === 429 || status >= 500 && status <= 599;
|
|
1956
2087
|
}
|
|
1957
|
-
var ChannelDriver = class {
|
|
2088
|
+
var ChannelDriver = class _ChannelDriver {
|
|
1958
2089
|
agentId;
|
|
1959
2090
|
port;
|
|
1960
2091
|
apiUrl;
|
|
@@ -1970,6 +2101,34 @@ var ChannelDriver = class {
|
|
|
1970
2101
|
now;
|
|
1971
2102
|
/** Cache of conversationId → opencode sessionId. */
|
|
1972
2103
|
sessions = /* @__PURE__ */ new Map();
|
|
2104
|
+
/**
|
|
2105
|
+
* conversationId → the opencode session this runner has ABANDONED as that
|
|
2106
|
+
* conversation's binding (#553), after a genuine (`sessionExists === true`)
|
|
2107
|
+
* dispatch failure: the session still exists but is wedged, so #485's self-heal
|
|
2108
|
+
* must bind a fresh one.
|
|
2109
|
+
*
|
|
2110
|
+
* Dropping the local binding + clearing the server row is not enough on its own:
|
|
2111
|
+
* a SIBLING message dispatched earlier in the same drain is still in-flight under
|
|
2112
|
+
* the same session, and its watcher's routine status writes carry
|
|
2113
|
+
* `opencode_session_id`, RESURRECTING the wedged id server-side after the clear —
|
|
2114
|
+
* and `ensureSession`'s persisted-id fallback then reuses it, defeating the
|
|
2115
|
+
* self-heal. This map makes the runner authoritative instead of racing those
|
|
2116
|
+
* writes: *`ensureSession` never reuses an abandoned id for that conversation,
|
|
2117
|
+
* whatever the server row says* — which holds even when the resurrecting write
|
|
2118
|
+
* is one we deliberately keep (see `markDone`).
|
|
2119
|
+
*
|
|
2120
|
+
* Bounded by construction, on both axes: keyed by CONVERSATION, so N failures on
|
|
2121
|
+
* one conversation hold ONE entry (the newest abandonment replaces the older), and
|
|
2122
|
+
* hard-capped at `MAX_SUPERSEDED_CONVERSATIONS` with FIFO eviction. Only the
|
|
2123
|
+
* NEWEST abandoned id per conversation is guarded: after a second abandonment a
|
|
2124
|
+
* late sibling of the FIRST session can write that id back and `ensureSession`
|
|
2125
|
+
* will reuse it — costing ONE repeat failure, which re-supersedes it. Deliberately
|
|
2126
|
+
* NOT dropped when the session's watcher tears down: `markDone` still writes the
|
|
2127
|
+
* abandoned id back (it must, or the reply is lost), so the guard has to outlive
|
|
2128
|
+
* the turn that resurrects it. In-memory only — a restart forgets it, at the same
|
|
2129
|
+
* bounded cost.
|
|
2130
|
+
*/
|
|
2131
|
+
supersededSessions = /* @__PURE__ */ new Map();
|
|
1973
2132
|
/**
|
|
1974
2133
|
* Per-opencode-session dispatch lock (Task 2.1a). `sendPromptAsync` is no
|
|
1975
2134
|
* longer idempotent (no caller-supplied `messageID`), and its read-back picks
|
|
@@ -2079,9 +2238,12 @@ var ChannelDriver = class {
|
|
|
2079
2238
|
sessionParents = /* @__PURE__ */ new Map();
|
|
2080
2239
|
/**
|
|
2081
2240
|
* Per-session OpenCode title cache (#310), keyed by sessionId. Only a resolved
|
|
2082
|
-
* NON-EMPTY name is stored (terminal — a real session name
|
|
2083
|
-
* so we do NOT re-GET `/session/:id` every tick.
|
|
2084
|
-
*
|
|
2241
|
+
* NON-EMPTY, non-placeholder name is stored (terminal — a real session name
|
|
2242
|
+
* won't later un-name), so we do NOT re-GET `/session/:id` every tick. "Non-empty"
|
|
2243
|
+
* excludes OpenCode's synchronous default title (see
|
|
2244
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX`, #549) — that placeholder is treated the same
|
|
2245
|
+
* as an empty title so it never latches. A missing entry = not yet resolved OR
|
|
2246
|
+
* resolved-but-still-empty/placeholder → re-fetch on next need, since OpenCode
|
|
2085
2247
|
* names sessions asynchronously mid-turn. Driver-level (not per-watcher) so both
|
|
2086
2248
|
* the watcher completion path AND the restart-recovery re-adopt path (which has
|
|
2087
2249
|
* no watcher) can resolve the title.
|
|
@@ -2275,10 +2437,15 @@ var ChannelDriver = class {
|
|
|
2275
2437
|
* @returns the count of messages NEWLY dispatched (not already in-flight).
|
|
2276
2438
|
*/
|
|
2277
2439
|
async processConversation(conv) {
|
|
2278
|
-
const sessionId = await this.ensureSession(conv);
|
|
2440
|
+
const { sessionId, refusedSessionId } = await this.ensureSession(conv);
|
|
2279
2441
|
const messages = await this.getPendingMessages(conv.id);
|
|
2280
2442
|
let dispatched = 0;
|
|
2281
2443
|
let skippedAlreadyDispatched = 0;
|
|
2444
|
+
if (refusedSessionId && messages.length > 0) {
|
|
2445
|
+
void this.postSignal(conv.id, messages[0].id, "session_superseded", {
|
|
2446
|
+
superseded_session_id: refusedSessionId
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2282
2449
|
for (const message of messages) {
|
|
2283
2450
|
if (this.stopped) break;
|
|
2284
2451
|
if (this.dispatched.has(message.id)) {
|
|
@@ -2305,7 +2472,8 @@ var ChannelDriver = class {
|
|
|
2305
2472
|
} catch (err) {
|
|
2306
2473
|
if (err instanceof ChannelAuthError) throw err;
|
|
2307
2474
|
this.dispatched.delete(message.id);
|
|
2308
|
-
|
|
2475
|
+
const exists = await sessionExists(this.port, sessionId);
|
|
2476
|
+
if (exists === false) {
|
|
2309
2477
|
this.sessions.delete(conv.id);
|
|
2310
2478
|
this.log({
|
|
2311
2479
|
level: "warn",
|
|
@@ -2315,15 +2483,39 @@ var ChannelDriver = class {
|
|
|
2315
2483
|
});
|
|
2316
2484
|
break;
|
|
2317
2485
|
}
|
|
2318
|
-
|
|
2486
|
+
if (exists === null) {
|
|
2487
|
+
this.log({
|
|
2488
|
+
level: "warn",
|
|
2489
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed (opencode momentarily unreachable) \u2014 deferring this and later messages for conversation ${conv.id.slice(0, 8)} to the next tick rather than treating it as a genuine failure.`,
|
|
2490
|
+
conversation_id: conv.id,
|
|
2491
|
+
message_id: message.id
|
|
2492
|
+
});
|
|
2493
|
+
break;
|
|
2494
|
+
}
|
|
2495
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
2496
|
+
this.sessions.delete(conv.id);
|
|
2497
|
+
this.supersede(conv.id, sessionId);
|
|
2498
|
+
this.log({
|
|
2499
|
+
level: "warn",
|
|
2500
|
+
message: `Abandoning OpenCode session ${sessionId.slice(0, 8)} as the binding for conversation ${conv.id.slice(0, 8)} (it exists but failed to run a turn) \u2014 a fresh session is created on the next tick, whatever the persisted binding says by then.`,
|
|
2501
|
+
conversation_id: conv.id,
|
|
2502
|
+
message_id: message.id
|
|
2503
|
+
});
|
|
2504
|
+
await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
|
|
2505
|
+
this.log({
|
|
2506
|
+
level: "warn",
|
|
2507
|
+
message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
|
|
2508
|
+
conversation_id: conv.id,
|
|
2509
|
+
message_id: message.id
|
|
2510
|
+
});
|
|
2319
2511
|
});
|
|
2320
2512
|
this.log({
|
|
2321
2513
|
level: "error",
|
|
2322
|
-
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${
|
|
2514
|
+
message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
|
|
2323
2515
|
conversation_id: conv.id,
|
|
2324
2516
|
message_id: message.id
|
|
2325
2517
|
});
|
|
2326
|
-
|
|
2518
|
+
break;
|
|
2327
2519
|
}
|
|
2328
2520
|
if (opencodeMessageId === null) {
|
|
2329
2521
|
this.log({
|
|
@@ -2349,8 +2541,42 @@ var ChannelDriver = class {
|
|
|
2349
2541
|
this.ensureWatcherRunning(sessionId);
|
|
2350
2542
|
return dispatched;
|
|
2351
2543
|
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Record that `sessionId` is no longer a valid binding for `conversationId`
|
|
2546
|
+
* (#553). Keyed by conversation and hard-capped, so it cannot grow with the
|
|
2547
|
+
* number of failures — see the `supersededSessions` field doc.
|
|
2548
|
+
*/
|
|
2549
|
+
supersede(conversationId, sessionId) {
|
|
2550
|
+
this.supersededSessions.delete(conversationId);
|
|
2551
|
+
this.supersededSessions.set(conversationId, sessionId);
|
|
2552
|
+
while (this.supersededSessions.size > MAX_SUPERSEDED_CONVERSATIONS) {
|
|
2553
|
+
const oldest = this.supersededSessions.keys().next().value;
|
|
2554
|
+
if (oldest === void 0) return;
|
|
2555
|
+
this.supersededSessions.delete(oldest);
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
/** Whether `sessionId` is the session this conversation has abandoned (#553). */
|
|
2559
|
+
isSuperseded(conversationId, sessionId) {
|
|
2560
|
+
return this.supersededSessions.get(conversationId) === sessionId;
|
|
2561
|
+
}
|
|
2562
|
+
/**
|
|
2563
|
+
* Resolve the opencode session to run this conversation's turns in.
|
|
2564
|
+
*
|
|
2565
|
+
* `refusedSessionId` is set when the #553 guard fired — i.e. the persisted
|
|
2566
|
+
* binding was an id this runner had abandoned, so a resurrection genuinely
|
|
2567
|
+
* happened and a fresh session was bound instead. The caller reports it.
|
|
2568
|
+
*/
|
|
2352
2569
|
async ensureSession(conv) {
|
|
2353
2570
|
const bound = this.sessions.get(conv.id) ?? conv.opencode_session_id ?? null;
|
|
2571
|
+
if (bound && this.isSuperseded(conv.id, bound)) {
|
|
2572
|
+
this.log({
|
|
2573
|
+
level: "warn",
|
|
2574
|
+
message: `OpenCode session ${bound.slice(0, 8)} was abandoned for conversation ${conv.id.slice(0, 8)} after a failed dispatch but is still bound to it (the persisted id was written back by a turn already in flight) \u2014 ignoring it and binding a fresh session.`,
|
|
2575
|
+
conversation_id: conv.id
|
|
2576
|
+
});
|
|
2577
|
+
this.sessions.delete(conv.id);
|
|
2578
|
+
return { sessionId: await this.createAndBindSession(conv.id), refusedSessionId: bound };
|
|
2579
|
+
}
|
|
2354
2580
|
if (bound) {
|
|
2355
2581
|
const exists = await sessionExists(this.port, bound);
|
|
2356
2582
|
if (exists === false) {
|
|
@@ -2360,12 +2586,12 @@ var ChannelDriver = class {
|
|
|
2360
2586
|
conversation_id: conv.id
|
|
2361
2587
|
});
|
|
2362
2588
|
this.sessions.delete(conv.id);
|
|
2363
|
-
return this.createAndBindSession(conv.id);
|
|
2589
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2364
2590
|
}
|
|
2365
2591
|
this.sessions.set(conv.id, bound);
|
|
2366
|
-
return bound;
|
|
2592
|
+
return { sessionId: bound };
|
|
2367
2593
|
}
|
|
2368
|
-
return this.createAndBindSession(conv.id);
|
|
2594
|
+
return { sessionId: await this.createAndBindSession(conv.id) };
|
|
2369
2595
|
}
|
|
2370
2596
|
/**
|
|
2371
2597
|
* Create a fresh OpenCode session for a conversation, cache the binding, and
|
|
@@ -2445,7 +2671,7 @@ var ChannelDriver = class {
|
|
|
2445
2671
|
}
|
|
2446
2672
|
/**
|
|
2447
2673
|
* Fetch ONE inbound image's bytes through Evident's WI-6 endpoint
|
|
2448
|
-
* (`GET {apiUrl}/
|
|
2674
|
+
* (`GET {apiUrl}/runners/{agentId}/attachments/{messageId}/{index}`) using the
|
|
2449
2675
|
* existing authenticated fetch, and base64-encode into a
|
|
2450
2676
|
* `data:<mime>;base64,<…>` URL for the opencode `file` part's `url`.
|
|
2451
2677
|
*
|
|
@@ -2453,15 +2679,38 @@ var ChannelDriver = class {
|
|
|
2453
2679
|
* (not-owned / out-of-range / deleted-at-source / workspace gone) / 413
|
|
2454
2680
|
* (over-cap). On ANY non-2xx or thrown failure we return `null` so the caller
|
|
2455
2681
|
* OMITS that one image and the text turn still sends — NEVER throws the turn.
|
|
2456
|
-
*
|
|
2682
|
+
* A 404 body carrying `{ reason: 'needs_reauth' }` (#547 — the server CONFIRMED
|
|
2683
|
+
* a Slack `files:read` scope problem via `files.info`) instead resolves the
|
|
2684
|
+
* `AttachmentFetchNeedsReauth` sentinel, so the in-thread note can steer the
|
|
2685
|
+
* user to reconnect Slack instead of a generic "unavailable". Failures are
|
|
2686
|
+
* logged with context (no silent swallow).
|
|
2457
2687
|
*/
|
|
2458
2688
|
async fetchAttachmentDataUrl(messageId, index, mime) {
|
|
2459
2689
|
try {
|
|
2460
2690
|
const res = await this.fetchImpl(
|
|
2461
|
-
`${this.apiUrl}/
|
|
2691
|
+
`${this.apiUrl}/runners/${this.agentId}/attachments/${messageId}/${index}`,
|
|
2462
2692
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
2463
2693
|
);
|
|
2464
2694
|
if (!res.ok) {
|
|
2695
|
+
let reason;
|
|
2696
|
+
try {
|
|
2697
|
+
const body = await res.json();
|
|
2698
|
+
if (body && typeof body.reason === "string") reason = body.reason;
|
|
2699
|
+
} catch (parseErr) {
|
|
2700
|
+
this.log({
|
|
2701
|
+
level: "debug",
|
|
2702
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index}: error body was not JSON (${parseErr instanceof Error ? parseErr.message : String(parseErr)}) \u2014 treating as a plain failure`,
|
|
2703
|
+
message_id: messageId
|
|
2704
|
+
});
|
|
2705
|
+
}
|
|
2706
|
+
if (reason === "needs_reauth") {
|
|
2707
|
+
this.log({
|
|
2708
|
+
level: "error",
|
|
2709
|
+
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 server confirmed a Slack reauth/scope problem \u2014 omitting this image (text turn proceeds)`,
|
|
2710
|
+
message_id: messageId
|
|
2711
|
+
});
|
|
2712
|
+
return { needsReauth: true };
|
|
2713
|
+
}
|
|
2465
2714
|
this.log({
|
|
2466
2715
|
level: "error",
|
|
2467
2716
|
message: `Attachment fetch for message ${messageId.slice(0, 8)} index ${index} returned HTTP ${res.status} \u2014 omitting this image (text turn proceeds)`,
|
|
@@ -2501,6 +2750,9 @@ var ChannelDriver = class {
|
|
|
2501
2750
|
if (this.attachmentsSkippedSignalled.has(messageId)) return;
|
|
2502
2751
|
this.attachmentsSkippedSignalled.add(messageId);
|
|
2503
2752
|
const skippedReason = capabilityUnknown ? "unknown" : "unsupported";
|
|
2753
|
+
const failedReason = outcomes.some(
|
|
2754
|
+
(o) => o.status === "failed" && o.reason === "needs_reauth"
|
|
2755
|
+
) ? "needs_reauth" : void 0;
|
|
2504
2756
|
this.log({
|
|
2505
2757
|
level: "info",
|
|
2506
2758
|
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`,
|
|
@@ -2510,7 +2762,8 @@ var ChannelDriver = class {
|
|
|
2510
2762
|
void this.postSignal(conversationId, messageId, "attachments_skipped", {
|
|
2511
2763
|
skipped,
|
|
2512
2764
|
failed,
|
|
2513
|
-
...skipped > 0 ? { skipped_reason: skippedReason } : {}
|
|
2765
|
+
...skipped > 0 ? { skipped_reason: skippedReason } : {},
|
|
2766
|
+
...failedReason ? { failed_reason: failedReason } : {}
|
|
2514
2767
|
});
|
|
2515
2768
|
}
|
|
2516
2769
|
/** Register a freshly-dispatched message with its session's watcher state. */
|
|
@@ -2790,13 +3043,15 @@ var ChannelDriver = class {
|
|
|
2790
3043
|
message_id: inFlight.evidentMessageId
|
|
2791
3044
|
});
|
|
2792
3045
|
const title = await this.resolveSessionTitle(sessionId, watcher.conv.id);
|
|
3046
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2793
3047
|
try {
|
|
2794
3048
|
await this.markDone(
|
|
2795
3049
|
conv.id,
|
|
2796
3050
|
inFlight.evidentMessageId,
|
|
2797
3051
|
sessionId,
|
|
2798
3052
|
inFlight.opencodeMessageId,
|
|
2799
|
-
title
|
|
3053
|
+
title,
|
|
3054
|
+
usage
|
|
2800
3055
|
);
|
|
2801
3056
|
} catch (err) {
|
|
2802
3057
|
if (err instanceof ChannelAuthError) throw err;
|
|
@@ -2843,8 +3098,9 @@ var ChannelDriver = class {
|
|
|
2843
3098
|
conversation_id: conv.id,
|
|
2844
3099
|
message_id: inFlight.evidentMessageId
|
|
2845
3100
|
});
|
|
3101
|
+
const usage = messageUsage(messages, inFlight.opencodeMessageId);
|
|
2846
3102
|
try {
|
|
2847
|
-
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2);
|
|
3103
|
+
await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
|
|
2848
3104
|
} catch (err) {
|
|
2849
3105
|
if (err instanceof ChannelAuthError) throw err;
|
|
2850
3106
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3081,7 +3337,8 @@ var ChannelDriver = class {
|
|
|
3081
3337
|
});
|
|
3082
3338
|
try {
|
|
3083
3339
|
const title = await this.resolveSessionTitle(sessionId, row.conversation_id);
|
|
3084
|
-
|
|
3340
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3341
|
+
await this.markDone(row.conversation_id, row.id, sessionId, ocId, title, usage);
|
|
3085
3342
|
} catch (err) {
|
|
3086
3343
|
if (err instanceof ChannelAuthError) throw err;
|
|
3087
3344
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3109,6 +3366,7 @@ var ChannelDriver = class {
|
|
|
3109
3366
|
}
|
|
3110
3367
|
if (state === "failed") {
|
|
3111
3368
|
const error2 = messageError(messages, ocId ?? "") ?? void 0;
|
|
3369
|
+
const usage = messageUsage(messages, ocId ?? "");
|
|
3112
3370
|
this.log({
|
|
3113
3371
|
level: "error",
|
|
3114
3372
|
message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
|
|
@@ -3116,7 +3374,7 @@ var ChannelDriver = class {
|
|
|
3116
3374
|
message_id: row.id
|
|
3117
3375
|
});
|
|
3118
3376
|
try {
|
|
3119
|
-
await this.markFailed(row.conversation_id, row.id, sessionId, error2);
|
|
3377
|
+
await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
|
|
3120
3378
|
} catch (err) {
|
|
3121
3379
|
if (err instanceof ChannelAuthError) throw err;
|
|
3122
3380
|
if (err instanceof ChannelTerminalError) {
|
|
@@ -3544,19 +3802,36 @@ var ChannelDriver = class {
|
|
|
3544
3802
|
if (parent !== void 0) this.sessionParents.set(sessionId, parent);
|
|
3545
3803
|
return parent;
|
|
3546
3804
|
}
|
|
3805
|
+
/**
|
|
3806
|
+
* OpenCode's synchronous default session title (e.g.
|
|
3807
|
+
* `"New session - 1737800000000"`), assigned immediately when a session is
|
|
3808
|
+
* created — before OpenCode's async LLM-based auto-titling later renames it
|
|
3809
|
+
* mid-turn (#549). Matched by this literal, case-sensitive prefix only; the
|
|
3810
|
+
* timestamp suffix's exact format is deliberately NOT matched, since the prefix
|
|
3811
|
+
* alone is the stable, cheap signal and over-anchoring on the timestamp
|
|
3812
|
+
* representation risks silently breaking if OpenCode ever changes it. Accepted
|
|
3813
|
+
* trade-off: a genuine LLM-assigned title that happens to literally start with
|
|
3814
|
+
* this prefix would also fail to latch (see `resolveSessionTitle`) —
|
|
3815
|
+
* vanishingly unlikely in practice, and deliberately not engineered around.
|
|
3816
|
+
*/
|
|
3817
|
+
static OPENCODE_DEFAULT_TITLE_PREFIX = /^New session - /;
|
|
3547
3818
|
/**
|
|
3548
3819
|
* Resolve (and cache in `sessionTitles`) the OpenCode session TITLE (#310) so the
|
|
3549
3820
|
* status PATCH can carry it into the "Live sessions" list. Driver-level cache so
|
|
3550
3821
|
* BOTH the watcher completion path and the restart-recovery re-adopt path (which
|
|
3551
3822
|
* has no watcher) can use it. `conversationId` is passed only for log context.
|
|
3552
3823
|
* Best-effort:
|
|
3553
|
-
* - a resolved NON-EMPTY title
|
|
3824
|
+
* - a resolved NON-EMPTY title that does NOT match
|
|
3825
|
+
* `OPENCODE_DEFAULT_TITLE_PREFIX` is cached and terminal (a real session name
|
|
3554
3826
|
* won't later un-name), so we do NOT re-GET `/session/:id` every tick;
|
|
3555
|
-
* - while the title is still absent
|
|
3556
|
-
*
|
|
3557
|
-
*
|
|
3558
|
-
*
|
|
3559
|
-
*
|
|
3827
|
+
* - while the title is still absent, empty, or matches the OpenCode
|
|
3828
|
+
* placeholder prefix (#549) we do NOT latch it — OpenCode names sessions
|
|
3829
|
+
* asynchronously mid-turn, so an early call (e.g. at `processing`) must leave
|
|
3830
|
+
* the cache unresolved and re-fetch on the next need so a later call (e.g. at
|
|
3831
|
+
* `done`) picks up the name assigned in the meantime. Such a call returns
|
|
3832
|
+
* `null` (omit the title on THIS PATCH) without caching. If a session is
|
|
3833
|
+
* never renamed, the title is omitted forever rather than ever persisting
|
|
3834
|
+
* the placeholder as a last resort;
|
|
3560
3835
|
* - a failed request likewise leaves the cache unresolved (retry next need)
|
|
3561
3836
|
* and returns `null` — it must NEVER throw or block completion.
|
|
3562
3837
|
* A failure is logged with agent/session context (no silent catch).
|
|
@@ -3569,7 +3844,7 @@ var ChannelDriver = class {
|
|
|
3569
3844
|
if (res.ok) {
|
|
3570
3845
|
const body = await res.json();
|
|
3571
3846
|
const title = body && typeof body.title === "string" ? body.title.trim() : "";
|
|
3572
|
-
if (title.length > 0) {
|
|
3847
|
+
if (title.length > 0 && !_ChannelDriver.OPENCODE_DEFAULT_TITLE_PREFIX.test(title)) {
|
|
3573
3848
|
this.sessionTitles.set(sessionId, title);
|
|
3574
3849
|
return title;
|
|
3575
3850
|
}
|
|
@@ -3719,7 +3994,7 @@ var ChannelDriver = class {
|
|
|
3719
3994
|
// Evident API calls (combinedAuth thread routes)
|
|
3720
3995
|
async getPendingConversations() {
|
|
3721
3996
|
const res = await this.fetchImpl(
|
|
3722
|
-
`${this.apiUrl}/
|
|
3997
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/pending`,
|
|
3723
3998
|
{
|
|
3724
3999
|
headers: { Authorization: this.getAuthHeader() }
|
|
3725
4000
|
}
|
|
@@ -3737,7 +4012,7 @@ var ChannelDriver = class {
|
|
|
3737
4012
|
}
|
|
3738
4013
|
async getPendingMessages(conversationId) {
|
|
3739
4014
|
const res = await this.fetchImpl(
|
|
3740
|
-
`${this.apiUrl}/
|
|
4015
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages?status=pending`,
|
|
3741
4016
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3742
4017
|
);
|
|
3743
4018
|
this.assertAuth(res, "fetching pending messages");
|
|
@@ -3761,7 +4036,7 @@ var ChannelDriver = class {
|
|
|
3761
4036
|
*/
|
|
3762
4037
|
async getProcessingMessages() {
|
|
3763
4038
|
const res = await this.fetchImpl(
|
|
3764
|
-
`${this.apiUrl}/
|
|
4039
|
+
`${this.apiUrl}/runners/${this.agentId}/conversations/processing`,
|
|
3765
4040
|
{ headers: { Authorization: this.getAuthHeader() } }
|
|
3766
4041
|
);
|
|
3767
4042
|
this.assertAuth(res, "fetching processing messages");
|
|
@@ -3775,6 +4050,32 @@ var ChannelDriver = class {
|
|
|
3775
4050
|
}
|
|
3776
4051
|
return messages;
|
|
3777
4052
|
}
|
|
4053
|
+
/**
|
|
4054
|
+
* The `opencode_session_id` fragment of a status PATCH body — `{}` when this
|
|
4055
|
+
* conversation has ABANDONED that session (#553). The field is optional
|
|
4056
|
+
* server-side and an absent one leaves the persisted binding untouched, so
|
|
4057
|
+
* omitting it is how a routine status write stops resurrecting it.
|
|
4058
|
+
*
|
|
4059
|
+
* ONLY for writes whose sole cost is a lost deep link. The `processing` notice
|
|
4060
|
+
* degrades to no "View in Evident" link (the reaction swap still fires) and the
|
|
4061
|
+
* turn-failure notice is built from the PATCH's own `error` text with a link off
|
|
4062
|
+
* the persisted row — neither loses content the user came for. `markDone`
|
|
4063
|
+
* deliberately does NOT use this helper: the server fetches the reply text
|
|
4064
|
+
* THROUGH the session id it is given, so suppressing there would replace the
|
|
4065
|
+
* agent's answer with a bare "✅ Done!" (the #183/#187 failure). The
|
|
4066
|
+
* `ensureSession` guard, not this suppression, is what makes the self-heal
|
|
4067
|
+
* stick.
|
|
4068
|
+
*/
|
|
4069
|
+
sessionIdBody(sessionId, conversationId, messageId, status) {
|
|
4070
|
+
if (!this.isSuperseded(conversationId, sessionId)) return { opencode_session_id: sessionId };
|
|
4071
|
+
this.log({
|
|
4072
|
+
level: "debug",
|
|
4073
|
+
message: `Omitting the abandoned OpenCode session ${sessionId.slice(0, 8)} from the '${status}' update for message ${messageId.slice(0, 8)} so it is not re-bound to conversation ${conversationId.slice(0, 8)}`,
|
|
4074
|
+
conversation_id: conversationId,
|
|
4075
|
+
message_id: messageId
|
|
4076
|
+
});
|
|
4077
|
+
return {};
|
|
4078
|
+
}
|
|
3778
4079
|
/**
|
|
3779
4080
|
* EXISTING combinedAuth route — now fired by the watcher on queued→running
|
|
3780
4081
|
* (Task 3.3), NOT at dispatch/claim time. `{status:'processing',
|
|
@@ -3798,13 +4099,13 @@ var ChannelDriver = class {
|
|
|
3798
4099
|
*/
|
|
3799
4100
|
async markProcessing(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
3800
4101
|
const res = await this.fetchImpl(
|
|
3801
|
-
`${this.apiUrl}/
|
|
4102
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3802
4103
|
{
|
|
3803
4104
|
method: "PATCH",
|
|
3804
4105
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3805
4106
|
body: JSON.stringify({
|
|
3806
4107
|
status: "processing",
|
|
3807
|
-
|
|
4108
|
+
...this.sessionIdBody(sessionId, conversationId, messageId, "processing"),
|
|
3808
4109
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3809
4110
|
...title ? { title } : {}
|
|
3810
4111
|
})
|
|
@@ -3845,17 +4146,23 @@ var ChannelDriver = class {
|
|
|
3845
4146
|
* watcher retries next tick within the
|
|
3846
4147
|
* deadline, Finding 4).
|
|
3847
4148
|
*/
|
|
3848
|
-
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title) {
|
|
4149
|
+
async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage) {
|
|
3849
4150
|
const res = await this.fetchImpl(
|
|
3850
|
-
`${this.apiUrl}/
|
|
4151
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3851
4152
|
{
|
|
3852
4153
|
method: "PATCH",
|
|
3853
4154
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
3854
4155
|
body: JSON.stringify({
|
|
3855
4156
|
status: "done",
|
|
4157
|
+
// ALWAYS sent, even for a session this conversation has abandoned
|
|
4158
|
+
// (#553): the server reads the reply text back out of THIS session id
|
|
4159
|
+
// to deliver it. Omitting it would leave the user with "✅ Done!"
|
|
4160
|
+
// instead of the answer — a worse regression than the resurrection it
|
|
4161
|
+
// would prevent, which `ensureSession`'s guard handles anyway.
|
|
3856
4162
|
opencode_session_id: sessionId,
|
|
3857
4163
|
...opencodeMessageId ? { opencode_message_id: opencodeMessageId } : {},
|
|
3858
|
-
...title ? { title } : {}
|
|
4164
|
+
...title ? { title } : {},
|
|
4165
|
+
...usage ? usage : {}
|
|
3859
4166
|
})
|
|
3860
4167
|
}
|
|
3861
4168
|
);
|
|
@@ -3868,19 +4175,29 @@ var ChannelDriver = class {
|
|
|
3868
4175
|
}
|
|
3869
4176
|
/**
|
|
3870
4177
|
* Mark a message `failed`. `sessionId` / `error` are threaded to the API ONLY
|
|
3871
|
-
* when provided (issue #182)
|
|
3872
|
-
* `
|
|
3873
|
-
*
|
|
3874
|
-
*
|
|
4178
|
+
* when provided (issue #182). Three states for `sessionId`:
|
|
4179
|
+
* - omitted (`undefined`) → don't send the field, leave the persisted
|
|
4180
|
+
* session untouched (unused today; kept for API symmetry).
|
|
4181
|
+
* - a real id (`string`) → send it, update the persisted session (the
|
|
4182
|
+
* turn-failure call sites: an errored OpenCode turn).
|
|
4183
|
+
* - explicit `null` → send it, CLEAR the persisted session (issue
|
|
4184
|
+
* #485's dispatch-handoff-failure call site: the session id still
|
|
4185
|
+
* exists but is wedged, so the next attempt must get a fresh one
|
|
4186
|
+
* instead of reusing it — see WI-1's server-side null-clearing PATCH).
|
|
3875
4187
|
*/
|
|
3876
|
-
async markFailed(conversationId, messageId, sessionId, error2) {
|
|
4188
|
+
async markFailed(conversationId, messageId, sessionId, error2, usage) {
|
|
3877
4189
|
const body = { status: "failed" };
|
|
3878
|
-
if (sessionId
|
|
4190
|
+
if (sessionId === null) {
|
|
4191
|
+
body.opencode_session_id = null;
|
|
4192
|
+
} else if (sessionId !== void 0) {
|
|
4193
|
+
Object.assign(body, this.sessionIdBody(sessionId, conversationId, messageId, "failed"));
|
|
4194
|
+
}
|
|
3879
4195
|
if (error2 !== void 0) body.error = error2;
|
|
4196
|
+
if (usage) Object.assign(body, usage);
|
|
3880
4197
|
await this.callWithRetry(
|
|
3881
4198
|
"marking message as failed",
|
|
3882
4199
|
() => this.fetchImpl(
|
|
3883
|
-
`${this.apiUrl}/
|
|
4200
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
|
|
3884
4201
|
{
|
|
3885
4202
|
method: "PATCH",
|
|
3886
4203
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3907,7 +4224,7 @@ var ChannelDriver = class {
|
|
|
3907
4224
|
async postSignal(conversationId, messageId, signal, extra) {
|
|
3908
4225
|
try {
|
|
3909
4226
|
const res = await this.fetchImpl(
|
|
3910
|
-
`${this.apiUrl}/
|
|
4227
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}/signal`,
|
|
3911
4228
|
{
|
|
3912
4229
|
method: "POST",
|
|
3913
4230
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3936,7 +4253,7 @@ var ChannelDriver = class {
|
|
|
3936
4253
|
}
|
|
3937
4254
|
async persistSession(conversationId, sessionId) {
|
|
3938
4255
|
const res = await this.fetchImpl(
|
|
3939
|
-
`${this.apiUrl}/
|
|
4256
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}`,
|
|
3940
4257
|
{
|
|
3941
4258
|
method: "PATCH",
|
|
3942
4259
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -3962,7 +4279,7 @@ var ChannelDriver = class {
|
|
|
3962
4279
|
await this.callWithRetry(
|
|
3963
4280
|
"reporting interactive event",
|
|
3964
4281
|
() => this.fetchImpl(
|
|
3965
|
-
`${this.apiUrl}/
|
|
4282
|
+
`${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/interactive-event`,
|
|
3966
4283
|
{
|
|
3967
4284
|
method: "POST",
|
|
3968
4285
|
headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
|
|
@@ -4205,7 +4522,7 @@ async function resolveAgentIdFromKey(authHeader) {
|
|
|
4205
4522
|
async function notifyAgentDisconnected(agentId, authHeader) {
|
|
4206
4523
|
const apiUrl = getApiUrlConfig();
|
|
4207
4524
|
try {
|
|
4208
|
-
const response = await fetch(`${apiUrl}/
|
|
4525
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}/disconnect`, {
|
|
4209
4526
|
method: "POST",
|
|
4210
4527
|
headers: { Authorization: authHeader }
|
|
4211
4528
|
});
|
|
@@ -4224,7 +4541,7 @@ async function notifyAgentDisconnected(agentId, authHeader) {
|
|
|
4224
4541
|
async function getAgentInfo(agentId, authHeader) {
|
|
4225
4542
|
const apiUrl = getApiUrlConfig();
|
|
4226
4543
|
try {
|
|
4227
|
-
const response = await fetch(`${apiUrl}/
|
|
4544
|
+
const response = await fetch(`${apiUrl}/runners/${agentId}`, {
|
|
4228
4545
|
headers: { Authorization: authHeader }
|
|
4229
4546
|
});
|
|
4230
4547
|
if (response.status === 401) {
|
|
@@ -4611,7 +4928,7 @@ async function run(options) {
|
|
|
4611
4928
|
return;
|
|
4612
4929
|
}
|
|
4613
4930
|
const state = {
|
|
4614
|
-
agentId: options.agent || "",
|
|
4931
|
+
agentId: options.runner || options.agent || "",
|
|
4615
4932
|
agentName: null,
|
|
4616
4933
|
port: options.port ?? 4096,
|
|
4617
4934
|
conversationFilter: options.conversation ?? null,
|
|
@@ -4633,6 +4950,19 @@ async function run(options) {
|
|
|
4633
4950
|
sessionCleanupTimers: [],
|
|
4634
4951
|
authHeader: ""
|
|
4635
4952
|
};
|
|
4953
|
+
if (!options.runner && options.agent) {
|
|
4954
|
+
telemetry.info(
|
|
4955
|
+
EventTypes.DEPRECATED_AGENT_FLAG_USED,
|
|
4956
|
+
"Deprecated --agent flag used instead of --runner",
|
|
4957
|
+
{ command: "run" },
|
|
4958
|
+
state.agentId
|
|
4959
|
+
);
|
|
4960
|
+
const agentFlagNotice = "--agent is deprecated, use --runner instead; will be removed in a future release.";
|
|
4961
|
+
log2(state, agentFlagNotice, "warn");
|
|
4962
|
+
if (state.interactive && !state.json) {
|
|
4963
|
+
logActivity(state, { type: "info", level: "warn", message: agentFlagNotice });
|
|
4964
|
+
}
|
|
4965
|
+
}
|
|
4636
4966
|
if (state.idleTimeout === null && (process.env.GITHUB_ACTIONS || process.env.CI)) {
|
|
4637
4967
|
log2(
|
|
4638
4968
|
state,
|
|
@@ -4661,7 +4991,9 @@ async function run(options) {
|
|
|
4661
4991
|
if (!interactive) {
|
|
4662
4992
|
printError("Authentication required");
|
|
4663
4993
|
blank();
|
|
4664
|
-
console.log(
|
|
4994
|
+
console.log(
|
|
4995
|
+
chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
|
|
4996
|
+
);
|
|
4665
4997
|
console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
|
|
4666
4998
|
blank();
|
|
4667
4999
|
process.exit(1);
|
|
@@ -4675,6 +5007,25 @@ async function run(options) {
|
|
|
4675
5007
|
);
|
|
4676
5008
|
}
|
|
4677
5009
|
state.authHeader = getAuthHeader(credentials2);
|
|
5010
|
+
if (credentials2.notice) {
|
|
5011
|
+
log2(state, credentials2.notice, "warn");
|
|
5012
|
+
if (state.interactive && !state.json) {
|
|
5013
|
+
logActivity(state, { type: "info", level: "warn", message: credentials2.notice });
|
|
5014
|
+
}
|
|
5015
|
+
}
|
|
5016
|
+
if (credentials2.keySource === "agent_key") {
|
|
5017
|
+
telemetry.info(
|
|
5018
|
+
EventTypes.DEPRECATED_AGENT_KEY_ENV_USED,
|
|
5019
|
+
"Deprecated EVIDENT_AGENT_KEY env var used instead of EVIDENT_RUNNER_KEY",
|
|
5020
|
+
{ command: "run" },
|
|
5021
|
+
state.agentId
|
|
5022
|
+
);
|
|
5023
|
+
const agentKeyNotice = "EVIDENT_AGENT_KEY is deprecated, use EVIDENT_RUNNER_KEY instead; will be removed in a future release.";
|
|
5024
|
+
log2(state, agentKeyNotice, "warn");
|
|
5025
|
+
if (state.interactive && !state.json) {
|
|
5026
|
+
logActivity(state, { type: "info", level: "warn", message: agentKeyNotice });
|
|
5027
|
+
}
|
|
5028
|
+
}
|
|
4678
5029
|
if (!state.agentId) {
|
|
4679
5030
|
if (credentials2.authType === "agent_key") {
|
|
4680
5031
|
const resolved = await resolveAgentIdFromKey(state.authHeader);
|
|
@@ -4692,9 +5043,15 @@ async function run(options) {
|
|
|
4692
5043
|
process.exit(1);
|
|
4693
5044
|
}
|
|
4694
5045
|
} else {
|
|
4695
|
-
printError(
|
|
5046
|
+
printError(
|
|
5047
|
+
"--runner (or --agent) is required when not using EVIDENT_RUNNER_KEY or EVIDENT_AGENT_KEY"
|
|
5048
|
+
);
|
|
4696
5049
|
blank();
|
|
4697
|
-
console.log(
|
|
5050
|
+
console.log(
|
|
5051
|
+
chalk6.dim(
|
|
5052
|
+
"Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
|
|
5053
|
+
)
|
|
5054
|
+
);
|
|
4698
5055
|
blank();
|
|
4699
5056
|
process.exit(1);
|
|
4700
5057
|
}
|
|
@@ -4758,6 +5115,21 @@ async function run(options) {
|
|
|
4758
5115
|
logActivity(state, { type: "info", level: "warn", message: versionWarning });
|
|
4759
5116
|
}
|
|
4760
5117
|
}
|
|
5118
|
+
const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
|
|
5119
|
+
if (noProviderWarning) {
|
|
5120
|
+
log2(state, noProviderWarning, "warn");
|
|
5121
|
+
if (state.interactive && !state.json) {
|
|
5122
|
+
logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
|
|
5123
|
+
blank();
|
|
5124
|
+
console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
|
|
5125
|
+
console.log(
|
|
5126
|
+
chalk6.dim(
|
|
5127
|
+
`Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
|
|
5128
|
+
)
|
|
5129
|
+
);
|
|
5130
|
+
blank();
|
|
5131
|
+
}
|
|
5132
|
+
}
|
|
4761
5133
|
} catch (error2) {
|
|
4762
5134
|
ocSpinner?.fail(error2.message);
|
|
4763
5135
|
throw error2;
|
|
@@ -4909,7 +5281,7 @@ async function run(options) {
|
|
|
4909
5281
|
}
|
|
4910
5282
|
telemetry.error(EventTypes.CLI_ERROR, `Run command failed: ${message}`, {
|
|
4911
5283
|
command: "run",
|
|
4912
|
-
agentId: options.agent
|
|
5284
|
+
agentId: options.runner || options.agent
|
|
4913
5285
|
});
|
|
4914
5286
|
await shutdownTelemetry();
|
|
4915
5287
|
process.exit(1);
|
|
@@ -4934,7 +5306,7 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
4934
5306
|
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);
|
|
4935
5307
|
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 }));
|
|
4936
5308
|
program.command("whoami").description("Show the currently logged in user").action(whoami);
|
|
4937
|
-
program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
5309
|
+
program.command("run").description("Connect to Evident and process messages").option("-a, --agent [id]", "Runner ID to connect to (optional when EVIDENT_AGENT_KEY is set)").option("--runner [id]", "Alias for --agent (preferred name; wins if both are given)").option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
|
|
4938
5310
|
"--log-level <level>",
|
|
4939
5311
|
"Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
|
|
4940
5312
|
).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(
|
|
@@ -4950,6 +5322,7 @@ program.command("run").description("Connect to Evident and process messages").op
|
|
|
4950
5322
|
(options) => {
|
|
4951
5323
|
run({
|
|
4952
5324
|
agent: options.agent,
|
|
5325
|
+
runner: options.runner,
|
|
4953
5326
|
port: parseInt(options.port, 10),
|
|
4954
5327
|
// Raw string — validation/precedence is single-sourced in run.ts's
|
|
4955
5328
|
// resolveLogLevel (flag > -v > EVIDENT_LOG_LEVEL > info).
|