@evident-ai/cli 3.6.1-dev.37d1a87 → 3.6.1-dev.43c1fd7

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) {
@@ -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.37d1a87" : void 0) ?? process.env.npm_package_version ?? "unknown";
1445
+ var CLI_VERSION = (true ? "3.6.1-dev.43c1fd7" : 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) {
@@ -4681,11 +4797,11 @@ function failureMessage(status2) {
4681
4797
  function isRetryableStatus(status2) {
4682
4798
  return CONNECT_KEY_RETRY_STATUSES.includes(status2);
4683
4799
  }
4684
- async function importOneCredential(request2, credential, sleepForRetry, log3) {
4800
+ async function importOneCredential(request3, credential, sleepForRetry, log3) {
4685
4801
  const path = `/api/integration/${encodeURIComponent(credential.integrationId)}/connect/key`;
4686
4802
  for (let attempt = 1; attempt <= CONNECT_KEY_MAX_ATTEMPTS; attempt += 1) {
4687
4803
  try {
4688
- const response = await request2(
4804
+ const response = await request3(
4689
4805
  path,
4690
4806
  {
4691
4807
  method: "POST",
@@ -4720,7 +4836,7 @@ async function importOneCredential(request2, credential, sleepForRetry, log3) {
4720
4836
  throw new Error("OpenCode credential import retry loop did not return");
4721
4837
  }
4722
4838
  async function importOpenCodeCredentials({
4723
- request: request2,
4839
+ request: request3,
4724
4840
  classified,
4725
4841
  connectedIntegrationIds,
4726
4842
  sleepForRetry = sleep2,
@@ -4732,7 +4848,7 @@ async function importOpenCodeCredentials({
4732
4848
  result.alreadyConnected.push(credential.integrationId);
4733
4849
  continue;
4734
4850
  }
4735
- const outcome = await importOneCredential(request2, credential, sleepForRetry, log3);
4851
+ const outcome = await importOneCredential(request3, credential, sleepForRetry, log3);
4736
4852
  if (outcome.ok) result.imported.push(credential.integrationId);
4737
4853
  else result.failed.push(outcome.failure);
4738
4854
  }
@@ -4750,7 +4866,7 @@ function parseIntegrationList(value) {
4750
4866
  return { integrationIds, hasData: value.data.length > 0 };
4751
4867
  }
4752
4868
  async function getConnectedOpenCodeIntegrationIds({
4753
- request: request2,
4869
+ request: request3,
4754
4870
  directory,
4755
4871
  sleepForRetry = sleep2,
4756
4872
  log: log3
@@ -4758,7 +4874,7 @@ async function getConnectedOpenCodeIntegrationIds({
4758
4874
  const path = `/api/integration?location%5Bdirectory%5D=${encodeURIComponent(directory)}`;
4759
4875
  for (let attempt = 1; attempt <= INTEGRATION_LIST_MAX_READS; attempt += 1) {
4760
4876
  try {
4761
- const response = await request2(path);
4877
+ const response = await request3(path);
4762
4878
  const parsed = parseIntegrationList(await response.json());
4763
4879
  if (parsed === null) {
4764
4880
  log3(
@@ -4787,7 +4903,7 @@ async function getConnectedOpenCodeIntegrationIds({
4787
4903
  return null;
4788
4904
  }
4789
4905
  async function importOpenCodeV2Credentials({
4790
- request: request2,
4906
+ request: request3,
4791
4907
  homeDir,
4792
4908
  directory,
4793
4909
  sleepForRetry = sleep2,
@@ -4805,7 +4921,7 @@ async function importOpenCodeV2Credentials({
4805
4921
  const classified = classifyOpenCodeCredentials(credentials2);
4806
4922
  if (classified.importable.length === 0) return emptyResult(classified.unsupported);
4807
4923
  const connectedIntegrationIds = await getConnectedOpenCodeIntegrationIds({
4808
- request: request2,
4924
+ request: request3,
4809
4925
  directory,
4810
4926
  sleepForRetry,
4811
4927
  log: log3
@@ -4814,7 +4930,7 @@ async function importOpenCodeV2Credentials({
4814
4930
  return emptyResult(classified.unsupported, "connection-list-unavailable");
4815
4931
  }
4816
4932
  return importOpenCodeCredentials({
4817
- request: request2,
4933
+ request: request3,
4818
4934
  classified,
4819
4935
  connectedIntegrationIds,
4820
4936
  sleepForRetry,
@@ -6550,6 +6666,7 @@ function connectTunnel(options) {
6550
6666
  }, 3e4);
6551
6667
  let relaySilenceTimeout;
6552
6668
  let relaySilenceTimedOut = false;
6669
+ let relayConnectionId;
6553
6670
  const clearRelaySilenceTimeout = () => {
6554
6671
  if (relaySilenceTimeout === void 0) return;
6555
6672
  clearTimeout(relaySilenceTimeout);
@@ -6635,7 +6752,8 @@ function connectTunnel(options) {
6635
6752
  armRelaySilenceTimeout();
6636
6753
  forwarder.setBinaryFramesSupported(message.binary_frames === true);
6637
6754
  const connectedAgentId = message.agent_id ?? agentId;
6638
- onConnected?.(connectedAgentId);
6755
+ relayConnectionId = message.connection_id;
6756
+ onConnected?.(connectedAgentId, relayConnectionId);
6639
6757
  resolve5({
6640
6758
  ws,
6641
6759
  close: () => ws.close(1e3, "CLI shutdown")
@@ -6672,7 +6790,7 @@ function connectTunnel(options) {
6672
6790
  clearRelaySilenceTimeout();
6673
6791
  const reasonStr = (relaySilenceTimedOut ? "no relay heartbeat for 90s \u2014 reconnecting" : void 0) || reason.toString() || upgradeRejection || (code === 1006 ? "abnormal closure" : "No reason provided");
6674
6792
  forwarder.abortAll();
6675
- onDisconnected?.(code, reasonStr);
6793
+ onDisconnected?.(code, reasonStr, relayConnectionId);
6676
6794
  });
6677
6795
  });
6678
6796
  }
@@ -6735,7 +6853,7 @@ var RunnerConnection = class _RunnerConnection {
6735
6853
  authHeader: this.opts.getAuthHeader(),
6736
6854
  port: this.opts.port,
6737
6855
  openCodePassword: this.opts.openCodePassword,
6738
- onConnected: (agentId) => {
6856
+ onConnected: (agentId, relayConnectionId) => {
6739
6857
  const attempt = this.reconnectAttempt + 1;
6740
6858
  this.reconnectAttempt = 0;
6741
6859
  this.reconnecting = false;
@@ -6745,13 +6863,17 @@ var RunnerConnection = class _RunnerConnection {
6745
6863
  this.disconnectedAtMs = null;
6746
6864
  events.onConnected(agentId, isReconnect, {
6747
6865
  generation: this.generation,
6866
+ relayConnectionId: relayConnectionId ?? null,
6748
6867
  attempt,
6749
6868
  downtimeMs
6750
6869
  });
6751
6870
  },
6752
- onDisconnected: (code, reason) => {
6871
+ onDisconnected: (code, reason, relayConnectionId) => {
6753
6872
  this.disconnectedAtMs = this.now();
6754
- events.onDisconnected(code, reason, { generation: this.generation });
6873
+ events.onDisconnected(code, reason, {
6874
+ generation: this.generation,
6875
+ relayConnectionId: relayConnectionId ?? null
6876
+ });
6755
6877
  const relayRequestedReconnect = code === 1e3 && _RunnerConnection.RELAY_RECONNECT_CLOSE_REASONS.has(reason);
6756
6878
  if (this.opts.isRunning() && (code !== 1e3 || relayRequestedReconnect) && !this.reconnecting) {
6757
6879
  this.reconnectPromise = this.connectWithRetry(true).catch((err) => {
@@ -7199,8 +7321,8 @@ import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/p
7199
7321
  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";
7200
7322
  var FILE_MODE = 384;
7201
7323
  var DIRECTORY_MODE = 448;
7202
- async function writePushedFile(request2) {
7203
- const { requestedPath, content, allowedDirectories, homeDir } = request2;
7324
+ async function writePushedFile(request3) {
7325
+ const { requestedPath, content, allowedDirectories, homeDir } = request3;
7204
7326
  const bytes = content.byteLength;
7205
7327
  if (allowedDirectories.length === 0) {
7206
7328
  return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
@@ -13778,6 +13900,38 @@ async function configureGitHubAccess({ env, log: log3 }) {
13778
13900
  import { execFileSync as execFileSync2 } from "node:child_process";
13779
13901
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
13780
13902
  import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
13903
+ function parseConfigContent(content) {
13904
+ if (!content?.trim()) return {};
13905
+ const parsed = JSON.parse(content);
13906
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
13907
+ throw new Error("OPENCODE_CONFIG_CONTENT must contain a JSON object");
13908
+ }
13909
+ return parsed;
13910
+ }
13911
+ function mergeManagedOpenCodeConfigContent(content, managedProviders) {
13912
+ const config = parseConfigContent(content);
13913
+ const provider = typeof config.provider === "object" && config.provider !== null && !Array.isArray(config.provider) ? { ...config.provider } : {};
13914
+ for (const namespace of CREDENTIAL_PROXY_NATIVE_NAMESPACES) {
13915
+ delete provider[namespace];
13916
+ }
13917
+ return JSON.stringify({ ...config, provider: { ...provider, ...managedProviders } });
13918
+ }
13919
+ function removeManagedOpenCodeConfigContent(content) {
13920
+ if (!content?.trim()) return content;
13921
+ const config = parseConfigContent(content);
13922
+ if (typeof config.provider !== "object" || config.provider === null || Array.isArray(config.provider)) {
13923
+ return content;
13924
+ }
13925
+ const provider = { ...config.provider };
13926
+ let changed = false;
13927
+ for (const namespace of CREDENTIAL_PROXY_NATIVE_NAMESPACES) {
13928
+ if (namespace in provider) {
13929
+ delete provider[namespace];
13930
+ changed = true;
13931
+ }
13932
+ }
13933
+ return changed ? JSON.stringify({ ...config, provider }) : content;
13934
+ }
13781
13935
  function isFile(filePath) {
13782
13936
  return existsSync2(filePath) && statSync6(filePath).isFile();
13783
13937
  }
@@ -14199,6 +14353,230 @@ function createCredentialSync({
14199
14353
  };
14200
14354
  }
14201
14355
 
14356
+ // src/lib/managed-inference-setup.ts
14357
+ var defaultStore = {
14358
+ get: getManagedInferenceCredential,
14359
+ set: setManagedInferenceCredential,
14360
+ clear: clearManagedInferenceCredential
14361
+ };
14362
+ function endpoint(options, operation) {
14363
+ return `${options.apiUrl}/runners/${options.agentId}/managed-credentials/${operation}`;
14364
+ }
14365
+ function requestHeaders(options) {
14366
+ return { Authorization: options.getAuthHeader(), "Content-Type": "application/json" };
14367
+ }
14368
+ function request2(options) {
14369
+ return withRequestTimeout(options.fetchImpl ?? fetch, REQUEST_TIMEOUT_MS);
14370
+ }
14371
+ function safeFailure(operation, status2) {
14372
+ return status2 === void 0 ? `${operation} could not reach the managed credential service` : `${operation} returned HTTP ${status2}`;
14373
+ }
14374
+ function logTransportFailure(options, operation, error2, authorization) {
14375
+ let detail = error2 instanceof Error ? error2.message : String(error2);
14376
+ const credential = authorization.split(/\s+/, 2)[1];
14377
+ for (const secret of [authorization, credential]) {
14378
+ if (secret) detail = detail.replaceAll(secret, "[redacted]");
14379
+ }
14380
+ options.log(
14381
+ `MANAGED-INFERENCE-TRANSPORT-FAILED: operation=${operation} detail=${redactDiagnosticText(detail)}`,
14382
+ "debug"
14383
+ );
14384
+ }
14385
+ async function responseJson(response) {
14386
+ try {
14387
+ const value = await response.json();
14388
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
14389
+ } catch (error2) {
14390
+ return null;
14391
+ }
14392
+ }
14393
+ function readSetup(value) {
14394
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14395
+ const setup = value;
14396
+ if (typeof setup.runner_id !== "string" || typeof setup.generation !== "string" || typeof setup.status !== "string" || setup.token_id !== null && typeof setup.token_id !== "string") {
14397
+ return null;
14398
+ }
14399
+ return setup;
14400
+ }
14401
+ function clearLocalSetup(options) {
14402
+ const env = options.env ?? process.env;
14403
+ (options.store ?? defaultStore).clear(options.agentId);
14404
+ delete env.EVIDENT_PROXY_TOKEN;
14405
+ try {
14406
+ const content = removeManagedOpenCodeConfigContent(env.OPENCODE_CONFIG_CONTENT);
14407
+ if (content === void 0) delete env.OPENCODE_CONFIG_CONTENT;
14408
+ else env.OPENCODE_CONFIG_CONTENT = content;
14409
+ } catch (error2) {
14410
+ options.log(
14411
+ "MANAGED-INFERENCE-CLEANUP-PARTIAL: stored credentials were removed, but malformed OPENCODE_CONFIG_CONTENT could not be inspected",
14412
+ "warn"
14413
+ );
14414
+ }
14415
+ }
14416
+ async function discoverManagedInferenceSetup(options) {
14417
+ const headers = requestHeaders(options);
14418
+ let response;
14419
+ try {
14420
+ response = await request2(options)(endpoint(options, "current"), {
14421
+ headers
14422
+ });
14423
+ } catch (error2) {
14424
+ logTransportFailure(options, "discovery", error2, headers.Authorization);
14425
+ return { kind: "failed", reason: safeFailure("Managed setup discovery") };
14426
+ }
14427
+ if (response.status === 404) {
14428
+ clearLocalSetup(options);
14429
+ return { kind: "none" };
14430
+ }
14431
+ if (!response.ok) {
14432
+ return { kind: "failed", reason: safeFailure("Managed setup discovery", response.status) };
14433
+ }
14434
+ const body = await responseJson(response);
14435
+ const setup = readSetup(body?.setup);
14436
+ return setup ? { kind: "setup", setup } : { kind: "failed", reason: "Managed setup discovery returned an invalid response" };
14437
+ }
14438
+ async function post(options, operation, body) {
14439
+ const headers = requestHeaders(options);
14440
+ try {
14441
+ return await request2(options)(endpoint(options, operation), {
14442
+ method: "POST",
14443
+ headers,
14444
+ body: JSON.stringify(body)
14445
+ });
14446
+ } catch (error2) {
14447
+ logTransportFailure(options, operation, error2, headers.Authorization);
14448
+ return null;
14449
+ }
14450
+ }
14451
+ function applyCredential(options, credential) {
14452
+ const { config, unsupportedProviders } = buildCredentialProxyNativeConfig({
14453
+ inferenceBaseUrl: credential.inferenceBaseUrl,
14454
+ modelDescriptors: credential.modelDescriptors
14455
+ });
14456
+ if (unsupportedProviders.length > 0 || Object.keys(config.provider).length === 0) {
14457
+ return "Managed setup contains unsupported provider descriptors";
14458
+ }
14459
+ const env = options.env ?? process.env;
14460
+ let merged;
14461
+ try {
14462
+ merged = mergeManagedOpenCodeConfigContent(env.OPENCODE_CONFIG_CONTENT, config.provider);
14463
+ } catch (error2) {
14464
+ return "OPENCODE_CONFIG_CONTENT is malformed; managed providers were not installed";
14465
+ }
14466
+ try {
14467
+ (options.store ?? defaultStore).set(options.agentId, credential);
14468
+ } catch (error2) {
14469
+ options.log(
14470
+ `MANAGED-INFERENCE-STORE-FAILED: runner=${options.agentId} generation=${credential.generation}`,
14471
+ "warn"
14472
+ );
14473
+ return "Managed credentials could not be written to the protected store";
14474
+ }
14475
+ env.EVIDENT_PROXY_TOKEN = credential.token;
14476
+ env.OPENCODE_CONFIG_CONTENT = merged;
14477
+ return null;
14478
+ }
14479
+ async function reportManagedInferenceApplyFailure(options, failure) {
14480
+ const response = await post(options, "report-failure", {
14481
+ generation: failure.generation,
14482
+ token_id: failure.tokenId
14483
+ });
14484
+ if (!response?.ok) {
14485
+ options.log(
14486
+ `MANAGED-INFERENCE-REPORT-FAILED: runner=${options.agentId} generation=${failure.generation}${response ? ` status=${response.status}` : ""}`,
14487
+ "warn"
14488
+ );
14489
+ }
14490
+ }
14491
+ async function reaffirmStored(options, credential) {
14492
+ const response = await post(options, "reaffirm", {
14493
+ generation: credential.generation,
14494
+ token_id: credential.tokenId
14495
+ });
14496
+ if (!response?.ok) {
14497
+ return {
14498
+ kind: "failed",
14499
+ 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")
14500
+ };
14501
+ }
14502
+ const body = await responseJson(response);
14503
+ const setup = readSetup(body?.setup);
14504
+ if (!setup || setup.generation !== credential.generation || setup.token_id !== credential.tokenId) {
14505
+ return { kind: "failed", reason: "Managed credential reaffirmation returned a mismatch" };
14506
+ }
14507
+ const failure = applyCredential(options, credential);
14508
+ return failure ? { kind: "failed", reason: failure } : { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
14509
+ }
14510
+ async function prepareManagedInferenceSetup(options, discovery, health) {
14511
+ if (health.authFailed) {
14512
+ return {
14513
+ kind: "failed",
14514
+ reason: "OpenCode authentication failed; managed credentials were not rotated"
14515
+ };
14516
+ }
14517
+ const stored = (options.store ?? defaultStore).get(options.agentId);
14518
+ if (health.healthy) {
14519
+ if (!stored) {
14520
+ return {
14521
+ kind: "failed",
14522
+ reason: "Managed credentials are missing for the serving OpenCode process; restart required"
14523
+ };
14524
+ }
14525
+ return reaffirmStored(options, stored);
14526
+ }
14527
+ if (discovery.setup.status === "acknowledged" && stored?.generation === discovery.setup.generation && stored.tokenId === discovery.setup.token_id) {
14528
+ return reaffirmStored(options, stored);
14529
+ }
14530
+ const response = await post(options, "bootstrap", { generation: discovery.setup.generation });
14531
+ if (!response?.ok) {
14532
+ return {
14533
+ kind: "failed",
14534
+ reason: response ? safeFailure("Managed credential bootstrap", response.status) : safeFailure("Managed credential bootstrap")
14535
+ };
14536
+ }
14537
+ const body = await responseJson(response);
14538
+ const setup = readSetup(body?.setup);
14539
+ const token = body?.inference_token;
14540
+ const inferenceBaseUrl = body?.inference_base_url;
14541
+ const modelDescriptors = body?.model_descriptors;
14542
+ if (!setup || setup.generation !== discovery.setup.generation || typeof setup.token_id !== "string" || typeof token !== "string" || typeof inferenceBaseUrl !== "string" || !Array.isArray(modelDescriptors) || !modelDescriptors.every(
14543
+ (descriptor) => typeof descriptor === "object" && descriptor !== null && typeof descriptor.id === "string" && typeof descriptor.provider === "string"
14544
+ )) {
14545
+ return { kind: "failed", reason: "Managed credential bootstrap returned an invalid response" };
14546
+ }
14547
+ const credential = {
14548
+ generation: setup.generation,
14549
+ tokenId: setup.token_id,
14550
+ token,
14551
+ inferenceBaseUrl,
14552
+ modelDescriptors
14553
+ };
14554
+ const failure = applyCredential(options, credential);
14555
+ if (failure) {
14556
+ await reportManagedInferenceApplyFailure(options, credential);
14557
+ return { kind: "failed", reason: failure };
14558
+ }
14559
+ return { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
14560
+ }
14561
+ async function acknowledgeManagedInferenceSetup(options, preparation) {
14562
+ const response = await post(options, "acknowledge", {
14563
+ generation: preparation.generation,
14564
+ token_id: preparation.tokenId,
14565
+ config_validated: true
14566
+ });
14567
+ if (!response?.ok) {
14568
+ throw new Error(
14569
+ response ? safeFailure("Managed credential acknowledgment", response.status) : safeFailure("Managed credential acknowledgment")
14570
+ );
14571
+ }
14572
+ const body = await responseJson(response);
14573
+ const setup = readSetup(body?.setup);
14574
+ if (!setup || setup.generation !== preparation.generation || setup.token_id !== preparation.tokenId) {
14575
+ throw new Error("Managed credential acknowledgment returned a mismatch");
14576
+ }
14577
+ return response.status === 200 && setup.status === "acknowledged" ? "acknowledged" : "pending";
14578
+ }
14579
+
14202
14580
  // src/commands/run.ts
14203
14581
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
14204
14582
  var MAX_DISCONNECT_REASON_LENGTH = 200;
@@ -15983,6 +16361,40 @@ async function run(options) {
15983
16361
  for (const warning2 of opencodeVersionWarnings) {
15984
16362
  logActivity(state, { type: "info", level: "warn", message: warning2 });
15985
16363
  }
16364
+ const managedSetupOptions = {
16365
+ agentId: state.agentId,
16366
+ apiUrl: getApiUrlConfig(),
16367
+ getAuthHeader: () => state.authHeader,
16368
+ log: (message, level = "info") => logActivity(state, {
16369
+ type: level === "error" ? "error" : "info",
16370
+ level,
16371
+ ...level === "error" ? { error: message } : { message }
16372
+ })
16373
+ };
16374
+ const managedDiscovery = await discoverManagedInferenceSetup(managedSetupOptions);
16375
+ let managedPreparation = { kind: "none" };
16376
+ if (managedDiscovery.kind === "failed") {
16377
+ managedPreparation = managedDiscovery;
16378
+ managedSetupOptions.log(`MANAGED-INFERENCE-NOT-READY: ${managedDiscovery.reason}`, "warn");
16379
+ } else if (managedDiscovery.kind === "setup") {
16380
+ const managedHealth = opencodeVersion === "v2" ? await checkOpenCode2Health(state.port) : await checkOpenCodeHealth(state.port);
16381
+ managedPreparation = await prepareManagedInferenceSetup(
16382
+ managedSetupOptions,
16383
+ managedDiscovery,
16384
+ managedHealth
16385
+ );
16386
+ if (managedPreparation.kind === "failed") {
16387
+ managedSetupOptions.log(
16388
+ `MANAGED-INFERENCE-NOT-READY: ${managedPreparation.reason}`,
16389
+ "warn"
16390
+ );
16391
+ } else if (managedPreparation.kind === "ready") {
16392
+ managedSetupOptions.log(
16393
+ `MANAGED-INFERENCE-PREPARED: runner=${state.agentId} generation=${managedPreparation.generation}`,
16394
+ "info"
16395
+ );
16396
+ }
16397
+ }
15986
16398
  const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
15987
16399
  for (const warning2 of maxActiveSessionsWarnings) {
15988
16400
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -16077,6 +16489,30 @@ async function run(options) {
16077
16489
  }
16078
16490
  }
16079
16491
  state.opencodeConnected = oc.notReadyReason === null;
16492
+ if (managedPreparation.kind === "ready" && oc.notReadyReason === null) {
16493
+ try {
16494
+ const acknowledgement = await acknowledgeManagedInferenceSetup(
16495
+ managedSetupOptions,
16496
+ managedPreparation
16497
+ );
16498
+ if (acknowledgement === "acknowledged") {
16499
+ managedSetupOptions.log(
16500
+ `MANAGED-INFERENCE-ACKNOWLEDGED: runner=${state.agentId} generation=${managedPreparation.generation}`,
16501
+ "info"
16502
+ );
16503
+ } else {
16504
+ managedSetupOptions.log(
16505
+ `MANAGED-INFERENCE-NOT-READY: policy refresh is pending for runner=${state.agentId} generation=${managedPreparation.generation}`,
16506
+ "warn"
16507
+ );
16508
+ }
16509
+ } catch (error2) {
16510
+ managedSetupOptions.log(
16511
+ `MANAGED-INFERENCE-NOT-READY: ${error2 instanceof Error ? error2.message : String(error2)}`,
16512
+ "warn"
16513
+ );
16514
+ }
16515
+ }
16080
16516
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
16081
16517
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
16082
16518
  if (!state.interactive && oc.notReadyReason !== null) {
@@ -16259,7 +16695,7 @@ async function run(options) {
16259
16695
  onConnected: (agentId, isReconnect, transition) => {
16260
16696
  state.connected = true;
16261
16697
  state.agentId = agentId;
16262
- 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})`;
16698
+ 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"})`;
16263
16699
  logActivity(state, {
16264
16700
  type: "info",
16265
16701
  message: connectionMessage
@@ -16292,6 +16728,7 @@ async function run(options) {
16292
16728
  connected: state.opencodeConnected
16293
16729
  }),
16294
16730
  connection_generation: transition.generation,
16731
+ ...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {},
16295
16732
  ...isReconnect && transition.downtimeMs !== null ? {
16296
16733
  reconnect_attempt: transition.attempt,
16297
16734
  downtime_ms: transition.downtimeMs
@@ -16322,12 +16759,13 @@ async function run(options) {
16322
16759
  const safeReason2 = redactDiagnosticText(reason).slice(0, MAX_DISCONNECT_REASON_LENGTH);
16323
16760
  logActivity(state, {
16324
16761
  type: "info",
16325
- message: `Tunnel disconnected (generation: ${transition.generation}, code: ${code}, reason: ${safeReason2})`
16762
+ message: `Tunnel disconnected (generation: ${transition.generation}, relay connection: ${transition.relayConnectionId ?? "unknown"}, code: ${code}, reason: ${safeReason2})`
16326
16763
  });
16327
16764
  emitAgentDisconnected(state.agentId, {
16328
16765
  code,
16329
16766
  reason: safeReason2,
16330
- connection_generation: transition.generation
16767
+ connection_generation: transition.generation,
16768
+ ...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {}
16331
16769
  });
16332
16770
  if (state.interactive) displayStatus(state);
16333
16771
  },
@@ -16478,9 +16916,9 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
16478
16916
  "--endpoint <url>",
16479
16917
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
16480
16918
  ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
16481
- const { endpoint, tunnel } = thisCommand.opts();
16482
- if (endpoint) {
16483
- setEndpoint(endpoint);
16919
+ const { endpoint: endpoint2, tunnel } = thisCommand.opts();
16920
+ if (endpoint2) {
16921
+ setEndpoint(endpoint2);
16484
16922
  }
16485
16923
  if (tunnel) {
16486
16924
  setTunnelUrl(tunnel);