@evident-ai/cli 3.6.1-dev.e0da455 → 3.6.1-dev.eedc5a9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -100,6 +100,26 @@ function clearCredentials() {
100
100
  credentials.set("byEndpoint", byEndpoint);
101
101
  hardenCredentialsPermissions();
102
102
  }
103
+ function getManagedInferenceCredential(runnerId) {
104
+ hardenCredentialsPermissions();
105
+ return credentials.get("managedInferenceByEndpoint")?.[credentialsKey()]?.[runnerId];
106
+ }
107
+ function setManagedInferenceCredential(runnerId, credential) {
108
+ const byEndpoint = credentials.get("managedInferenceByEndpoint") ?? {};
109
+ byEndpoint[credentialsKey()] ??= {};
110
+ byEndpoint[credentialsKey()][runnerId] = credential;
111
+ credentials.set("managedInferenceByEndpoint", byEndpoint);
112
+ hardenCredentialsPermissions();
113
+ }
114
+ function clearManagedInferenceCredential(runnerId) {
115
+ const byEndpoint = credentials.get("managedInferenceByEndpoint") ?? {};
116
+ const runners = byEndpoint[credentialsKey()];
117
+ if (!runners || !(runnerId in runners)) return;
118
+ delete runners[runnerId];
119
+ if (Object.keys(runners).length === 0) delete byEndpoint[credentialsKey()];
120
+ credentials.set("managedInferenceByEndpoint", byEndpoint);
121
+ hardenCredentialsPermissions();
122
+ }
103
123
  function clearAllCredentials() {
104
124
  credentials.clear();
105
125
  hardenCredentialsPermissions();
@@ -119,13 +139,13 @@ function getCliName() {
119
139
  // src/lib/api.ts
120
140
  async function request(path, method, body, headers = {}) {
121
141
  const url = `${getApiUrlConfig()}${path}`;
122
- const requestHeaders = {
142
+ const requestHeaders2 = {
123
143
  "Content-Type": "application/json",
124
144
  ...headers
125
145
  };
126
146
  const response = await fetch(url, {
127
147
  method,
128
- headers: requestHeaders,
148
+ headers: requestHeaders2,
129
149
  body: body ? JSON.stringify(body) : void 0
130
150
  });
131
151
  if (!response.ok) {
@@ -1156,9 +1176,9 @@ async function claudeUsage() {
1156
1176
  }
1157
1177
 
1158
1178
  // src/commands/run.ts
1159
- import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
1160
- import { homedir as homedir7 } from "node:os";
1161
- import { isAbsolute as isAbsolute4, join as join12, parse, resolve as resolvePath2 } from "node:path";
1179
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "node:fs";
1180
+ import { homedir as homedir8 } from "node:os";
1181
+ import { isAbsolute as isAbsolute4, join as join13, parse, resolve as resolvePath2 } from "node:path";
1162
1182
  import chalk7 from "chalk";
1163
1183
 
1164
1184
  // ../../packages/types/src/agents/index.ts
@@ -1287,6 +1307,102 @@ var TUNNEL_USAGE_REARM_PING_PATH = "/__evident/usage-rearm";
1287
1307
  var MAX_FILE_PUSH_BYTES = 64 * 1024;
1288
1308
  var MAX_FILE_SYNC_DIRECTORIES = 16;
1289
1309
 
1310
+ // ../../packages/types/src/credential-proxy-native-config.ts
1311
+ var EVIDENT_PROXY_TOKEN_REFERENCE = "{env:EVIDENT_PROXY_TOKEN}";
1312
+ var CLAUDE_PROVIDER = {
1313
+ namespace: "evident-claude",
1314
+ name: "Evident Claude credential proxy",
1315
+ npm: "@ai-sdk/anthropic"
1316
+ };
1317
+ var NATIVE_PROVIDERS = {
1318
+ claude: CLAUDE_PROVIDER,
1319
+ anthropic: CLAUDE_PROVIDER,
1320
+ codex: {
1321
+ namespace: "evident-codex",
1322
+ name: "Evident Codex credential proxy",
1323
+ npm: "@ai-sdk/openai"
1324
+ },
1325
+ openai: {
1326
+ namespace: "evident-openai",
1327
+ name: "Evident OpenAI credential proxy",
1328
+ npm: "@ai-sdk/openai"
1329
+ },
1330
+ kimi: {
1331
+ namespace: "evident-kimi",
1332
+ name: "Evident Kimi credential proxy",
1333
+ npm: "@ai-sdk/openai-compatible",
1334
+ sdkName: "evident-kimi"
1335
+ },
1336
+ antigravity: {
1337
+ namespace: "evident-antigravity",
1338
+ name: "Evident Antigravity credential proxy",
1339
+ npm: "@ai-sdk/openai-compatible",
1340
+ sdkName: "evident-antigravity"
1341
+ },
1342
+ xai: {
1343
+ namespace: "evident-xai",
1344
+ name: "Evident xAI credential proxy",
1345
+ npm: "@ai-sdk/openai-compatible",
1346
+ sdkName: "evident-xai"
1347
+ },
1348
+ mistral: {
1349
+ namespace: "evident-mistral",
1350
+ name: "Evident Mistral credential proxy",
1351
+ npm: "@ai-sdk/openai-compatible",
1352
+ sdkName: "evident-mistral"
1353
+ }
1354
+ };
1355
+ var CREDENTIAL_PROXY_NATIVE_NAMESPACES = [
1356
+ ...new Set(Object.values(NATIVE_PROVIDERS).map(({ namespace }) => namespace))
1357
+ ];
1358
+ function credentialProxyInferenceUrl(baseUrl) {
1359
+ const trimmed = baseUrl.trim().replace(/\/+$/, "");
1360
+ return /\/v1$/i.test(trimmed) ? trimmed : `${trimmed}/v1`;
1361
+ }
1362
+ function buildCredentialProxyNativeConfig({
1363
+ inferenceBaseUrl,
1364
+ modelDescriptors
1365
+ }) {
1366
+ const baseURL = credentialProxyInferenceUrl(inferenceBaseUrl);
1367
+ const providers = {};
1368
+ const unsupportedProviders = /* @__PURE__ */ new Set();
1369
+ for (const descriptor of modelDescriptors) {
1370
+ const definition = NATIVE_PROVIDERS[descriptor.provider.trim().toLowerCase()];
1371
+ if (!definition) {
1372
+ unsupportedProviders.add(descriptor.provider.trim() || descriptor.provider);
1373
+ continue;
1374
+ }
1375
+ providers[definition.namespace] ??= definition.npm === "@ai-sdk/anthropic" ? {
1376
+ name: definition.name,
1377
+ npm: definition.npm,
1378
+ options: { baseURL, authToken: EVIDENT_PROXY_TOKEN_REFERENCE },
1379
+ models: {}
1380
+ } : definition.npm === "@ai-sdk/openai" ? {
1381
+ name: definition.name,
1382
+ npm: definition.npm,
1383
+ options: { baseURL, apiKey: EVIDENT_PROXY_TOKEN_REFERENCE },
1384
+ models: {}
1385
+ } : {
1386
+ name: definition.name,
1387
+ npm: definition.npm,
1388
+ options: {
1389
+ name: definition.sdkName,
1390
+ baseURL,
1391
+ apiKey: EVIDENT_PROXY_TOKEN_REFERENCE
1392
+ },
1393
+ models: {}
1394
+ };
1395
+ providers[definition.namespace].models[descriptor.id] = { name: descriptor.id };
1396
+ }
1397
+ return {
1398
+ unsupportedProviders: [...unsupportedProviders],
1399
+ config: {
1400
+ $schema: "https://opencode.ai/config.json",
1401
+ provider: providers
1402
+ }
1403
+ };
1404
+ }
1405
+
1290
1406
  // ../../packages/types/src/logging/index.ts
1291
1407
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1292
1408
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1326,7 +1442,7 @@ import ora4 from "ora";
1326
1442
  import { select as select4 } from "@inquirer/prompts";
1327
1443
 
1328
1444
  // src/lib/telemetry.ts
1329
- var CLI_VERSION = (true ? "3.6.1-dev.e0da455" : void 0) ?? process.env.npm_package_version ?? "unknown";
1445
+ var CLI_VERSION = (true ? "3.6.1-dev.eedc5a9" : void 0) ?? process.env.npm_package_version ?? "unknown";
1330
1446
  function getCliVersion() {
1331
1447
  return CLI_VERSION;
1332
1448
  }
@@ -1407,7 +1523,7 @@ async function flushEvents() {
1407
1523
  const controller = new AbortController();
1408
1524
  const timeout = setTimeout(() => controller.abort(), FLUSH_TIMEOUT_MS);
1409
1525
  try {
1410
- const request2 = {
1526
+ const request3 = {
1411
1527
  events,
1412
1528
  client_type: "cli",
1413
1529
  client_version: CLI_VERSION
@@ -1418,7 +1534,7 @@ async function flushEvents() {
1418
1534
  "Content-Type": "application/json",
1419
1535
  Authorization: authHeader
1420
1536
  },
1421
- body: JSON.stringify(request2),
1537
+ body: JSON.stringify(request3),
1422
1538
  signal: controller.signal
1423
1539
  });
1424
1540
  if (!response.ok) {
@@ -2075,7 +2191,8 @@ function createDependencyInstallDiagnosticReporter({
2075
2191
  var FORWARDED_LEVELS_BY_SOURCE = {
2076
2192
  "cli.run": /* @__PURE__ */ new Set(["warn", "error"]),
2077
2193
  opencode: /* @__PURE__ */ new Set(["warn", "error"]),
2078
- "cli.session-cleanup": /* @__PURE__ */ new Set(["info", "warn", "error"])
2194
+ "cli.session-cleanup": /* @__PURE__ */ new Set(["info", "warn", "error"]),
2195
+ "cli.runtime-provenance": /* @__PURE__ */ new Set(["info", "warn", "error"])
2079
2196
  };
2080
2197
  var SEVERITY_BY_LEVEL = {
2081
2198
  info: "info",
@@ -2871,6 +2988,58 @@ async function listAllSessions(port, client) {
2871
2988
  }
2872
2989
  return { sessions };
2873
2990
  }
2991
+ var INTERRUPT_NETWORK_CODES = /* @__PURE__ */ new Set([
2992
+ "ABORT_ERR",
2993
+ "EAI_AGAIN",
2994
+ "ECONNREFUSED",
2995
+ "ECONNRESET",
2996
+ "ENETUNREACH",
2997
+ "ENOTFOUND",
2998
+ "ETIMEDOUT",
2999
+ "UND_ERR_CONNECT_TIMEOUT",
3000
+ "UND_ERR_HEADERS_TIMEOUT",
3001
+ "UND_ERR_SOCKET"
3002
+ ]);
3003
+ function interruptFailureDiagnostic(error2) {
3004
+ const message = error2 instanceof Error ? error2.message : "";
3005
+ const httpStatus = /^OpenCode request failed: HTTP ([1-5]\d{2})(?::|$)/.exec(message)?.[1];
3006
+ if (httpStatus) return `HTTP ${httpStatus}`;
3007
+ const candidates = [error2, error2 instanceof Error ? error2.cause : void 0];
3008
+ for (const candidate of candidates) {
3009
+ if (typeof candidate !== "object" || candidate === null || !("code" in candidate)) continue;
3010
+ const code = candidate.code;
3011
+ if (typeof code === "string" && INTERRUPT_NETWORK_CODES.has(code)) {
3012
+ return redactDiagnosticText(`network ${code}`).slice(0, 120);
3013
+ }
3014
+ }
3015
+ const name = error2 instanceof Error && ["AbortError", "Error", "TimeoutError", "TypeError"].includes(error2.name) ? error2.name : "unknown error";
3016
+ return redactDiagnosticText(`request threw ${name}`).slice(0, 120);
3017
+ }
3018
+ async function interruptSession(port, id, client) {
3019
+ if (client?.version === "v2") {
3020
+ try {
3021
+ await interruptV2Session(client, id);
3022
+ return { kind: "confirmed_stopped" };
3023
+ } catch (error2) {
3024
+ return { kind: "not_confirmed", diagnostic: interruptFailureDiagnostic(error2) };
3025
+ }
3026
+ }
3027
+ try {
3028
+ const res = await requestWithClient(
3029
+ port,
3030
+ client,
3031
+ `/session/${id}/abort`,
3032
+ { method: "POST" },
3033
+ { allowStatuses: ALL_HTTP_STATUSES }
3034
+ );
3035
+ if (res.status >= 200 && res.status < 300) {
3036
+ return { kind: "confirmed_stopped", status: res.status };
3037
+ }
3038
+ return { kind: "not_confirmed", status: res.status };
3039
+ } catch (error2) {
3040
+ return { kind: "threw", diagnostic: interruptFailureDiagnostic(error2) };
3041
+ }
3042
+ }
2874
3043
  async function deleteSession(port, id, client) {
2875
3044
  if (client?.version === "v2") return deleteV2Session(client, id);
2876
3045
  try {
@@ -4221,6 +4390,11 @@ async function listV2Permissions(client, sessionId) {
4221
4390
  return null;
4222
4391
  }
4223
4392
  }
4393
+ async function interruptV2Session(client, sessionId) {
4394
+ await client.request(`/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
4395
+ method: "POST"
4396
+ });
4397
+ }
4224
4398
  async function getV2ActiveSessions(client) {
4225
4399
  try {
4226
4400
  const body = await readJson(await client.request("/api/session/active"));
@@ -4623,11 +4797,11 @@ function failureMessage(status2) {
4623
4797
  function isRetryableStatus(status2) {
4624
4798
  return CONNECT_KEY_RETRY_STATUSES.includes(status2);
4625
4799
  }
4626
- async function importOneCredential(request2, credential, sleepForRetry, log3) {
4800
+ async function importOneCredential(request3, credential, sleepForRetry, log3) {
4627
4801
  const path = `/api/integration/${encodeURIComponent(credential.integrationId)}/connect/key`;
4628
4802
  for (let attempt = 1; attempt <= CONNECT_KEY_MAX_ATTEMPTS; attempt += 1) {
4629
4803
  try {
4630
- const response = await request2(
4804
+ const response = await request3(
4631
4805
  path,
4632
4806
  {
4633
4807
  method: "POST",
@@ -4662,7 +4836,7 @@ async function importOneCredential(request2, credential, sleepForRetry, log3) {
4662
4836
  throw new Error("OpenCode credential import retry loop did not return");
4663
4837
  }
4664
4838
  async function importOpenCodeCredentials({
4665
- request: request2,
4839
+ request: request3,
4666
4840
  classified,
4667
4841
  connectedIntegrationIds,
4668
4842
  sleepForRetry = sleep2,
@@ -4674,7 +4848,7 @@ async function importOpenCodeCredentials({
4674
4848
  result.alreadyConnected.push(credential.integrationId);
4675
4849
  continue;
4676
4850
  }
4677
- const outcome = await importOneCredential(request2, credential, sleepForRetry, log3);
4851
+ const outcome = await importOneCredential(request3, credential, sleepForRetry, log3);
4678
4852
  if (outcome.ok) result.imported.push(credential.integrationId);
4679
4853
  else result.failed.push(outcome.failure);
4680
4854
  }
@@ -4692,7 +4866,7 @@ function parseIntegrationList(value) {
4692
4866
  return { integrationIds, hasData: value.data.length > 0 };
4693
4867
  }
4694
4868
  async function getConnectedOpenCodeIntegrationIds({
4695
- request: request2,
4869
+ request: request3,
4696
4870
  directory,
4697
4871
  sleepForRetry = sleep2,
4698
4872
  log: log3
@@ -4700,7 +4874,7 @@ async function getConnectedOpenCodeIntegrationIds({
4700
4874
  const path = `/api/integration?location%5Bdirectory%5D=${encodeURIComponent(directory)}`;
4701
4875
  for (let attempt = 1; attempt <= INTEGRATION_LIST_MAX_READS; attempt += 1) {
4702
4876
  try {
4703
- const response = await request2(path);
4877
+ const response = await request3(path);
4704
4878
  const parsed = parseIntegrationList(await response.json());
4705
4879
  if (parsed === null) {
4706
4880
  log3(
@@ -4729,7 +4903,7 @@ async function getConnectedOpenCodeIntegrationIds({
4729
4903
  return null;
4730
4904
  }
4731
4905
  async function importOpenCodeV2Credentials({
4732
- request: request2,
4906
+ request: request3,
4733
4907
  homeDir,
4734
4908
  directory,
4735
4909
  sleepForRetry = sleep2,
@@ -4747,7 +4921,7 @@ async function importOpenCodeV2Credentials({
4747
4921
  const classified = classifyOpenCodeCredentials(credentials2);
4748
4922
  if (classified.importable.length === 0) return emptyResult(classified.unsupported);
4749
4923
  const connectedIntegrationIds = await getConnectedOpenCodeIntegrationIds({
4750
- request: request2,
4924
+ request: request3,
4751
4925
  directory,
4752
4926
  sleepForRetry,
4753
4927
  log: log3
@@ -4756,7 +4930,7 @@ async function importOpenCodeV2Credentials({
4756
4930
  return emptyResult(classified.unsupported, "connection-list-unavailable");
4757
4931
  }
4758
4932
  return importOpenCodeCredentials({
4759
- request: request2,
4933
+ request: request3,
4760
4934
  classified,
4761
4935
  connectedIntegrationIds,
4762
4936
  sleepForRetry,
@@ -5447,7 +5621,11 @@ function isSessionDbProvenanceRecord(value) {
5447
5621
  var OPENCODE2_PACKAGE_SPEC = "@opencode-ai/cli@0.0.0-beta-17823";
5448
5622
 
5449
5623
  // src/lib/opencode/opencode-version-gate.ts
5450
- var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
5624
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = [
5625
+ "1.17.11",
5626
+ "1.18.3",
5627
+ "1.18.35"
5628
+ ];
5451
5629
  function isQueueValidatedVersion(version2) {
5452
5630
  if (!version2) return false;
5453
5631
  return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
@@ -6492,6 +6670,7 @@ function connectTunnel(options) {
6492
6670
  }, 3e4);
6493
6671
  let relaySilenceTimeout;
6494
6672
  let relaySilenceTimedOut = false;
6673
+ let relayConnectionId;
6495
6674
  const clearRelaySilenceTimeout = () => {
6496
6675
  if (relaySilenceTimeout === void 0) return;
6497
6676
  clearTimeout(relaySilenceTimeout);
@@ -6577,7 +6756,8 @@ function connectTunnel(options) {
6577
6756
  armRelaySilenceTimeout();
6578
6757
  forwarder.setBinaryFramesSupported(message.binary_frames === true);
6579
6758
  const connectedAgentId = message.agent_id ?? agentId;
6580
- onConnected?.(connectedAgentId);
6759
+ relayConnectionId = message.connection_id;
6760
+ onConnected?.(connectedAgentId, relayConnectionId);
6581
6761
  resolve5({
6582
6762
  ws,
6583
6763
  close: () => ws.close(1e3, "CLI shutdown")
@@ -6614,7 +6794,7 @@ function connectTunnel(options) {
6614
6794
  clearRelaySilenceTimeout();
6615
6795
  const reasonStr = (relaySilenceTimedOut ? "no relay heartbeat for 90s \u2014 reconnecting" : void 0) || reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
6616
6796
  forwarder.abortAll();
6617
- onDisconnected?.(code, reasonStr);
6797
+ onDisconnected?.(code, reasonStr, relayConnectionId);
6618
6798
  });
6619
6799
  });
6620
6800
  }
@@ -6677,7 +6857,7 @@ var RunnerConnection = class _RunnerConnection {
6677
6857
  authHeader: this.opts.getAuthHeader(),
6678
6858
  port: this.opts.port,
6679
6859
  openCodePassword: this.opts.openCodePassword,
6680
- onConnected: (agentId) => {
6860
+ onConnected: (agentId, relayConnectionId) => {
6681
6861
  const attempt = this.reconnectAttempt + 1;
6682
6862
  this.reconnectAttempt = 0;
6683
6863
  this.reconnecting = false;
@@ -6687,13 +6867,17 @@ var RunnerConnection = class _RunnerConnection {
6687
6867
  this.disconnectedAtMs = null;
6688
6868
  events.onConnected(agentId, isReconnect, {
6689
6869
  generation: this.generation,
6870
+ relayConnectionId: relayConnectionId ?? null,
6690
6871
  attempt,
6691
6872
  downtimeMs
6692
6873
  });
6693
6874
  },
6694
- onDisconnected: (code, reason) => {
6875
+ onDisconnected: (code, reason, relayConnectionId) => {
6695
6876
  this.disconnectedAtMs = this.now();
6696
- events.onDisconnected(code, reason, { generation: this.generation });
6877
+ events.onDisconnected(code, reason, {
6878
+ generation: this.generation,
6879
+ relayConnectionId: relayConnectionId ?? null
6880
+ });
6697
6881
  const relayRequestedReconnect = code === 1e3 && _RunnerConnection.RELAY_RECONNECT_CLOSE_REASONS.has(reason);
6698
6882
  if (this.opts.isRunning() && (code !== 1e3 || relayRequestedReconnect) && !this.reconnecting) {
6699
6883
  this.reconnectPromise = this.connectWithRetry(true).catch((err) => {
@@ -7141,8 +7325,8 @@ import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/p
7141
7325
  import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
7142
7326
  var FILE_MODE = 384;
7143
7327
  var DIRECTORY_MODE = 448;
7144
- async function writePushedFile(request2) {
7145
- const { requestedPath, content, allowedDirectories, homeDir } = request2;
7328
+ async function writePushedFile(request3) {
7329
+ const { requestedPath, content, allowedDirectories, homeDir } = request3;
7146
7330
  const bytes = content.byteLength;
7147
7331
  if (allowedDirectories.length === 0) {
7148
7332
  return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
@@ -8891,6 +9075,34 @@ var ChannelDriver = class _ChannelDriver {
8891
9075
  if (state === "failed" && isAbortedTerminalReply(messages, ocId ?? "")) {
8892
9076
  const ongoing = await this.isSessionOngoing(sessionId);
8893
9077
  if (ongoing === false) {
9078
+ const age = this.absoluteAgeForRow(message.processing_started_at);
9079
+ if (age.tripped && age.anchorMs !== null) {
9080
+ try {
9081
+ await this.markFailed(
9082
+ conv.id,
9083
+ message.id,
9084
+ sessionId,
9085
+ this.absoluteCeilingError(message.id, sessionId, age.anchorMs),
9086
+ void 0,
9087
+ {
9088
+ classification: null,
9089
+ errorShape: extractReplyErrorShape(findLastAssistantReplyFor(messages, ocId ?? ""))
9090
+ }
9091
+ );
9092
+ } catch (err) {
9093
+ if (err instanceof ChannelAuthError) throw err;
9094
+ this.log({
9095
+ level: "warn",
9096
+ message: `Re-drive: failed to report past-ceiling restart orphan ${message.id.slice(0, 8)} terminal; refusing to re-dispatch: ${err instanceof Error ? err.message : String(err)}`,
9097
+ conversation_id: conv.id,
9098
+ message_id: message.id
9099
+ });
9100
+ return "unresolved";
9101
+ }
9102
+ this.clearRedriveUnresolved(message.id);
9103
+ void this.postSignal(conv.id, message.id, "redrive_ceiling_refused");
9104
+ return "settled";
9105
+ }
8894
9106
  this.log({
8895
9107
  level: "info",
8896
9108
  message: `Re-drive: message ${message.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per the active-session status check \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
@@ -8961,6 +9173,29 @@ var ChannelDriver = class _ChannelDriver {
8961
9173
  message_id: message.id
8962
9174
  });
8963
9175
  }
9176
+ if (this.absoluteAgeForRow(message.processing_started_at).tripped) {
9177
+ try {
9178
+ await this.markFailed(
9179
+ conv.id,
9180
+ message.id,
9181
+ sessionId,
9182
+ this.absoluteCeilingError(message.id, sessionId, anchorMs)
9183
+ );
9184
+ } catch (err) {
9185
+ if (err instanceof ChannelAuthError) throw err;
9186
+ this.log({
9187
+ level: "warn",
9188
+ message: `Re-drive: failed to report past-ceiling message ${message.id.slice(0, 8)} terminal; refusing to re-attach: ${err instanceof Error ? err.message : String(err)}`,
9189
+ conversation_id: conv.id,
9190
+ message_id: message.id
9191
+ });
9192
+ const bound = await this.boundRedriveOutcome(conv, message, "reattach");
9193
+ return bound === "abandoned" ? "abandoned" : "unresolved";
9194
+ }
9195
+ this.clearRedriveUnresolved(message.id);
9196
+ void this.postSignal(conv.id, message.id, "redrive_ceiling_refused");
9197
+ return "abandoned";
9198
+ }
8964
9199
  const title = await this.resolveSessionTitle(sessionId, conv.id);
8965
9200
  try {
8966
9201
  await this.markProcessing(conv.id, message.id, sessionId, ocId, title);
@@ -9227,8 +9462,7 @@ var ChannelDriver = class _ChannelDriver {
9227
9462
  const since = this.redriveOutcomeFailingSince.get(message.id);
9228
9463
  if (since === void 0) this.redriveOutcomeFailingSince.set(message.id, now);
9229
9464
  const durationTripped = now - (since ?? now) >= this.pausedMaxWaitMs;
9230
- const parsed = message.processing_started_at ? Date.parse(message.processing_started_at) : NaN;
9231
- const absoluteAgeTripped = !Number.isNaN(parsed) && now - parsed >= ABSOLUTE_MAX_PROCESSING_MS;
9465
+ const absoluteAgeTripped = this.absoluteAgeForRow(message.processing_started_at).tripped;
9232
9466
  if (!durationTripped && !absoluteAgeTripped) {
9233
9467
  this.signalRedriveOutcomeUnreported(conv, message, outcome);
9234
9468
  return "retry";
@@ -9267,6 +9501,15 @@ var ChannelDriver = class _ChannelDriver {
9267
9501
  });
9268
9502
  return "abandoned";
9269
9503
  }
9504
+ /** Row-level guards use the durable server stamp; in-flight guards use processingAnchorMs. */
9505
+ absoluteAgeForRow(stamp) {
9506
+ const anchorMs = stamp ? Date.parse(stamp) : NaN;
9507
+ return Number.isNaN(anchorMs) ? { tripped: false, anchorMs: null } : { tripped: this.now() - anchorMs >= ABSOLUTE_MAX_PROCESSING_MS, anchorMs };
9508
+ }
9509
+ absoluteCeilingError(messageId, sessionId, anchorMs, retainedReason = this.readRetainedSessionError(sessionId)) {
9510
+ const baseError = `Message ${messageId.slice(0, 8)} exceeded the absolute processing ceiling (${Math.round((this.now() - anchorMs) / 6e4)}min, session ${sessionId}) while still actively running.`;
9511
+ return retainedReason ? `${baseError} ${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}` : baseError;
9512
+ }
9270
9513
  /**
9271
9514
  * Record one poll outcome toward the re-drive fence's consecutive-identical-
9272
9515
  * failure streak (#1348) and return the resulting count. `signature === null`
@@ -9708,10 +9951,7 @@ var ChannelDriver = class _ChannelDriver {
9708
9951
  opencodeMessageId,
9709
9952
  message,
9710
9953
  dispatchedAt: this.now(),
9711
- // Anchor the absolute-age ceiling to the SERVER-SIDE `processed_at`, NOT
9712
- // `dispatchedAt` — so a re-adopted zombie's age reflects the real turn duration
9713
- // and the ceiling fires on the ORIGINAL turn.
9714
- processingAnchorMs: processedAtMs,
9954
+ processingAnchorMs: this.absoluteAgeForRow(message.processing_started_at).anchorMs ?? processedAtMs,
9715
9955
  deadline: watchDeadlineAnchorMs + this.pausedMaxWaitMs,
9716
9956
  // The server row is ALREADY `processing`; do not re-fire markProcessing.
9717
9957
  started: true,
@@ -10162,7 +10402,9 @@ var ChannelDriver = class _ChannelDriver {
10162
10402
  }
10163
10403
  const { openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk } = await this.pollInteractions(sessionId, watcher, messages);
10164
10404
  if (watcher.generation !== generation) return;
10405
+ const ceilingAttemptsThisTick = /* @__PURE__ */ new Set();
10165
10406
  for (const inFlight of [...watcher.inFlight.values()]) {
10407
+ if (ceilingAttemptsThisTick.has(inFlight.evidentMessageId)) continue;
10166
10408
  await this.serviceInFlightMessage(
10167
10409
  sessionId,
10168
10410
  watcher,
@@ -10171,7 +10413,8 @@ var ChannelDriver = class _ChannelDriver {
10171
10413
  openQuestions,
10172
10414
  openPermissions,
10173
10415
  questionsPolledOk,
10174
- permissionsPolledOk
10416
+ permissionsPolledOk,
10417
+ ceilingAttemptsThisTick
10175
10418
  );
10176
10419
  }
10177
10420
  }
@@ -10212,13 +10455,117 @@ var ChannelDriver = class _ChannelDriver {
10212
10455
  inFlight.deadline = this.now() + this.pausedMaxWaitMs;
10213
10456
  }
10214
10457
  }
10458
+ async settleAbsoluteCeiling(sessionId, watcher, messages, ceilingAttemptsThisTick) {
10459
+ const entries = [...watcher.inFlight.values()];
10460
+ const pastCeiling = entries.filter(
10461
+ (entry) => this.now() - entry.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS
10462
+ );
10463
+ const healthySiblings = entries.length - pastCeiling.length;
10464
+ const landed = [];
10465
+ let allRecordsLanded = true;
10466
+ const retainedReason = this.readRetainedSessionError(sessionId);
10467
+ for (const entry of pastCeiling) {
10468
+ if (!watcher.inFlight.has(entry.evidentMessageId)) continue;
10469
+ ceilingAttemptsThisTick.add(entry.evidentMessageId);
10470
+ const error2 = this.absoluteCeilingError(
10471
+ entry.evidentMessageId,
10472
+ sessionId,
10473
+ entry.processingAnchorMs,
10474
+ retainedReason
10475
+ );
10476
+ this.log({
10477
+ level: "warn",
10478
+ message: error2,
10479
+ conversation_id: watcher.conv.id,
10480
+ message_id: entry.evidentMessageId
10481
+ });
10482
+ try {
10483
+ await this.markFailed(
10484
+ watcher.conv.id,
10485
+ entry.evidentMessageId,
10486
+ sessionId,
10487
+ error2,
10488
+ void 0,
10489
+ {
10490
+ classification: null,
10491
+ errorShape: extractReplyErrorShape(
10492
+ findLastAssistantReplyFor(messages, entry.opencodeMessageId)
10493
+ )
10494
+ }
10495
+ );
10496
+ } catch (err) {
10497
+ if (err instanceof ChannelAuthError) throw err;
10498
+ allRecordsLanded = false;
10499
+ const watched_for_ms = this.now() - entry.processingAnchorMs;
10500
+ if (err instanceof ChannelTerminalError) {
10501
+ void this.postSignal(watcher.conv.id, entry.evidentMessageId, "gave_up", {
10502
+ watched_for_ms,
10503
+ interrupt_outcome: "record_terminal"
10504
+ });
10505
+ this.removeInFlight(watcher, entry.evidentMessageId);
10506
+ continue;
10507
+ }
10508
+ if (this.now() >= entry.deadline) {
10509
+ void this.postSignal(watcher.conv.id, entry.evidentMessageId, "gave_up", {
10510
+ watched_for_ms,
10511
+ interrupt_outcome: "record_deadline"
10512
+ });
10513
+ this.removeInFlight(watcher, entry.evidentMessageId);
10514
+ continue;
10515
+ }
10516
+ void this.postSignal(watcher.conv.id, entry.evidentMessageId, "gave_up", {
10517
+ watched_for_ms,
10518
+ interrupt_outcome: "record_retry"
10519
+ });
10520
+ this.log({
10521
+ level: "warn",
10522
+ message: `Failed to record the absolute-ceiling failure for message ${entry.evidentMessageId.slice(0, 8)}; leaving its running turn untouched and retrying next tick: ${err instanceof Error ? err.message : String(err)}`,
10523
+ conversation_id: watcher.conv.id,
10524
+ message_id: entry.evidentMessageId
10525
+ });
10526
+ continue;
10527
+ }
10528
+ entry.done = true;
10529
+ landed.push(entry);
10530
+ }
10531
+ if (!allRecordsLanded) {
10532
+ for (const entry of landed) this.removeInFlight(watcher, entry.evidentMessageId);
10533
+ return;
10534
+ }
10535
+ if (healthySiblings > 0) {
10536
+ for (const entry of landed) {
10537
+ void this.postSignal(watcher.conv.id, entry.evidentMessageId, "gave_up", {
10538
+ watched_for_ms: this.now() - entry.processingAnchorMs,
10539
+ interrupt_outcome: "deferred_for_healthy_sibling",
10540
+ healthy_siblings: healthySiblings
10541
+ });
10542
+ this.removeInFlight(watcher, entry.evidentMessageId);
10543
+ }
10544
+ return;
10545
+ }
10546
+ const interrupt = await interruptSession(this.port, sessionId, this.openCodeClient);
10547
+ for (const entry of landed) {
10548
+ void this.postSignal(watcher.conv.id, entry.evidentMessageId, "gave_up", {
10549
+ watched_for_ms: this.now() - entry.processingAnchorMs,
10550
+ interrupt_outcome: interrupt.kind
10551
+ });
10552
+ this.removeInFlight(watcher, entry.evidentMessageId);
10553
+ }
10554
+ if (interrupt.kind !== "confirmed_stopped") {
10555
+ this.log({
10556
+ level: "warn",
10557
+ message: `Absolute-ceiling records landed for session ${sessionId}, but OpenCode interruption was ${interrupt.kind}${interrupt.diagnostic ? ` (${interrupt.diagnostic})` : "status" in interrupt && typeof interrupt.status === "number" ? ` (HTTP ${interrupt.status})` : ""}; the rows are terminal and released, while the session may still be running`,
10558
+ conversation_id: watcher.conv.id
10559
+ });
10560
+ }
10561
+ }
10215
10562
  /**
10216
10563
  * Drive ONE in-flight message's lifecycle from the tick's message snapshot.
10217
10564
  * Fires markProcessing on queued→running and markDone on done (each once),
10218
10565
  * applies the idle-path re-dispatch guard, and removes the message from the
10219
10566
  * in-flight set on completion or timeout.
10220
10567
  */
10221
- async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk) {
10568
+ async serviceInFlightMessage(sessionId, watcher, inFlight, messages, openQuestions, openPermissions, questionsPolledOk, permissionsPolledOk, ceilingAttemptsThisTick) {
10222
10569
  const conv = watcher.conv;
10223
10570
  const state = messageRunState(messages, inFlight.opencodeMessageId);
10224
10571
  const id = inFlight.evidentMessageId;
@@ -10562,17 +10909,8 @@ var ChannelDriver = class _ChannelDriver {
10562
10909
  return;
10563
10910
  }
10564
10911
  }
10565
- if (activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
10566
- this.log({
10567
- level: "warn",
10568
- 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`,
10569
- conversation_id: conv.id,
10570
- message_id: inFlight.evidentMessageId
10571
- });
10572
- void this.postSignal(conv.id, inFlight.evidentMessageId, "gave_up", {
10573
- watched_for_ms: this.now() - inFlight.processingAnchorMs
10574
- });
10575
- this.removeInFlight(watcher, inFlight.evidentMessageId);
10912
+ if (watcher.inFlight.has(inFlight.evidentMessageId) && activelyRunning && this.now() - inFlight.processingAnchorMs >= ABSOLUTE_MAX_PROCESSING_MS) {
10913
+ await this.settleAbsoluteCeiling(sessionId, watcher, messages, ceilingAttemptsThisTick);
10576
10914
  return;
10577
10915
  }
10578
10916
  const heartbeatDue = activelyRunning && !inFlight.awaitingHumanLatched && !inFlight.aliveInFlight && this.now() - inFlight.lastAliveAt >= HEARTBEAT_MS;
@@ -11195,6 +11533,33 @@ var ChannelDriver = class _ChannelDriver {
11195
11533
  }
11196
11534
  const restartAborted = state === "failed" && sessionOngoing === false && isAbortedTerminalReply(messages, ocId ?? "");
11197
11535
  if (restartAborted) {
11536
+ const age = this.absoluteAgeForRow(row.processing_started_at);
11537
+ if (age.tripped && age.anchorMs !== null) {
11538
+ try {
11539
+ await this.markFailed(
11540
+ row.conversation_id,
11541
+ row.id,
11542
+ sessionId,
11543
+ this.absoluteCeilingError(row.id, sessionId, age.anchorMs),
11544
+ void 0,
11545
+ {
11546
+ classification: null,
11547
+ errorShape: extractReplyErrorShape(findLastAssistantReplyFor(messages, ocId ?? ""))
11548
+ }
11549
+ );
11550
+ } catch (err) {
11551
+ if (err instanceof ChannelAuthError) throw err;
11552
+ this.log({
11553
+ level: "warn",
11554
+ message: `Re-adopt: failed to report past-ceiling restart orphan ${row.id.slice(0, 8)} terminal; refusing to re-dispatch: ${err instanceof Error ? err.message : String(err)}`,
11555
+ conversation_id: row.conversation_id,
11556
+ message_id: row.id
11557
+ });
11558
+ return;
11559
+ }
11560
+ void this.postSignal(row.conversation_id, row.id, "redrive_ceiling_refused");
11561
+ return;
11562
+ }
11198
11563
  this.log({
11199
11564
  level: "info",
11200
11565
  message: `Re-adopt: message ${row.id.slice(0, 8)} carries an abort-shaped terminal error and session ${sessionId.slice(0, 8)} is not-ongoing per the active-session status check \u2014 restart orphan, re-dispatching instead of marking it permanently failed`,
@@ -11740,7 +12105,8 @@ var ChannelDriver = class _ChannelDriver {
11740
12105
  source_message_id: row.source_message_id,
11741
12106
  slack_user_id: row.slack_user_id,
11742
12107
  attachments: row.attachments ?? null,
11743
- opencode_message_id: row.opencode_message_id
12108
+ opencode_message_id: row.opencode_message_id,
12109
+ processing_started_at: row.processing_started_at
11744
12110
  };
11745
12111
  }
11746
12112
  /**
@@ -13538,6 +13904,22 @@ async function configureGitHubAccess({ env, log: log3 }) {
13538
13904
  import { execFileSync as execFileSync2 } from "node:child_process";
13539
13905
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
13540
13906
  import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
13907
+ function parseConfigContent(content) {
13908
+ if (!content?.trim()) return {};
13909
+ const parsed = JSON.parse(content);
13910
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
13911
+ throw new Error("OPENCODE_CONFIG_CONTENT must contain a JSON object");
13912
+ }
13913
+ return parsed;
13914
+ }
13915
+ function mergeManagedOpenCodeConfigContent(content, managedProviders) {
13916
+ const config = parseConfigContent(content);
13917
+ const provider = typeof config.provider === "object" && config.provider !== null && !Array.isArray(config.provider) ? { ...config.provider } : {};
13918
+ for (const namespace of CREDENTIAL_PROXY_NATIVE_NAMESPACES) {
13919
+ delete provider[namespace];
13920
+ }
13921
+ return JSON.stringify({ ...config, provider: { ...provider, ...managedProviders } });
13922
+ }
13541
13923
  function isFile(filePath) {
13542
13924
  return existsSync2(filePath) && statSync6(filePath).isFile();
13543
13925
  }
@@ -13571,6 +13953,159 @@ function applyRunnerOpenCodeConfig({
13571
13953
  log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
13572
13954
  }
13573
13955
 
13956
+ // src/lib/opencode/runtime-provenance.ts
13957
+ import { readFileSync as readFileSync7, readdirSync } from "node:fs";
13958
+ import { homedir as homedir7 } from "node:os";
13959
+ import { join as join12 } from "node:path";
13960
+ var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
13961
+ var REGISTRY_SPEC = /^[a-z0-9.*+^~<>=|-]+$/i;
13962
+ function errorKind(error2) {
13963
+ if (!(error2 instanceof Error)) return "unknown error";
13964
+ const code = "code" in error2 && typeof error2.code === "string" ? ` (${error2.code})` : "";
13965
+ return `${error2.name}${code}`;
13966
+ }
13967
+ function parseRegistryPluginSpec(value) {
13968
+ const separator = value.lastIndexOf("@");
13969
+ if (separator <= 0) return null;
13970
+ const name = value.slice(0, separator);
13971
+ const spec = value.slice(separator + 1);
13972
+ if (!PACKAGE_NAME.test(name) || !REGISTRY_SPEC.test(spec)) return null;
13973
+ return { name, spec };
13974
+ }
13975
+ function parseJsonc(value) {
13976
+ let output = "";
13977
+ let inString = false;
13978
+ let escaped = false;
13979
+ let lineComment = false;
13980
+ let blockComment = false;
13981
+ for (let index = 0; index < value.length; index++) {
13982
+ const character = value[index];
13983
+ const next = value[index + 1];
13984
+ if (lineComment) {
13985
+ if (character === "\n") {
13986
+ lineComment = false;
13987
+ output += character;
13988
+ }
13989
+ continue;
13990
+ }
13991
+ if (blockComment) {
13992
+ if (character === "*" && next === "/") {
13993
+ blockComment = false;
13994
+ index++;
13995
+ } else if (character === "\n") {
13996
+ output += character;
13997
+ }
13998
+ continue;
13999
+ }
14000
+ if (inString) {
14001
+ output += character;
14002
+ if (escaped) escaped = false;
14003
+ else if (character === "\\") escaped = true;
14004
+ else if (character === '"') inString = false;
14005
+ continue;
14006
+ }
14007
+ if (character === '"') {
14008
+ inString = true;
14009
+ output += character;
14010
+ } else if (character === "/" && next === "/") {
14011
+ lineComment = true;
14012
+ index++;
14013
+ } else if (character === "/" && next === "*") {
14014
+ blockComment = true;
14015
+ index++;
14016
+ } else if (character === ",") {
14017
+ let lookahead = index + 1;
14018
+ while (/\s/.test(value[lookahead] ?? "")) lookahead++;
14019
+ if (value[lookahead] !== "]" && value[lookahead] !== "}") output += character;
14020
+ } else {
14021
+ output += character;
14022
+ }
14023
+ }
14024
+ return JSON.parse(output);
14025
+ }
14026
+ function openCodeCacheRoot(env = process.env, homeDir = homedir7()) {
14027
+ return join12(env.XDG_CACHE_HOME ?? join12(homeDir, ".cache"), "opencode");
14028
+ }
14029
+ function readConfiguredPluginSpecs({
14030
+ cwd = process.cwd(),
14031
+ log: log3
14032
+ }) {
14033
+ let config;
14034
+ try {
14035
+ try {
14036
+ config = parseJsonc(readFileSync7(join12(cwd, "opencode.jsonc"), "utf8"));
14037
+ } catch (error2) {
14038
+ if (!("code" in Object(error2)) || Object(error2).code !== "ENOENT") throw error2;
14039
+ config = parseJsonc(readFileSync7(join12(cwd, "opencode.json"), "utf8"));
14040
+ }
14041
+ } catch (error2) {
14042
+ log3(`Could not read OpenCode plugin configuration: ${errorKind(error2)}`);
14043
+ return [];
14044
+ }
14045
+ if (typeof config !== "object" || config === null || !("plugin" in config)) return [];
14046
+ const plugins = config.plugin;
14047
+ if (!Array.isArray(plugins)) {
14048
+ log3("Could not read OpenCode plugin configuration: plugin is not an array");
14049
+ return [];
14050
+ }
14051
+ const configured = plugins.filter(
14052
+ (plugin) => typeof plugin === "string" && parseRegistryPluginSpec(plugin) !== null
14053
+ );
14054
+ if (configured.length !== plugins.length) {
14055
+ log3(
14056
+ `Skipped ${plugins.length - configured.length} non-registry OpenCode plugin spec(s); their values were not recorded`
14057
+ );
14058
+ }
14059
+ return configured;
14060
+ }
14061
+ function resolveInstalledPluginVersions({
14062
+ cacheRoot,
14063
+ env = process.env,
14064
+ homeDir = homedir7(),
14065
+ log: log3
14066
+ }) {
14067
+ const packagesRoot = join12(cacheRoot ?? openCodeCacheRoot(env, homeDir), "packages");
14068
+ let directories;
14069
+ try {
14070
+ directories = readdirSync(packagesRoot, { withFileTypes: true });
14071
+ } catch (error2) {
14072
+ if ("code" in Object(error2) && Object(error2).code === "ENOENT") return [];
14073
+ log3(`Could not inspect the OpenCode plugin cache: ${errorKind(error2)}`);
14074
+ return [];
14075
+ }
14076
+ const plugins = [];
14077
+ let skipped = 0;
14078
+ for (const directory of directories) {
14079
+ if (!directory.isDirectory()) continue;
14080
+ const parsed = parseRegistryPluginSpec(directory.name);
14081
+ if (parsed === null) {
14082
+ skipped++;
14083
+ continue;
14084
+ }
14085
+ let resolvedVersion = null;
14086
+ try {
14087
+ const packageJson = JSON.parse(
14088
+ readFileSync7(
14089
+ join12(packagesRoot, directory.name, "node_modules", parsed.name, "package.json"),
14090
+ "utf8"
14091
+ )
14092
+ );
14093
+ if (typeof packageJson.version === "string" && REGISTRY_SPEC.test(packageJson.version)) {
14094
+ resolvedVersion = packageJson.version;
14095
+ } else {
14096
+ log3(`Could not resolve OpenCode plugin ${parsed.name}@${parsed.spec}: invalid version`);
14097
+ }
14098
+ } catch (error2) {
14099
+ log3(`Could not resolve OpenCode plugin ${parsed.name}@${parsed.spec}: ${errorKind(error2)}`);
14100
+ }
14101
+ plugins.push({ ...parsed, resolvedVersion });
14102
+ }
14103
+ if (skipped > 0) {
14104
+ log3(`Skipped ${skipped} non-registry OpenCode package cache entry; its value was not recorded`);
14105
+ }
14106
+ return plugins;
14107
+ }
14108
+
13574
14109
  // src/lib/credential-sync.ts
13575
14110
  import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
13576
14111
  var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
@@ -13806,6 +14341,226 @@ function createCredentialSync({
13806
14341
  };
13807
14342
  }
13808
14343
 
14344
+ // src/lib/managed-inference-setup.ts
14345
+ var defaultStore = {
14346
+ get: getManagedInferenceCredential,
14347
+ set: setManagedInferenceCredential,
14348
+ clear: clearManagedInferenceCredential
14349
+ };
14350
+ function endpoint(options, operation) {
14351
+ return `${options.apiUrl}/runners/${options.agentId}/managed-credentials/${operation}`;
14352
+ }
14353
+ function requestHeaders(options) {
14354
+ return { Authorization: options.getAuthHeader(), "Content-Type": "application/json" };
14355
+ }
14356
+ function request2(options) {
14357
+ return withRequestTimeout(options.fetchImpl ?? fetch, REQUEST_TIMEOUT_MS);
14358
+ }
14359
+ function safeFailure(operation, status2) {
14360
+ return status2 === void 0 ? `${operation} could not reach the managed credential service` : `${operation} returned HTTP ${status2}`;
14361
+ }
14362
+ function logTransportFailure(options, operation, error2, authorization) {
14363
+ let detail = error2 instanceof Error ? error2.message : String(error2);
14364
+ const credential = authorization.split(/\s+/, 2)[1];
14365
+ for (const secret of [authorization, credential]) {
14366
+ if (secret) detail = detail.replaceAll(secret, "[redacted]");
14367
+ }
14368
+ options.log(
14369
+ `MANAGED-INFERENCE-TRANSPORT-FAILED: operation=${operation} detail=${redactDiagnosticText(detail)}`,
14370
+ "debug"
14371
+ );
14372
+ }
14373
+ async function responseJson(response) {
14374
+ try {
14375
+ const value = await response.json();
14376
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
14377
+ } catch (error2) {
14378
+ return null;
14379
+ }
14380
+ }
14381
+ function readSetup(value) {
14382
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14383
+ const setup = value;
14384
+ if (typeof setup.runner_id !== "string" || typeof setup.generation !== "string" || typeof setup.status !== "string" || setup.token_id !== null && typeof setup.token_id !== "string") {
14385
+ return null;
14386
+ }
14387
+ return setup;
14388
+ }
14389
+ function clearLocalSetup(options) {
14390
+ const env = options.env ?? process.env;
14391
+ (options.store ?? defaultStore).clear(options.agentId);
14392
+ delete env.EVIDENT_PROXY_TOKEN;
14393
+ }
14394
+ async function discoverManagedInferenceSetup(options) {
14395
+ const headers = requestHeaders(options);
14396
+ let response;
14397
+ try {
14398
+ response = await request2(options)(endpoint(options, "current"), {
14399
+ headers
14400
+ });
14401
+ } catch (error2) {
14402
+ logTransportFailure(options, "discovery", error2, headers.Authorization);
14403
+ return { kind: "failed", reason: safeFailure("Managed setup discovery") };
14404
+ }
14405
+ if (response.status === 404) {
14406
+ clearLocalSetup(options);
14407
+ return { kind: "none" };
14408
+ }
14409
+ if (!response.ok) {
14410
+ return { kind: "failed", reason: safeFailure("Managed setup discovery", response.status) };
14411
+ }
14412
+ const body = await responseJson(response);
14413
+ const setup = readSetup(body?.setup);
14414
+ return setup ? { kind: "setup", setup } : { kind: "failed", reason: "Managed setup discovery returned an invalid response" };
14415
+ }
14416
+ async function post(options, operation, body) {
14417
+ const headers = requestHeaders(options);
14418
+ try {
14419
+ return await request2(options)(endpoint(options, operation), {
14420
+ method: "POST",
14421
+ headers,
14422
+ body: JSON.stringify(body)
14423
+ });
14424
+ } catch (error2) {
14425
+ logTransportFailure(options, operation, error2, headers.Authorization);
14426
+ return null;
14427
+ }
14428
+ }
14429
+ function applyCredential(options, credential) {
14430
+ const env = options.env ?? process.env;
14431
+ let merged;
14432
+ if (options.autoConfigureCredentialsProxy) {
14433
+ const { config, unsupportedProviders } = buildCredentialProxyNativeConfig({
14434
+ inferenceBaseUrl: credential.inferenceBaseUrl,
14435
+ modelDescriptors: credential.modelDescriptors
14436
+ });
14437
+ if (unsupportedProviders.length > 0 || Object.keys(config.provider).length === 0) {
14438
+ return "Managed setup contains unsupported provider descriptors";
14439
+ }
14440
+ try {
14441
+ merged = mergeManagedOpenCodeConfigContent(env.OPENCODE_CONFIG_CONTENT, config.provider);
14442
+ } catch (error2) {
14443
+ return "OPENCODE_CONFIG_CONTENT is malformed; managed providers were not installed";
14444
+ }
14445
+ }
14446
+ try {
14447
+ (options.store ?? defaultStore).set(options.agentId, credential);
14448
+ } catch (error2) {
14449
+ const detail = (error2 instanceof Error ? error2.message : String(error2)).replaceAll(
14450
+ credential.token,
14451
+ "[redacted]"
14452
+ );
14453
+ options.log(
14454
+ `MANAGED-INFERENCE-STORE-FAILED: runner=${options.agentId} generation=${credential.generation} detail=${redactDiagnosticText(detail)}`,
14455
+ "warn"
14456
+ );
14457
+ return "Managed credentials could not be written to the protected store";
14458
+ }
14459
+ env.EVIDENT_PROXY_TOKEN = credential.token;
14460
+ if (merged !== void 0) env.OPENCODE_CONFIG_CONTENT = merged;
14461
+ return null;
14462
+ }
14463
+ async function reportManagedInferenceApplyFailure(options, failure) {
14464
+ const response = await post(options, "report-failure", {
14465
+ generation: failure.generation,
14466
+ token_id: failure.tokenId
14467
+ });
14468
+ if (!response?.ok) {
14469
+ options.log(
14470
+ `MANAGED-INFERENCE-REPORT-FAILED: runner=${options.agentId} generation=${failure.generation}${response ? ` status=${response.status}` : ""}`,
14471
+ "warn"
14472
+ );
14473
+ }
14474
+ }
14475
+ async function reaffirmStored(options, credential) {
14476
+ const response = await post(options, "reaffirm", {
14477
+ generation: credential.generation,
14478
+ token_id: credential.tokenId
14479
+ });
14480
+ if (!response?.ok) {
14481
+ return {
14482
+ kind: "failed",
14483
+ reason: response?.status === 409 ? "Stored managed credential no longer matches this setup; restart required" : response ? safeFailure("Managed credential reaffirmation", response.status) : safeFailure("Managed credential reaffirmation")
14484
+ };
14485
+ }
14486
+ const body = await responseJson(response);
14487
+ const setup = readSetup(body?.setup);
14488
+ if (!setup || setup.generation !== credential.generation || setup.token_id !== credential.tokenId) {
14489
+ return { kind: "failed", reason: "Managed credential reaffirmation returned a mismatch" };
14490
+ }
14491
+ const failure = applyCredential(options, credential);
14492
+ return failure ? { kind: "failed", reason: failure } : { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
14493
+ }
14494
+ async function prepareManagedInferenceSetup(options, discovery, health) {
14495
+ if (health.authFailed) {
14496
+ return {
14497
+ kind: "failed",
14498
+ reason: "OpenCode authentication failed; managed credentials were not rotated"
14499
+ };
14500
+ }
14501
+ const stored = (options.store ?? defaultStore).get(options.agentId);
14502
+ if (health.healthy) {
14503
+ if (!stored) {
14504
+ return {
14505
+ kind: "failed",
14506
+ reason: "Managed credentials are missing for the serving OpenCode process; restart required"
14507
+ };
14508
+ }
14509
+ return reaffirmStored(options, stored);
14510
+ }
14511
+ if (discovery.setup.status === "acknowledged" && stored?.generation === discovery.setup.generation && stored.tokenId === discovery.setup.token_id) {
14512
+ return reaffirmStored(options, stored);
14513
+ }
14514
+ const response = await post(options, "bootstrap", { generation: discovery.setup.generation });
14515
+ if (!response?.ok) {
14516
+ return {
14517
+ kind: "failed",
14518
+ reason: response ? safeFailure("Managed credential bootstrap", response.status) : safeFailure("Managed credential bootstrap")
14519
+ };
14520
+ }
14521
+ const body = await responseJson(response);
14522
+ const setup = readSetup(body?.setup);
14523
+ const token = body?.inference_token;
14524
+ const inferenceBaseUrl = body?.inference_base_url;
14525
+ const modelDescriptors = body?.model_descriptors;
14526
+ if (!setup || setup.generation !== discovery.setup.generation || typeof setup.token_id !== "string" || typeof token !== "string" || typeof inferenceBaseUrl !== "string" || !Array.isArray(modelDescriptors) || !modelDescriptors.every(
14527
+ (descriptor) => typeof descriptor === "object" && descriptor !== null && typeof descriptor.id === "string" && typeof descriptor.provider === "string"
14528
+ )) {
14529
+ return { kind: "failed", reason: "Managed credential bootstrap returned an invalid response" };
14530
+ }
14531
+ const credential = {
14532
+ generation: setup.generation,
14533
+ tokenId: setup.token_id,
14534
+ token,
14535
+ inferenceBaseUrl,
14536
+ modelDescriptors
14537
+ };
14538
+ const failure = applyCredential(options, credential);
14539
+ if (failure) {
14540
+ await reportManagedInferenceApplyFailure(options, credential);
14541
+ return { kind: "failed", reason: failure };
14542
+ }
14543
+ return { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
14544
+ }
14545
+ async function acknowledgeManagedInferenceSetup(options, preparation) {
14546
+ const response = await post(options, "acknowledge", {
14547
+ generation: preparation.generation,
14548
+ token_id: preparation.tokenId,
14549
+ config_validated: options.autoConfigureCredentialsProxy === true
14550
+ });
14551
+ if (!response?.ok) {
14552
+ throw new Error(
14553
+ response ? safeFailure("Managed credential acknowledgment", response.status) : safeFailure("Managed credential acknowledgment")
14554
+ );
14555
+ }
14556
+ const body = await responseJson(response);
14557
+ const setup = readSetup(body?.setup);
14558
+ if (!setup || setup.generation !== preparation.generation || setup.token_id !== preparation.tokenId) {
14559
+ throw new Error("Managed credential acknowledgment returned a mismatch");
14560
+ }
14561
+ return response.status === 200 && setup.status === "acknowledged" ? "acknowledged" : "pending";
14562
+ }
14563
+
13809
14564
  // src/commands/run.ts
13810
14565
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
13811
14566
  var MAX_DISCONNECT_REASON_LENGTH = 200;
@@ -13846,7 +14601,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
13846
14601
  if (trimmed === "") {
13847
14602
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
13848
14603
  }
13849
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join12(homeDir, trimmed.slice(2)) : trimmed;
14604
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join13(homeDir, trimmed.slice(2)) : trimmed;
13850
14605
  if (!isAbsolute4(expanded)) {
13851
14606
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
13852
14607
  }
@@ -14001,7 +14756,7 @@ function logActivity(state, entry) {
14001
14756
  }
14002
14757
  function reportSessionDbRecovery(state) {
14003
14758
  try {
14004
- const report = drainSessionDbRecoveryReport({ homeDir: homedir7(), env: process.env });
14759
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir8(), env: process.env });
14005
14760
  for (const record of report.records) {
14006
14761
  const activity = buildSessionDbRecoveryActivity(record);
14007
14762
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -14082,7 +14837,7 @@ async function importOpenCodeV2CredentialsForState(state) {
14082
14837
  }
14083
14838
  const result = await importOpenCodeV2Credentials({
14084
14839
  request: client.request,
14085
- homeDir: homedir7(),
14840
+ homeDir: homedir8(),
14086
14841
  directory,
14087
14842
  guard: state.opencodeV2CredentialImportGuard,
14088
14843
  log: (message, level = "info") => logActivity(state, { type: "info", level, message })
@@ -14502,7 +15257,7 @@ function shouldWarnForReclaimSkip(reason) {
14502
15257
  return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
14503
15258
  }
14504
15259
  function sessionDbPath() {
14505
- return join12(homedir7(), ".local", "share", "opencode", "opencode.db");
15260
+ return join13(homedir8(), ".local", "share", "opencode", "opencode.db");
14506
15261
  }
14507
15262
  function logSessionCleanupActivity(state, phase, entry) {
14508
15263
  logActivity(state, {
@@ -14746,7 +15501,7 @@ function scheduleSessionCleanup(state, driver, options) {
14746
15501
  for (const warning2 of config.warnings) {
14747
15502
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
14748
15503
  }
14749
- const dbBytes = statSessionDbBytes(homedir7());
15504
+ const dbBytes = statSessionDbBytes(homedir8());
14750
15505
  void (async () => {
14751
15506
  const reclaimAvailability = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
14752
15507
  if (reclaimAvailability !== null) {
@@ -14965,7 +15720,7 @@ function scheduleResourceUsageReporting(state, options) {
14965
15720
  });
14966
15721
  return;
14967
15722
  }
14968
- const { collect, stop } = createResourceUsageCollector(homedir7());
15723
+ const { collect, stop } = createResourceUsageCollector(homedir8());
14969
15724
  state.stopResourceUsageSampling = stop;
14970
15725
  let consecutiveFailures = 0;
14971
15726
  const tick = async () => {
@@ -15206,7 +15961,7 @@ async function run(options) {
15206
15961
  let fileSyncDirectories;
15207
15962
  try {
15208
15963
  logLevel = resolveLogLevel(options);
15209
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir7());
15964
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir8());
15210
15965
  if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
15211
15966
  throw new Error(
15212
15967
  "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
@@ -15492,7 +16247,7 @@ async function run(options) {
15492
16247
  state.credentialSync?.arm();
15493
16248
  const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
15494
16249
  context: {
15495
- homeDir: homedir7(),
16250
+ homeDir: homedir8(),
15496
16251
  cwd: process.cwd(),
15497
16252
  microvmId: process.env.MICROVM_ID?.trim(),
15498
16253
  euid: process.getuid?.(),
@@ -15515,7 +16270,7 @@ async function run(options) {
15515
16270
  dependencyInstallDiagnosticReporter
15516
16271
  );
15517
16272
  const openCodeLogTail = tailOpenCodeLogFile(
15518
- resolveOpenCodeLogPath(homedir7(), process.env),
16273
+ resolveOpenCodeLogPath(homedir8(), process.env),
15519
16274
  openCodeActivityForwarder
15520
16275
  );
15521
16276
  state.stopOpenCodeLogTail = () => {
@@ -15590,6 +16345,41 @@ async function run(options) {
15590
16345
  for (const warning2 of opencodeVersionWarnings) {
15591
16346
  logActivity(state, { type: "info", level: "warn", message: warning2 });
15592
16347
  }
16348
+ const managedSetupOptions = {
16349
+ agentId: state.agentId,
16350
+ apiUrl: getApiUrlConfig(),
16351
+ getAuthHeader: () => state.authHeader,
16352
+ autoConfigureCredentialsProxy: options.autoConfigureCredentialsProxy,
16353
+ log: (message, level = "info") => logActivity(state, {
16354
+ type: level === "error" ? "error" : "info",
16355
+ level,
16356
+ ...level === "error" ? { error: message } : { message }
16357
+ })
16358
+ };
16359
+ const managedDiscovery = await discoverManagedInferenceSetup(managedSetupOptions);
16360
+ let managedPreparation = { kind: "none" };
16361
+ if (managedDiscovery.kind === "failed") {
16362
+ managedPreparation = managedDiscovery;
16363
+ managedSetupOptions.log(`MANAGED-INFERENCE-NOT-READY: ${managedDiscovery.reason}`, "warn");
16364
+ } else if (managedDiscovery.kind === "setup") {
16365
+ const managedHealth = opencodeVersion === "v2" ? await checkOpenCode2Health(state.port) : await checkOpenCodeHealth(state.port);
16366
+ managedPreparation = await prepareManagedInferenceSetup(
16367
+ managedSetupOptions,
16368
+ managedDiscovery,
16369
+ managedHealth
16370
+ );
16371
+ if (managedPreparation.kind === "failed") {
16372
+ managedSetupOptions.log(
16373
+ `MANAGED-INFERENCE-NOT-READY: ${managedPreparation.reason}`,
16374
+ "warn"
16375
+ );
16376
+ } else if (managedPreparation.kind === "ready") {
16377
+ managedSetupOptions.log(
16378
+ `MANAGED-INFERENCE-PREPARED: runner=${state.agentId} generation=${managedPreparation.generation}`,
16379
+ "info"
16380
+ );
16381
+ }
16382
+ }
15593
16383
  const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
15594
16384
  for (const warning2 of maxActiveSessionsWarnings) {
15595
16385
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -15616,6 +16406,32 @@ async function run(options) {
15616
16406
  state.opencodeProcess = options.opencodePidFile ? null : oc.process;
15617
16407
  state.opencodeVersion = oc.version;
15618
16408
  state.opencodeApiVersion = opencodeVersion;
16409
+ let configuredPlugins = [];
16410
+ let resolvedPlugins = [];
16411
+ try {
16412
+ const provenanceLog = (message) => logActivity(state, { type: "info", level: "warn", message });
16413
+ configuredPlugins = readConfiguredPluginSpecs({ log: provenanceLog });
16414
+ resolvedPlugins = resolveInstalledPluginVersions({ log: provenanceLog });
16415
+ } catch (error2) {
16416
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
16417
+ logActivity(state, {
16418
+ type: "info",
16419
+ level: "warn",
16420
+ message: `Could not collect OpenCode runtime provenance: ${kind}`
16421
+ });
16422
+ }
16423
+ logActivity(state, {
16424
+ type: "info",
16425
+ level: "info",
16426
+ message: "OpenCode runtime provenance",
16427
+ metadata: {
16428
+ opencode_version: state.opencodeVersion,
16429
+ opencode_api_version: state.opencodeApiVersion,
16430
+ configured_plugins: JSON.stringify(configuredPlugins),
16431
+ resolved_plugins: JSON.stringify(resolvedPlugins)
16432
+ },
16433
+ source: "cli.runtime-provenance"
16434
+ });
15619
16435
  let opencodePassword = null;
15620
16436
  if (opencodeVersion === "v2" && "password" in oc) {
15621
16437
  const value = oc.password;
@@ -15644,7 +16460,7 @@ async function run(options) {
15644
16460
  const provenance = checkSessionDbProvenance({
15645
16461
  dbPath: sessionDbPath(),
15646
16462
  currentVersion: state.opencodeVersion,
15647
- homeDir: homedir7(),
16463
+ homeDir: homedir8(),
15648
16464
  env: process.env
15649
16465
  });
15650
16466
  if (provenance.anomaly) {
@@ -15658,6 +16474,30 @@ async function run(options) {
15658
16474
  }
15659
16475
  }
15660
16476
  state.opencodeConnected = oc.notReadyReason === null;
16477
+ if (managedPreparation.kind === "ready" && oc.notReadyReason === null) {
16478
+ try {
16479
+ const acknowledgement = await acknowledgeManagedInferenceSetup(
16480
+ managedSetupOptions,
16481
+ managedPreparation
16482
+ );
16483
+ if (acknowledgement === "acknowledged") {
16484
+ managedSetupOptions.log(
16485
+ `MANAGED-INFERENCE-ACKNOWLEDGED: runner=${state.agentId} generation=${managedPreparation.generation}`,
16486
+ "info"
16487
+ );
16488
+ } else {
16489
+ managedSetupOptions.log(
16490
+ `MANAGED-INFERENCE-NOT-READY: policy refresh is pending for runner=${state.agentId} generation=${managedPreparation.generation}`,
16491
+ "warn"
16492
+ );
16493
+ }
16494
+ } catch (error2) {
16495
+ managedSetupOptions.log(
16496
+ `MANAGED-INFERENCE-NOT-READY: ${error2 instanceof Error ? error2.message : String(error2)}`,
16497
+ "warn"
16498
+ );
16499
+ }
16500
+ }
15661
16501
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
15662
16502
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
15663
16503
  if (!state.interactive && oc.notReadyReason !== null) {
@@ -15716,7 +16556,7 @@ async function run(options) {
15716
16556
  let existingPid;
15717
16557
  if (existsSync3(options.litestreamPidFile)) {
15718
16558
  try {
15719
- const rawPid = readFileSync7(options.litestreamPidFile, "utf8").trim();
16559
+ const rawPid = readFileSync8(options.litestreamPidFile, "utf8").trim();
15720
16560
  const parsedPid = Number(rawPid);
15721
16561
  if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
15722
16562
  existingPid = parsedPid;
@@ -15815,7 +16655,7 @@ async function run(options) {
15815
16655
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
15816
16656
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
15817
16657
  fileSyncDirectories,
15818
- homeDir: homedir7(),
16658
+ homeDir: homedir8(),
15819
16659
  maxActiveSessions,
15820
16660
  log: (entry) => (
15821
16661
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -15840,7 +16680,7 @@ async function run(options) {
15840
16680
  onConnected: (agentId, isReconnect, transition) => {
15841
16681
  state.connected = true;
15842
16682
  state.agentId = agentId;
15843
- const connectionMessage = isReconnect ? `Tunnel reconnected (runner: ${agentId}, generation: ${transition.generation}, attempt: ${transition.attempt}, offline for ${transition.downtimeMs}ms)` : `Tunnel connected (runner: ${agentId}, generation: ${transition.generation})`;
16683
+ const connectionMessage = isReconnect ? `Tunnel reconnected (runner: ${agentId}, generation: ${transition.generation}, relay connection: ${transition.relayConnectionId ?? "unknown"}, attempt: ${transition.attempt}, offline for ${transition.downtimeMs}ms)` : `Tunnel connected (runner: ${agentId}, generation: ${transition.generation}, relay connection: ${transition.relayConnectionId ?? "unknown"})`;
15844
16684
  logActivity(state, {
15845
16685
  type: "info",
15846
16686
  message: connectionMessage
@@ -15873,6 +16713,7 @@ async function run(options) {
15873
16713
  connected: state.opencodeConnected
15874
16714
  }),
15875
16715
  connection_generation: transition.generation,
16716
+ ...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {},
15876
16717
  ...isReconnect && transition.downtimeMs !== null ? {
15877
16718
  reconnect_attempt: transition.attempt,
15878
16719
  downtime_ms: transition.downtimeMs
@@ -15903,12 +16744,13 @@ async function run(options) {
15903
16744
  const safeReason2 = redactDiagnosticText(reason).slice(0, MAX_DISCONNECT_REASON_LENGTH);
15904
16745
  logActivity(state, {
15905
16746
  type: "info",
15906
- message: `Tunnel disconnected (generation: ${transition.generation}, code: ${code}, reason: ${safeReason2})`
16747
+ message: `Tunnel disconnected (generation: ${transition.generation}, relay connection: ${transition.relayConnectionId ?? "unknown"}, code: ${code}, reason: ${safeReason2})`
15907
16748
  });
15908
16749
  emitAgentDisconnected(state.agentId, {
15909
16750
  code,
15910
16751
  reason: safeReason2,
15911
- connection_generation: transition.generation
16752
+ connection_generation: transition.generation,
16753
+ ...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {}
15912
16754
  });
15913
16755
  if (state.interactive) displayStatus(state);
15914
16756
  },
@@ -16059,9 +16901,9 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
16059
16901
  "--endpoint <url>",
16060
16902
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
16061
16903
  ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
16062
- const { endpoint, tunnel } = thisCommand.opts();
16063
- if (endpoint) {
16064
- setEndpoint(endpoint);
16904
+ const { endpoint: endpoint2, tunnel } = thisCommand.opts();
16905
+ if (endpoint2) {
16906
+ setEndpoint(endpoint2);
16065
16907
  }
16066
16908
  if (tunnel) {
16067
16909
  setTunnelUrl(tunnel);
@@ -16135,6 +16977,9 @@ program.command("run").description("Connect to Evident and process messages").op
16135
16977
  ).option(
16136
16978
  "--opencode-config-overlay <path>",
16137
16979
  "Apply this runner-provided OpenCode config before starting OpenCode."
16980
+ ).option(
16981
+ "--auto-configure-credentials-proxy",
16982
+ "Install Evident's generated OpenCode providers for the runner's credential pool (off by default)."
16138
16983
  ).option(
16139
16984
  "--credential-sync-marker <path>",
16140
16985
  "Own the interval credential sync and write this marker once the shutdown flush has finished, so the runner image's lifecycle hooks can wait on it."
@@ -16178,6 +17023,7 @@ program.command("run").description("Connect to Evident and process messages").op
16178
17023
  restoreSessionDb: options.restoreSessionDb,
16179
17024
  restoreRunnerCredentials: options.restoreRunnerCredentials,
16180
17025
  opencodeConfigOverlay: options.opencodeConfigOverlay,
17026
+ autoConfigureCredentialsProxy: options.autoConfigureCredentialsProxy,
16181
17027
  credentialSyncMarker: options.credentialSyncMarker
16182
17028
  });
16183
17029
  }