@evident-ai/cli 3.6.1-dev.e0da455 → 3.6.1-dev.ebfd455
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 +925 -64
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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
|
|
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:
|
|
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
|
|
1160
|
-
import { homedir as
|
|
1161
|
-
import { isAbsolute as isAbsolute4, join as
|
|
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.
|
|
1445
|
+
var CLI_VERSION = (true ? "3.6.1-dev.ebfd455" : 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
|
|
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(
|
|
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(
|
|
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
|
|
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:
|
|
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(
|
|
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:
|
|
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
|
|
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:
|
|
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:
|
|
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:
|
|
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 = [
|
|
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
|
-
|
|
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, {
|
|
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(
|
|
7145
|
-
const { requestedPath, content, allowedDirectories, homeDir } =
|
|
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
|
|
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
|
-
|
|
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.
|
|
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,38 @@ 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
|
+
}
|
|
13923
|
+
function removeManagedOpenCodeConfigContent(content) {
|
|
13924
|
+
if (!content?.trim()) return content;
|
|
13925
|
+
const config = parseConfigContent(content);
|
|
13926
|
+
if (typeof config.provider !== "object" || config.provider === null || Array.isArray(config.provider)) {
|
|
13927
|
+
return content;
|
|
13928
|
+
}
|
|
13929
|
+
const provider = { ...config.provider };
|
|
13930
|
+
let changed = false;
|
|
13931
|
+
for (const namespace of CREDENTIAL_PROXY_NATIVE_NAMESPACES) {
|
|
13932
|
+
if (namespace in provider) {
|
|
13933
|
+
delete provider[namespace];
|
|
13934
|
+
changed = true;
|
|
13935
|
+
}
|
|
13936
|
+
}
|
|
13937
|
+
return changed ? JSON.stringify({ ...config, provider }) : content;
|
|
13938
|
+
}
|
|
13541
13939
|
function isFile(filePath) {
|
|
13542
13940
|
return existsSync2(filePath) && statSync6(filePath).isFile();
|
|
13543
13941
|
}
|
|
@@ -13571,6 +13969,159 @@ function applyRunnerOpenCodeConfig({
|
|
|
13571
13969
|
log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
|
|
13572
13970
|
}
|
|
13573
13971
|
|
|
13972
|
+
// src/lib/opencode/runtime-provenance.ts
|
|
13973
|
+
import { readFileSync as readFileSync7, readdirSync } from "node:fs";
|
|
13974
|
+
import { homedir as homedir7 } from "node:os";
|
|
13975
|
+
import { join as join12 } from "node:path";
|
|
13976
|
+
var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
|
|
13977
|
+
var REGISTRY_SPEC = /^[a-z0-9.*+^~<>=|-]+$/i;
|
|
13978
|
+
function errorKind(error2) {
|
|
13979
|
+
if (!(error2 instanceof Error)) return "unknown error";
|
|
13980
|
+
const code = "code" in error2 && typeof error2.code === "string" ? ` (${error2.code})` : "";
|
|
13981
|
+
return `${error2.name}${code}`;
|
|
13982
|
+
}
|
|
13983
|
+
function parseRegistryPluginSpec(value) {
|
|
13984
|
+
const separator = value.lastIndexOf("@");
|
|
13985
|
+
if (separator <= 0) return null;
|
|
13986
|
+
const name = value.slice(0, separator);
|
|
13987
|
+
const spec = value.slice(separator + 1);
|
|
13988
|
+
if (!PACKAGE_NAME.test(name) || !REGISTRY_SPEC.test(spec)) return null;
|
|
13989
|
+
return { name, spec };
|
|
13990
|
+
}
|
|
13991
|
+
function parseJsonc(value) {
|
|
13992
|
+
let output = "";
|
|
13993
|
+
let inString = false;
|
|
13994
|
+
let escaped = false;
|
|
13995
|
+
let lineComment = false;
|
|
13996
|
+
let blockComment = false;
|
|
13997
|
+
for (let index = 0; index < value.length; index++) {
|
|
13998
|
+
const character = value[index];
|
|
13999
|
+
const next = value[index + 1];
|
|
14000
|
+
if (lineComment) {
|
|
14001
|
+
if (character === "\n") {
|
|
14002
|
+
lineComment = false;
|
|
14003
|
+
output += character;
|
|
14004
|
+
}
|
|
14005
|
+
continue;
|
|
14006
|
+
}
|
|
14007
|
+
if (blockComment) {
|
|
14008
|
+
if (character === "*" && next === "/") {
|
|
14009
|
+
blockComment = false;
|
|
14010
|
+
index++;
|
|
14011
|
+
} else if (character === "\n") {
|
|
14012
|
+
output += character;
|
|
14013
|
+
}
|
|
14014
|
+
continue;
|
|
14015
|
+
}
|
|
14016
|
+
if (inString) {
|
|
14017
|
+
output += character;
|
|
14018
|
+
if (escaped) escaped = false;
|
|
14019
|
+
else if (character === "\\") escaped = true;
|
|
14020
|
+
else if (character === '"') inString = false;
|
|
14021
|
+
continue;
|
|
14022
|
+
}
|
|
14023
|
+
if (character === '"') {
|
|
14024
|
+
inString = true;
|
|
14025
|
+
output += character;
|
|
14026
|
+
} else if (character === "/" && next === "/") {
|
|
14027
|
+
lineComment = true;
|
|
14028
|
+
index++;
|
|
14029
|
+
} else if (character === "/" && next === "*") {
|
|
14030
|
+
blockComment = true;
|
|
14031
|
+
index++;
|
|
14032
|
+
} else if (character === ",") {
|
|
14033
|
+
let lookahead = index + 1;
|
|
14034
|
+
while (/\s/.test(value[lookahead] ?? "")) lookahead++;
|
|
14035
|
+
if (value[lookahead] !== "]" && value[lookahead] !== "}") output += character;
|
|
14036
|
+
} else {
|
|
14037
|
+
output += character;
|
|
14038
|
+
}
|
|
14039
|
+
}
|
|
14040
|
+
return JSON.parse(output);
|
|
14041
|
+
}
|
|
14042
|
+
function openCodeCacheRoot(env = process.env, homeDir = homedir7()) {
|
|
14043
|
+
return join12(env.XDG_CACHE_HOME ?? join12(homeDir, ".cache"), "opencode");
|
|
14044
|
+
}
|
|
14045
|
+
function readConfiguredPluginSpecs({
|
|
14046
|
+
cwd = process.cwd(),
|
|
14047
|
+
log: log3
|
|
14048
|
+
}) {
|
|
14049
|
+
let config;
|
|
14050
|
+
try {
|
|
14051
|
+
try {
|
|
14052
|
+
config = parseJsonc(readFileSync7(join12(cwd, "opencode.jsonc"), "utf8"));
|
|
14053
|
+
} catch (error2) {
|
|
14054
|
+
if (!("code" in Object(error2)) || Object(error2).code !== "ENOENT") throw error2;
|
|
14055
|
+
config = parseJsonc(readFileSync7(join12(cwd, "opencode.json"), "utf8"));
|
|
14056
|
+
}
|
|
14057
|
+
} catch (error2) {
|
|
14058
|
+
log3(`Could not read OpenCode plugin configuration: ${errorKind(error2)}`);
|
|
14059
|
+
return [];
|
|
14060
|
+
}
|
|
14061
|
+
if (typeof config !== "object" || config === null || !("plugin" in config)) return [];
|
|
14062
|
+
const plugins = config.plugin;
|
|
14063
|
+
if (!Array.isArray(plugins)) {
|
|
14064
|
+
log3("Could not read OpenCode plugin configuration: plugin is not an array");
|
|
14065
|
+
return [];
|
|
14066
|
+
}
|
|
14067
|
+
const configured = plugins.filter(
|
|
14068
|
+
(plugin) => typeof plugin === "string" && parseRegistryPluginSpec(plugin) !== null
|
|
14069
|
+
);
|
|
14070
|
+
if (configured.length !== plugins.length) {
|
|
14071
|
+
log3(
|
|
14072
|
+
`Skipped ${plugins.length - configured.length} non-registry OpenCode plugin spec(s); their values were not recorded`
|
|
14073
|
+
);
|
|
14074
|
+
}
|
|
14075
|
+
return configured;
|
|
14076
|
+
}
|
|
14077
|
+
function resolveInstalledPluginVersions({
|
|
14078
|
+
cacheRoot,
|
|
14079
|
+
env = process.env,
|
|
14080
|
+
homeDir = homedir7(),
|
|
14081
|
+
log: log3
|
|
14082
|
+
}) {
|
|
14083
|
+
const packagesRoot = join12(cacheRoot ?? openCodeCacheRoot(env, homeDir), "packages");
|
|
14084
|
+
let directories;
|
|
14085
|
+
try {
|
|
14086
|
+
directories = readdirSync(packagesRoot, { withFileTypes: true });
|
|
14087
|
+
} catch (error2) {
|
|
14088
|
+
if ("code" in Object(error2) && Object(error2).code === "ENOENT") return [];
|
|
14089
|
+
log3(`Could not inspect the OpenCode plugin cache: ${errorKind(error2)}`);
|
|
14090
|
+
return [];
|
|
14091
|
+
}
|
|
14092
|
+
const plugins = [];
|
|
14093
|
+
let skipped = 0;
|
|
14094
|
+
for (const directory of directories) {
|
|
14095
|
+
if (!directory.isDirectory()) continue;
|
|
14096
|
+
const parsed = parseRegistryPluginSpec(directory.name);
|
|
14097
|
+
if (parsed === null) {
|
|
14098
|
+
skipped++;
|
|
14099
|
+
continue;
|
|
14100
|
+
}
|
|
14101
|
+
let resolvedVersion = null;
|
|
14102
|
+
try {
|
|
14103
|
+
const packageJson = JSON.parse(
|
|
14104
|
+
readFileSync7(
|
|
14105
|
+
join12(packagesRoot, directory.name, "node_modules", parsed.name, "package.json"),
|
|
14106
|
+
"utf8"
|
|
14107
|
+
)
|
|
14108
|
+
);
|
|
14109
|
+
if (typeof packageJson.version === "string" && REGISTRY_SPEC.test(packageJson.version)) {
|
|
14110
|
+
resolvedVersion = packageJson.version;
|
|
14111
|
+
} else {
|
|
14112
|
+
log3(`Could not resolve OpenCode plugin ${parsed.name}@${parsed.spec}: invalid version`);
|
|
14113
|
+
}
|
|
14114
|
+
} catch (error2) {
|
|
14115
|
+
log3(`Could not resolve OpenCode plugin ${parsed.name}@${parsed.spec}: ${errorKind(error2)}`);
|
|
14116
|
+
}
|
|
14117
|
+
plugins.push({ ...parsed, resolvedVersion });
|
|
14118
|
+
}
|
|
14119
|
+
if (skipped > 0) {
|
|
14120
|
+
log3(`Skipped ${skipped} non-registry OpenCode package cache entry; its value was not recorded`);
|
|
14121
|
+
}
|
|
14122
|
+
return plugins;
|
|
14123
|
+
}
|
|
14124
|
+
|
|
13574
14125
|
// src/lib/credential-sync.ts
|
|
13575
14126
|
import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
|
|
13576
14127
|
var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
|
|
@@ -13806,6 +14357,230 @@ function createCredentialSync({
|
|
|
13806
14357
|
};
|
|
13807
14358
|
}
|
|
13808
14359
|
|
|
14360
|
+
// src/lib/managed-inference-setup.ts
|
|
14361
|
+
var defaultStore = {
|
|
14362
|
+
get: getManagedInferenceCredential,
|
|
14363
|
+
set: setManagedInferenceCredential,
|
|
14364
|
+
clear: clearManagedInferenceCredential
|
|
14365
|
+
};
|
|
14366
|
+
function endpoint(options, operation) {
|
|
14367
|
+
return `${options.apiUrl}/runners/${options.agentId}/managed-credentials/${operation}`;
|
|
14368
|
+
}
|
|
14369
|
+
function requestHeaders(options) {
|
|
14370
|
+
return { Authorization: options.getAuthHeader(), "Content-Type": "application/json" };
|
|
14371
|
+
}
|
|
14372
|
+
function request2(options) {
|
|
14373
|
+
return withRequestTimeout(options.fetchImpl ?? fetch, REQUEST_TIMEOUT_MS);
|
|
14374
|
+
}
|
|
14375
|
+
function safeFailure(operation, status2) {
|
|
14376
|
+
return status2 === void 0 ? `${operation} could not reach the managed credential service` : `${operation} returned HTTP ${status2}`;
|
|
14377
|
+
}
|
|
14378
|
+
function logTransportFailure(options, operation, error2, authorization) {
|
|
14379
|
+
let detail = error2 instanceof Error ? error2.message : String(error2);
|
|
14380
|
+
const credential = authorization.split(/\s+/, 2)[1];
|
|
14381
|
+
for (const secret of [authorization, credential]) {
|
|
14382
|
+
if (secret) detail = detail.replaceAll(secret, "[redacted]");
|
|
14383
|
+
}
|
|
14384
|
+
options.log(
|
|
14385
|
+
`MANAGED-INFERENCE-TRANSPORT-FAILED: operation=${operation} detail=${redactDiagnosticText(detail)}`,
|
|
14386
|
+
"debug"
|
|
14387
|
+
);
|
|
14388
|
+
}
|
|
14389
|
+
async function responseJson(response) {
|
|
14390
|
+
try {
|
|
14391
|
+
const value = await response.json();
|
|
14392
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
14393
|
+
} catch (error2) {
|
|
14394
|
+
return null;
|
|
14395
|
+
}
|
|
14396
|
+
}
|
|
14397
|
+
function readSetup(value) {
|
|
14398
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
14399
|
+
const setup = value;
|
|
14400
|
+
if (typeof setup.runner_id !== "string" || typeof setup.generation !== "string" || typeof setup.status !== "string" || setup.token_id !== null && typeof setup.token_id !== "string") {
|
|
14401
|
+
return null;
|
|
14402
|
+
}
|
|
14403
|
+
return setup;
|
|
14404
|
+
}
|
|
14405
|
+
function clearLocalSetup(options) {
|
|
14406
|
+
const env = options.env ?? process.env;
|
|
14407
|
+
(options.store ?? defaultStore).clear(options.agentId);
|
|
14408
|
+
delete env.EVIDENT_PROXY_TOKEN;
|
|
14409
|
+
try {
|
|
14410
|
+
const content = removeManagedOpenCodeConfigContent(env.OPENCODE_CONFIG_CONTENT);
|
|
14411
|
+
if (content === void 0) delete env.OPENCODE_CONFIG_CONTENT;
|
|
14412
|
+
else env.OPENCODE_CONFIG_CONTENT = content;
|
|
14413
|
+
} catch (error2) {
|
|
14414
|
+
options.log(
|
|
14415
|
+
"MANAGED-INFERENCE-CLEANUP-PARTIAL: stored credentials were removed, but malformed OPENCODE_CONFIG_CONTENT could not be inspected",
|
|
14416
|
+
"warn"
|
|
14417
|
+
);
|
|
14418
|
+
}
|
|
14419
|
+
}
|
|
14420
|
+
async function discoverManagedInferenceSetup(options) {
|
|
14421
|
+
const headers = requestHeaders(options);
|
|
14422
|
+
let response;
|
|
14423
|
+
try {
|
|
14424
|
+
response = await request2(options)(endpoint(options, "current"), {
|
|
14425
|
+
headers
|
|
14426
|
+
});
|
|
14427
|
+
} catch (error2) {
|
|
14428
|
+
logTransportFailure(options, "discovery", error2, headers.Authorization);
|
|
14429
|
+
return { kind: "failed", reason: safeFailure("Managed setup discovery") };
|
|
14430
|
+
}
|
|
14431
|
+
if (response.status === 404) {
|
|
14432
|
+
clearLocalSetup(options);
|
|
14433
|
+
return { kind: "none" };
|
|
14434
|
+
}
|
|
14435
|
+
if (!response.ok) {
|
|
14436
|
+
return { kind: "failed", reason: safeFailure("Managed setup discovery", response.status) };
|
|
14437
|
+
}
|
|
14438
|
+
const body = await responseJson(response);
|
|
14439
|
+
const setup = readSetup(body?.setup);
|
|
14440
|
+
return setup ? { kind: "setup", setup } : { kind: "failed", reason: "Managed setup discovery returned an invalid response" };
|
|
14441
|
+
}
|
|
14442
|
+
async function post(options, operation, body) {
|
|
14443
|
+
const headers = requestHeaders(options);
|
|
14444
|
+
try {
|
|
14445
|
+
return await request2(options)(endpoint(options, operation), {
|
|
14446
|
+
method: "POST",
|
|
14447
|
+
headers,
|
|
14448
|
+
body: JSON.stringify(body)
|
|
14449
|
+
});
|
|
14450
|
+
} catch (error2) {
|
|
14451
|
+
logTransportFailure(options, operation, error2, headers.Authorization);
|
|
14452
|
+
return null;
|
|
14453
|
+
}
|
|
14454
|
+
}
|
|
14455
|
+
function applyCredential(options, credential) {
|
|
14456
|
+
const { config, unsupportedProviders } = buildCredentialProxyNativeConfig({
|
|
14457
|
+
inferenceBaseUrl: credential.inferenceBaseUrl,
|
|
14458
|
+
modelDescriptors: credential.modelDescriptors
|
|
14459
|
+
});
|
|
14460
|
+
if (unsupportedProviders.length > 0 || Object.keys(config.provider).length === 0) {
|
|
14461
|
+
return "Managed setup contains unsupported provider descriptors";
|
|
14462
|
+
}
|
|
14463
|
+
const env = options.env ?? process.env;
|
|
14464
|
+
let merged;
|
|
14465
|
+
try {
|
|
14466
|
+
merged = mergeManagedOpenCodeConfigContent(env.OPENCODE_CONFIG_CONTENT, config.provider);
|
|
14467
|
+
} catch (error2) {
|
|
14468
|
+
return "OPENCODE_CONFIG_CONTENT is malformed; managed providers were not installed";
|
|
14469
|
+
}
|
|
14470
|
+
try {
|
|
14471
|
+
(options.store ?? defaultStore).set(options.agentId, credential);
|
|
14472
|
+
} catch (error2) {
|
|
14473
|
+
options.log(
|
|
14474
|
+
`MANAGED-INFERENCE-STORE-FAILED: runner=${options.agentId} generation=${credential.generation}`,
|
|
14475
|
+
"warn"
|
|
14476
|
+
);
|
|
14477
|
+
return "Managed credentials could not be written to the protected store";
|
|
14478
|
+
}
|
|
14479
|
+
env.EVIDENT_PROXY_TOKEN = credential.token;
|
|
14480
|
+
env.OPENCODE_CONFIG_CONTENT = merged;
|
|
14481
|
+
return null;
|
|
14482
|
+
}
|
|
14483
|
+
async function reportManagedInferenceApplyFailure(options, failure) {
|
|
14484
|
+
const response = await post(options, "report-failure", {
|
|
14485
|
+
generation: failure.generation,
|
|
14486
|
+
token_id: failure.tokenId
|
|
14487
|
+
});
|
|
14488
|
+
if (!response?.ok) {
|
|
14489
|
+
options.log(
|
|
14490
|
+
`MANAGED-INFERENCE-REPORT-FAILED: runner=${options.agentId} generation=${failure.generation}${response ? ` status=${response.status}` : ""}`,
|
|
14491
|
+
"warn"
|
|
14492
|
+
);
|
|
14493
|
+
}
|
|
14494
|
+
}
|
|
14495
|
+
async function reaffirmStored(options, credential) {
|
|
14496
|
+
const response = await post(options, "reaffirm", {
|
|
14497
|
+
generation: credential.generation,
|
|
14498
|
+
token_id: credential.tokenId
|
|
14499
|
+
});
|
|
14500
|
+
if (!response?.ok) {
|
|
14501
|
+
return {
|
|
14502
|
+
kind: "failed",
|
|
14503
|
+
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")
|
|
14504
|
+
};
|
|
14505
|
+
}
|
|
14506
|
+
const body = await responseJson(response);
|
|
14507
|
+
const setup = readSetup(body?.setup);
|
|
14508
|
+
if (!setup || setup.generation !== credential.generation || setup.token_id !== credential.tokenId) {
|
|
14509
|
+
return { kind: "failed", reason: "Managed credential reaffirmation returned a mismatch" };
|
|
14510
|
+
}
|
|
14511
|
+
const failure = applyCredential(options, credential);
|
|
14512
|
+
return failure ? { kind: "failed", reason: failure } : { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
|
|
14513
|
+
}
|
|
14514
|
+
async function prepareManagedInferenceSetup(options, discovery, health) {
|
|
14515
|
+
if (health.authFailed) {
|
|
14516
|
+
return {
|
|
14517
|
+
kind: "failed",
|
|
14518
|
+
reason: "OpenCode authentication failed; managed credentials were not rotated"
|
|
14519
|
+
};
|
|
14520
|
+
}
|
|
14521
|
+
const stored = (options.store ?? defaultStore).get(options.agentId);
|
|
14522
|
+
if (health.healthy) {
|
|
14523
|
+
if (!stored) {
|
|
14524
|
+
return {
|
|
14525
|
+
kind: "failed",
|
|
14526
|
+
reason: "Managed credentials are missing for the serving OpenCode process; restart required"
|
|
14527
|
+
};
|
|
14528
|
+
}
|
|
14529
|
+
return reaffirmStored(options, stored);
|
|
14530
|
+
}
|
|
14531
|
+
if (discovery.setup.status === "acknowledged" && stored?.generation === discovery.setup.generation && stored.tokenId === discovery.setup.token_id) {
|
|
14532
|
+
return reaffirmStored(options, stored);
|
|
14533
|
+
}
|
|
14534
|
+
const response = await post(options, "bootstrap", { generation: discovery.setup.generation });
|
|
14535
|
+
if (!response?.ok) {
|
|
14536
|
+
return {
|
|
14537
|
+
kind: "failed",
|
|
14538
|
+
reason: response ? safeFailure("Managed credential bootstrap", response.status) : safeFailure("Managed credential bootstrap")
|
|
14539
|
+
};
|
|
14540
|
+
}
|
|
14541
|
+
const body = await responseJson(response);
|
|
14542
|
+
const setup = readSetup(body?.setup);
|
|
14543
|
+
const token = body?.inference_token;
|
|
14544
|
+
const inferenceBaseUrl = body?.inference_base_url;
|
|
14545
|
+
const modelDescriptors = body?.model_descriptors;
|
|
14546
|
+
if (!setup || setup.generation !== discovery.setup.generation || typeof setup.token_id !== "string" || typeof token !== "string" || typeof inferenceBaseUrl !== "string" || !Array.isArray(modelDescriptors) || !modelDescriptors.every(
|
|
14547
|
+
(descriptor) => typeof descriptor === "object" && descriptor !== null && typeof descriptor.id === "string" && typeof descriptor.provider === "string"
|
|
14548
|
+
)) {
|
|
14549
|
+
return { kind: "failed", reason: "Managed credential bootstrap returned an invalid response" };
|
|
14550
|
+
}
|
|
14551
|
+
const credential = {
|
|
14552
|
+
generation: setup.generation,
|
|
14553
|
+
tokenId: setup.token_id,
|
|
14554
|
+
token,
|
|
14555
|
+
inferenceBaseUrl,
|
|
14556
|
+
modelDescriptors
|
|
14557
|
+
};
|
|
14558
|
+
const failure = applyCredential(options, credential);
|
|
14559
|
+
if (failure) {
|
|
14560
|
+
await reportManagedInferenceApplyFailure(options, credential);
|
|
14561
|
+
return { kind: "failed", reason: failure };
|
|
14562
|
+
}
|
|
14563
|
+
return { kind: "ready", generation: credential.generation, tokenId: credential.tokenId };
|
|
14564
|
+
}
|
|
14565
|
+
async function acknowledgeManagedInferenceSetup(options, preparation) {
|
|
14566
|
+
const response = await post(options, "acknowledge", {
|
|
14567
|
+
generation: preparation.generation,
|
|
14568
|
+
token_id: preparation.tokenId,
|
|
14569
|
+
config_validated: true
|
|
14570
|
+
});
|
|
14571
|
+
if (!response?.ok) {
|
|
14572
|
+
throw new Error(
|
|
14573
|
+
response ? safeFailure("Managed credential acknowledgment", response.status) : safeFailure("Managed credential acknowledgment")
|
|
14574
|
+
);
|
|
14575
|
+
}
|
|
14576
|
+
const body = await responseJson(response);
|
|
14577
|
+
const setup = readSetup(body?.setup);
|
|
14578
|
+
if (!setup || setup.generation !== preparation.generation || setup.token_id !== preparation.tokenId) {
|
|
14579
|
+
throw new Error("Managed credential acknowledgment returned a mismatch");
|
|
14580
|
+
}
|
|
14581
|
+
return response.status === 200 && setup.status === "acknowledged" ? "acknowledged" : "pending";
|
|
14582
|
+
}
|
|
14583
|
+
|
|
13809
14584
|
// src/commands/run.ts
|
|
13810
14585
|
var MAX_ACTIVITY_LOG_ENTRIES = 10;
|
|
13811
14586
|
var MAX_DISCONNECT_REASON_LENGTH = 200;
|
|
@@ -13846,7 +14621,7 @@ function resolveFileSyncDirectories(raw, homeDir) {
|
|
|
13846
14621
|
if (trimmed === "") {
|
|
13847
14622
|
throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
|
|
13848
14623
|
}
|
|
13849
|
-
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ?
|
|
14624
|
+
const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join13(homeDir, trimmed.slice(2)) : trimmed;
|
|
13850
14625
|
if (!isAbsolute4(expanded)) {
|
|
13851
14626
|
throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
|
|
13852
14627
|
}
|
|
@@ -14001,7 +14776,7 @@ function logActivity(state, entry) {
|
|
|
14001
14776
|
}
|
|
14002
14777
|
function reportSessionDbRecovery(state) {
|
|
14003
14778
|
try {
|
|
14004
|
-
const report = drainSessionDbRecoveryReport({ homeDir:
|
|
14779
|
+
const report = drainSessionDbRecoveryReport({ homeDir: homedir8(), env: process.env });
|
|
14005
14780
|
for (const record of report.records) {
|
|
14006
14781
|
const activity = buildSessionDbRecoveryActivity(record);
|
|
14007
14782
|
if (!activity) throw new Error("could not map session-DB recovery record");
|
|
@@ -14082,7 +14857,7 @@ async function importOpenCodeV2CredentialsForState(state) {
|
|
|
14082
14857
|
}
|
|
14083
14858
|
const result = await importOpenCodeV2Credentials({
|
|
14084
14859
|
request: client.request,
|
|
14085
|
-
homeDir:
|
|
14860
|
+
homeDir: homedir8(),
|
|
14086
14861
|
directory,
|
|
14087
14862
|
guard: state.opencodeV2CredentialImportGuard,
|
|
14088
14863
|
log: (message, level = "info") => logActivity(state, { type: "info", level, message })
|
|
@@ -14502,7 +15277,7 @@ function shouldWarnForReclaimSkip(reason) {
|
|
|
14502
15277
|
return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
|
|
14503
15278
|
}
|
|
14504
15279
|
function sessionDbPath() {
|
|
14505
|
-
return
|
|
15280
|
+
return join13(homedir8(), ".local", "share", "opencode", "opencode.db");
|
|
14506
15281
|
}
|
|
14507
15282
|
function logSessionCleanupActivity(state, phase, entry) {
|
|
14508
15283
|
logActivity(state, {
|
|
@@ -14746,7 +15521,7 @@ function scheduleSessionCleanup(state, driver, options) {
|
|
|
14746
15521
|
for (const warning2 of config.warnings) {
|
|
14747
15522
|
logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
|
|
14748
15523
|
}
|
|
14749
|
-
const dbBytes = statSessionDbBytes(
|
|
15524
|
+
const dbBytes = statSessionDbBytes(homedir8());
|
|
14750
15525
|
void (async () => {
|
|
14751
15526
|
const reclaimAvailability = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
|
|
14752
15527
|
if (reclaimAvailability !== null) {
|
|
@@ -14965,7 +15740,7 @@ function scheduleResourceUsageReporting(state, options) {
|
|
|
14965
15740
|
});
|
|
14966
15741
|
return;
|
|
14967
15742
|
}
|
|
14968
|
-
const { collect, stop } = createResourceUsageCollector(
|
|
15743
|
+
const { collect, stop } = createResourceUsageCollector(homedir8());
|
|
14969
15744
|
state.stopResourceUsageSampling = stop;
|
|
14970
15745
|
let consecutiveFailures = 0;
|
|
14971
15746
|
const tick = async () => {
|
|
@@ -15206,7 +15981,7 @@ async function run(options) {
|
|
|
15206
15981
|
let fileSyncDirectories;
|
|
15207
15982
|
try {
|
|
15208
15983
|
logLevel = resolveLogLevel(options);
|
|
15209
|
-
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo,
|
|
15984
|
+
fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir8());
|
|
15210
15985
|
if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
|
|
15211
15986
|
throw new Error(
|
|
15212
15987
|
"--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
|
|
@@ -15492,7 +16267,7 @@ async function run(options) {
|
|
|
15492
16267
|
state.credentialSync?.arm();
|
|
15493
16268
|
const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
|
|
15494
16269
|
context: {
|
|
15495
|
-
homeDir:
|
|
16270
|
+
homeDir: homedir8(),
|
|
15496
16271
|
cwd: process.cwd(),
|
|
15497
16272
|
microvmId: process.env.MICROVM_ID?.trim(),
|
|
15498
16273
|
euid: process.getuid?.(),
|
|
@@ -15515,7 +16290,7 @@ async function run(options) {
|
|
|
15515
16290
|
dependencyInstallDiagnosticReporter
|
|
15516
16291
|
);
|
|
15517
16292
|
const openCodeLogTail = tailOpenCodeLogFile(
|
|
15518
|
-
resolveOpenCodeLogPath(
|
|
16293
|
+
resolveOpenCodeLogPath(homedir8(), process.env),
|
|
15519
16294
|
openCodeActivityForwarder
|
|
15520
16295
|
);
|
|
15521
16296
|
state.stopOpenCodeLogTail = () => {
|
|
@@ -15590,6 +16365,40 @@ async function run(options) {
|
|
|
15590
16365
|
for (const warning2 of opencodeVersionWarnings) {
|
|
15591
16366
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
15592
16367
|
}
|
|
16368
|
+
const managedSetupOptions = {
|
|
16369
|
+
agentId: state.agentId,
|
|
16370
|
+
apiUrl: getApiUrlConfig(),
|
|
16371
|
+
getAuthHeader: () => state.authHeader,
|
|
16372
|
+
log: (message, level = "info") => logActivity(state, {
|
|
16373
|
+
type: level === "error" ? "error" : "info",
|
|
16374
|
+
level,
|
|
16375
|
+
...level === "error" ? { error: message } : { message }
|
|
16376
|
+
})
|
|
16377
|
+
};
|
|
16378
|
+
const managedDiscovery = await discoverManagedInferenceSetup(managedSetupOptions);
|
|
16379
|
+
let managedPreparation = { kind: "none" };
|
|
16380
|
+
if (managedDiscovery.kind === "failed") {
|
|
16381
|
+
managedPreparation = managedDiscovery;
|
|
16382
|
+
managedSetupOptions.log(`MANAGED-INFERENCE-NOT-READY: ${managedDiscovery.reason}`, "warn");
|
|
16383
|
+
} else if (managedDiscovery.kind === "setup") {
|
|
16384
|
+
const managedHealth = opencodeVersion === "v2" ? await checkOpenCode2Health(state.port) : await checkOpenCodeHealth(state.port);
|
|
16385
|
+
managedPreparation = await prepareManagedInferenceSetup(
|
|
16386
|
+
managedSetupOptions,
|
|
16387
|
+
managedDiscovery,
|
|
16388
|
+
managedHealth
|
|
16389
|
+
);
|
|
16390
|
+
if (managedPreparation.kind === "failed") {
|
|
16391
|
+
managedSetupOptions.log(
|
|
16392
|
+
`MANAGED-INFERENCE-NOT-READY: ${managedPreparation.reason}`,
|
|
16393
|
+
"warn"
|
|
16394
|
+
);
|
|
16395
|
+
} else if (managedPreparation.kind === "ready") {
|
|
16396
|
+
managedSetupOptions.log(
|
|
16397
|
+
`MANAGED-INFERENCE-PREPARED: runner=${state.agentId} generation=${managedPreparation.generation}`,
|
|
16398
|
+
"info"
|
|
16399
|
+
);
|
|
16400
|
+
}
|
|
16401
|
+
}
|
|
15593
16402
|
const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
|
|
15594
16403
|
for (const warning2 of maxActiveSessionsWarnings) {
|
|
15595
16404
|
logActivity(state, { type: "info", level: "warn", message: warning2 });
|
|
@@ -15616,6 +16425,32 @@ async function run(options) {
|
|
|
15616
16425
|
state.opencodeProcess = options.opencodePidFile ? null : oc.process;
|
|
15617
16426
|
state.opencodeVersion = oc.version;
|
|
15618
16427
|
state.opencodeApiVersion = opencodeVersion;
|
|
16428
|
+
let configuredPlugins = [];
|
|
16429
|
+
let resolvedPlugins = [];
|
|
16430
|
+
try {
|
|
16431
|
+
const provenanceLog = (message) => logActivity(state, { type: "info", level: "warn", message });
|
|
16432
|
+
configuredPlugins = readConfiguredPluginSpecs({ log: provenanceLog });
|
|
16433
|
+
resolvedPlugins = resolveInstalledPluginVersions({ log: provenanceLog });
|
|
16434
|
+
} catch (error2) {
|
|
16435
|
+
const kind = error2 instanceof Error ? error2.name : "unknown error";
|
|
16436
|
+
logActivity(state, {
|
|
16437
|
+
type: "info",
|
|
16438
|
+
level: "warn",
|
|
16439
|
+
message: `Could not collect OpenCode runtime provenance: ${kind}`
|
|
16440
|
+
});
|
|
16441
|
+
}
|
|
16442
|
+
logActivity(state, {
|
|
16443
|
+
type: "info",
|
|
16444
|
+
level: "info",
|
|
16445
|
+
message: "OpenCode runtime provenance",
|
|
16446
|
+
metadata: {
|
|
16447
|
+
opencode_version: state.opencodeVersion,
|
|
16448
|
+
opencode_api_version: state.opencodeApiVersion,
|
|
16449
|
+
configured_plugins: JSON.stringify(configuredPlugins),
|
|
16450
|
+
resolved_plugins: JSON.stringify(resolvedPlugins)
|
|
16451
|
+
},
|
|
16452
|
+
source: "cli.runtime-provenance"
|
|
16453
|
+
});
|
|
15619
16454
|
let opencodePassword = null;
|
|
15620
16455
|
if (opencodeVersion === "v2" && "password" in oc) {
|
|
15621
16456
|
const value = oc.password;
|
|
@@ -15644,7 +16479,7 @@ async function run(options) {
|
|
|
15644
16479
|
const provenance = checkSessionDbProvenance({
|
|
15645
16480
|
dbPath: sessionDbPath(),
|
|
15646
16481
|
currentVersion: state.opencodeVersion,
|
|
15647
|
-
homeDir:
|
|
16482
|
+
homeDir: homedir8(),
|
|
15648
16483
|
env: process.env
|
|
15649
16484
|
});
|
|
15650
16485
|
if (provenance.anomaly) {
|
|
@@ -15658,6 +16493,30 @@ async function run(options) {
|
|
|
15658
16493
|
}
|
|
15659
16494
|
}
|
|
15660
16495
|
state.opencodeConnected = oc.notReadyReason === null;
|
|
16496
|
+
if (managedPreparation.kind === "ready" && oc.notReadyReason === null) {
|
|
16497
|
+
try {
|
|
16498
|
+
const acknowledgement = await acknowledgeManagedInferenceSetup(
|
|
16499
|
+
managedSetupOptions,
|
|
16500
|
+
managedPreparation
|
|
16501
|
+
);
|
|
16502
|
+
if (acknowledgement === "acknowledged") {
|
|
16503
|
+
managedSetupOptions.log(
|
|
16504
|
+
`MANAGED-INFERENCE-ACKNOWLEDGED: runner=${state.agentId} generation=${managedPreparation.generation}`,
|
|
16505
|
+
"info"
|
|
16506
|
+
);
|
|
16507
|
+
} else {
|
|
16508
|
+
managedSetupOptions.log(
|
|
16509
|
+
`MANAGED-INFERENCE-NOT-READY: policy refresh is pending for runner=${state.agentId} generation=${managedPreparation.generation}`,
|
|
16510
|
+
"warn"
|
|
16511
|
+
);
|
|
16512
|
+
}
|
|
16513
|
+
} catch (error2) {
|
|
16514
|
+
managedSetupOptions.log(
|
|
16515
|
+
`MANAGED-INFERENCE-NOT-READY: ${error2 instanceof Error ? error2.message : String(error2)}`,
|
|
16516
|
+
"warn"
|
|
16517
|
+
);
|
|
16518
|
+
}
|
|
16519
|
+
}
|
|
15661
16520
|
const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
|
|
15662
16521
|
ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
|
|
15663
16522
|
if (!state.interactive && oc.notReadyReason !== null) {
|
|
@@ -15716,7 +16575,7 @@ async function run(options) {
|
|
|
15716
16575
|
let existingPid;
|
|
15717
16576
|
if (existsSync3(options.litestreamPidFile)) {
|
|
15718
16577
|
try {
|
|
15719
|
-
const rawPid =
|
|
16578
|
+
const rawPid = readFileSync8(options.litestreamPidFile, "utf8").trim();
|
|
15720
16579
|
const parsedPid = Number(rawPid);
|
|
15721
16580
|
if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
|
|
15722
16581
|
existingPid = parsedPid;
|
|
@@ -15815,7 +16674,7 @@ async function run(options) {
|
|
|
15815
16674
|
// #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
|
|
15816
16675
|
// REJECTED with `file_sync_disabled` on the ack, not silently ignored.
|
|
15817
16676
|
fileSyncDirectories,
|
|
15818
|
-
homeDir:
|
|
16677
|
+
homeDir: homedir8(),
|
|
15819
16678
|
maxActiveSessions,
|
|
15820
16679
|
log: (entry) => (
|
|
15821
16680
|
// Thread the driver's real level straight through so `debug`/`warn`
|
|
@@ -15840,7 +16699,7 @@ async function run(options) {
|
|
|
15840
16699
|
onConnected: (agentId, isReconnect, transition) => {
|
|
15841
16700
|
state.connected = true;
|
|
15842
16701
|
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})`;
|
|
16702
|
+
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
16703
|
logActivity(state, {
|
|
15845
16704
|
type: "info",
|
|
15846
16705
|
message: connectionMessage
|
|
@@ -15873,6 +16732,7 @@ async function run(options) {
|
|
|
15873
16732
|
connected: state.opencodeConnected
|
|
15874
16733
|
}),
|
|
15875
16734
|
connection_generation: transition.generation,
|
|
16735
|
+
...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {},
|
|
15876
16736
|
...isReconnect && transition.downtimeMs !== null ? {
|
|
15877
16737
|
reconnect_attempt: transition.attempt,
|
|
15878
16738
|
downtime_ms: transition.downtimeMs
|
|
@@ -15903,12 +16763,13 @@ async function run(options) {
|
|
|
15903
16763
|
const safeReason2 = redactDiagnosticText(reason).slice(0, MAX_DISCONNECT_REASON_LENGTH);
|
|
15904
16764
|
logActivity(state, {
|
|
15905
16765
|
type: "info",
|
|
15906
|
-
message: `Tunnel disconnected (generation: ${transition.generation}, code: ${code}, reason: ${safeReason2})`
|
|
16766
|
+
message: `Tunnel disconnected (generation: ${transition.generation}, relay connection: ${transition.relayConnectionId ?? "unknown"}, code: ${code}, reason: ${safeReason2})`
|
|
15907
16767
|
});
|
|
15908
16768
|
emitAgentDisconnected(state.agentId, {
|
|
15909
16769
|
code,
|
|
15910
16770
|
reason: safeReason2,
|
|
15911
|
-
connection_generation: transition.generation
|
|
16771
|
+
connection_generation: transition.generation,
|
|
16772
|
+
...transition.relayConnectionId !== null ? { relay_connection_id: transition.relayConnectionId } : {}
|
|
15912
16773
|
});
|
|
15913
16774
|
if (state.interactive) displayStatus(state);
|
|
15914
16775
|
},
|
|
@@ -16059,9 +16920,9 @@ program.name("evident").description("Run OpenCode locally and connect it to Evid
|
|
|
16059
16920
|
"--endpoint <url>",
|
|
16060
16921
|
"Evident API base URL (default: production; e.g. http://localhost:3001)"
|
|
16061
16922
|
).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
|
|
16062
|
-
const { endpoint, tunnel } = thisCommand.opts();
|
|
16063
|
-
if (
|
|
16064
|
-
setEndpoint(
|
|
16923
|
+
const { endpoint: endpoint2, tunnel } = thisCommand.opts();
|
|
16924
|
+
if (endpoint2) {
|
|
16925
|
+
setEndpoint(endpoint2);
|
|
16065
16926
|
}
|
|
16066
16927
|
if (tunnel) {
|
|
16067
16928
|
setTunnelUrl(tunnel);
|