nexus-agents 8.103.1 → 8.103.3
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/{ast-rule-runner-H2VFAOT4.js → ast-rule-runner-XJLYSAGE.js} +3 -3
- package/dist/{child-mcp-config-Y3DPCM6L.js → child-mcp-config-U6SFHNXN.js} +2 -2
- package/dist/{chunk-W7HVGLPS.js → chunk-24XTED4P.js} +2 -2
- package/dist/{chunk-BGATTU3Z.js → chunk-3IZPJAIC.js} +5 -5
- package/dist/{chunk-SIPFKN6U.js → chunk-5LG5RMTM.js} +2 -2
- package/dist/{chunk-LHI66BKG.js → chunk-6PB7JUNT.js} +30 -6
- package/dist/chunk-6PB7JUNT.js.map +1 -0
- package/dist/{chunk-V7VGNFAN.js → chunk-73Y7XRKL.js} +22 -4
- package/dist/chunk-73Y7XRKL.js.map +1 -0
- package/dist/{chunk-E5QULKGJ.js → chunk-BNRWICG7.js} +8 -8
- package/dist/{chunk-7VZXPXC4.js → chunk-EBABZGF7.js} +22 -8
- package/dist/chunk-EBABZGF7.js.map +1 -0
- package/dist/{chunk-WWBB6HUI.js → chunk-FKN4CJDF.js} +4 -4
- package/dist/{chunk-QYWR7LJP.js → chunk-G47BD5WL.js} +2 -2
- package/dist/{chunk-MUMQRZM5.js → chunk-HCPESANB.js} +2 -2
- package/dist/{chunk-L6RAO6KC.js → chunk-HDERP5V6.js} +2 -2
- package/dist/{chunk-XKJYFHPO.js → chunk-ISKYBNLW.js} +2 -2
- package/dist/{chunk-TNBHH2XO.js → chunk-IXYKYOYP.js} +43 -40
- package/dist/{chunk-TNBHH2XO.js.map → chunk-IXYKYOYP.js.map} +1 -1
- package/dist/chunk-JX7D7GXS.js +82 -0
- package/dist/chunk-JX7D7GXS.js.map +1 -0
- package/dist/{chunk-NZNPMI3W.js → chunk-K3QNYYJZ.js} +2 -2
- package/dist/{chunk-ONMUMFUN.js → chunk-K3XIXAWE.js} +2 -2
- package/dist/{chunk-X7BYCDQN.js → chunk-KGLMAIY3.js} +3 -3
- package/dist/{chunk-3H62U2MH.js → chunk-KH3QDRPJ.js} +2 -2
- package/dist/{chunk-KDNWXGUF.js → chunk-KIKYLN2U.js} +2 -2
- package/dist/{chunk-46CXXIQ4.js → chunk-KKGN23Z5.js} +4 -4
- package/dist/{chunk-WVVJWPZT.js → chunk-LJJHGXLZ.js} +3 -3
- package/dist/{chunk-DIPNNIVK.js → chunk-LSSX77DS.js} +5 -5
- package/dist/{chunk-RL2O37NE.js → chunk-NAQDGUNA.js} +2 -2
- package/dist/{chunk-NFBKSKEE.js → chunk-PTB4NERU.js} +3 -3
- package/dist/{chunk-KUT76BHZ.js → chunk-PV7WSTTS.js} +2 -2
- package/dist/{chunk-4WIJ2LKW.js → chunk-Q3JF6G7N.js} +3 -3
- package/dist/{chunk-QSXDLYV4.js → chunk-QDELEGK7.js} +2 -2
- package/dist/{chunk-KEN3STUW.js → chunk-RSDRQQTA.js} +25 -10
- package/dist/chunk-RSDRQQTA.js.map +1 -0
- package/dist/{chunk-W76A3RPF.js → chunk-S6PDNDLL.js} +2 -2
- package/dist/{chunk-6NROQXOM.js → chunk-SGRWJW57.js} +2 -2
- package/dist/{chunk-ALX7T72L.js → chunk-ULL23ADE.js} +16 -76
- package/dist/chunk-ULL23ADE.js.map +1 -0
- package/dist/{chunk-MPQDZVC6.js → chunk-W7IFJFYX.js} +3 -3
- package/dist/{chunk-5EFWZHUV.js → chunk-XEXQG3VV.js} +2 -2
- package/dist/{chunk-TQ6OKB3G.js → chunk-YOEWP7LI.js} +12 -12
- package/dist/{chunk-FAO37OT4.js → chunk-ZG6UJP6U.js} +23 -2
- package/dist/{chunk-FAO37OT4.js.map → chunk-ZG6UJP6U.js.map} +1 -1
- package/dist/{cli-circuit-breaker-LYB4F3VP.js → cli-circuit-breaker-XWXGC4LJ.js} +3 -3
- package/dist/cli.js +51 -45
- package/dist/cli.js.map +1 -1
- package/dist/{composite-router-OLXAFCJE.js → composite-router-ZY5ZYCJ6.js} +2 -2
- package/dist/{consensus-vote-SWMMGIJU.js → consensus-vote-QYKZ4Y73.js} +17 -16
- package/dist/{context-retriever-5C5MS2ZF.js → context-retriever-EXBO3PJ3.js} +8 -8
- package/dist/{doctor-deep-YLOG5CAD.js → doctor-deep-TB36AVUC.js} +3 -3
- package/dist/{doctor-gateway-report-JNOMZGSQ.js → doctor-gateway-report-3IOPQ5ZY.js} +6 -6
- package/dist/{doctor-live-SRNNC37A.js → doctor-live-VK7XA7SX.js} +10 -10
- package/dist/{expert-bridge-H4EOOXWB.js → expert-bridge-NOHPIEDY.js} +5 -4
- package/dist/{factory-VOICDXGX.js → factory-2QMQC7MF.js} +9 -9
- package/dist/{factory-FHJ42ORZ.js → factory-NINQ76ZS.js} +5 -5
- package/dist/{improvement-review-OW2MEP4O.js → improvement-review-JAX2WDGT.js} +5 -5
- package/dist/index.js +32 -31
- package/dist/index.js.map +1 -1
- package/dist/{init-opencode-ZO7MEDSW.js → init-opencode-TYXXLQCC.js} +5 -5
- package/dist/issue-triage-NTSZQ6M5.js +16 -0
- package/dist/{openai-compat-adapter-WKXMQE62.js → openai-compat-adapter-KDVYYW3X.js} +5 -5
- package/dist/{pr-reviewer-helpers-UMNXRN2R.js → pr-reviewer-helpers-R3IC24OM.js} +4 -4
- package/dist/{registry-command-A4SZT4UX.js → registry-command-S6F5AL2O.js} +2 -2
- package/dist/{repo-security-plan-XF5N6D6R.js → repo-security-plan-4ISGRT2F.js} +3 -3
- package/dist/{research-helpers-synthesize-SKK7U6KA.js → research-helpers-synthesize-HYDSM5TV.js} +4 -4
- package/dist/{routing-memory-64AEPNLI.js → routing-memory-VR36BYAN.js} +2 -2
- package/dist/{session-memory-EWRSQOIF.js → session-memory-4SOE5DXW.js} +3 -3
- package/dist/{setup-config-RDVRYJLA.js → setup-config-GMMASPIP.js} +3 -3
- package/dist/{setup-custom-api-65DC33O2.js → setup-custom-api-5DUXUYZV.js} +4 -4
- package/dist/setup-data-dir-RPDT6UGI.js +34 -0
- package/dist/{tool-memory-WVKKXZ4E.js → tool-memory-EPQZ2ZY7.js} +5 -5
- package/dist/{unified-registry-6YJ2LONB.js → unified-registry-I76W6WEZ.js} +11 -10
- package/dist/{weather-report-GL3FCWG4.js → weather-report-G4EUXYN4.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-7VZXPXC4.js.map +0 -1
- package/dist/chunk-ALX7T72L.js.map +0 -1
- package/dist/chunk-KEN3STUW.js.map +0 -1
- package/dist/chunk-LHI66BKG.js.map +0 -1
- package/dist/chunk-V7VGNFAN.js.map +0 -1
- package/dist/issue-triage-KEE4DN4M.js +0 -16
- package/dist/setup-data-dir-O7LK4JUO.js +0 -33
- /package/dist/{ast-rule-runner-H2VFAOT4.js.map → ast-rule-runner-XJLYSAGE.js.map} +0 -0
- /package/dist/{child-mcp-config-Y3DPCM6L.js.map → child-mcp-config-U6SFHNXN.js.map} +0 -0
- /package/dist/{chunk-W7HVGLPS.js.map → chunk-24XTED4P.js.map} +0 -0
- /package/dist/{chunk-BGATTU3Z.js.map → chunk-3IZPJAIC.js.map} +0 -0
- /package/dist/{chunk-SIPFKN6U.js.map → chunk-5LG5RMTM.js.map} +0 -0
- /package/dist/{chunk-E5QULKGJ.js.map → chunk-BNRWICG7.js.map} +0 -0
- /package/dist/{chunk-WWBB6HUI.js.map → chunk-FKN4CJDF.js.map} +0 -0
- /package/dist/{chunk-QYWR7LJP.js.map → chunk-G47BD5WL.js.map} +0 -0
- /package/dist/{chunk-MUMQRZM5.js.map → chunk-HCPESANB.js.map} +0 -0
- /package/dist/{chunk-L6RAO6KC.js.map → chunk-HDERP5V6.js.map} +0 -0
- /package/dist/{chunk-XKJYFHPO.js.map → chunk-ISKYBNLW.js.map} +0 -0
- /package/dist/{chunk-NZNPMI3W.js.map → chunk-K3QNYYJZ.js.map} +0 -0
- /package/dist/{chunk-ONMUMFUN.js.map → chunk-K3XIXAWE.js.map} +0 -0
- /package/dist/{chunk-X7BYCDQN.js.map → chunk-KGLMAIY3.js.map} +0 -0
- /package/dist/{chunk-3H62U2MH.js.map → chunk-KH3QDRPJ.js.map} +0 -0
- /package/dist/{chunk-KDNWXGUF.js.map → chunk-KIKYLN2U.js.map} +0 -0
- /package/dist/{chunk-46CXXIQ4.js.map → chunk-KKGN23Z5.js.map} +0 -0
- /package/dist/{chunk-WVVJWPZT.js.map → chunk-LJJHGXLZ.js.map} +0 -0
- /package/dist/{chunk-DIPNNIVK.js.map → chunk-LSSX77DS.js.map} +0 -0
- /package/dist/{chunk-RL2O37NE.js.map → chunk-NAQDGUNA.js.map} +0 -0
- /package/dist/{chunk-NFBKSKEE.js.map → chunk-PTB4NERU.js.map} +0 -0
- /package/dist/{chunk-KUT76BHZ.js.map → chunk-PV7WSTTS.js.map} +0 -0
- /package/dist/{chunk-4WIJ2LKW.js.map → chunk-Q3JF6G7N.js.map} +0 -0
- /package/dist/{chunk-QSXDLYV4.js.map → chunk-QDELEGK7.js.map} +0 -0
- /package/dist/{chunk-W76A3RPF.js.map → chunk-S6PDNDLL.js.map} +0 -0
- /package/dist/{chunk-6NROQXOM.js.map → chunk-SGRWJW57.js.map} +0 -0
- /package/dist/{chunk-MPQDZVC6.js.map → chunk-W7IFJFYX.js.map} +0 -0
- /package/dist/{chunk-5EFWZHUV.js.map → chunk-XEXQG3VV.js.map} +0 -0
- /package/dist/{chunk-TQ6OKB3G.js.map → chunk-YOEWP7LI.js.map} +0 -0
- /package/dist/{cli-circuit-breaker-LYB4F3VP.js.map → cli-circuit-breaker-XWXGC4LJ.js.map} +0 -0
- /package/dist/{composite-router-OLXAFCJE.js.map → composite-router-ZY5ZYCJ6.js.map} +0 -0
- /package/dist/{consensus-vote-SWMMGIJU.js.map → consensus-vote-QYKZ4Y73.js.map} +0 -0
- /package/dist/{context-retriever-5C5MS2ZF.js.map → context-retriever-EXBO3PJ3.js.map} +0 -0
- /package/dist/{doctor-deep-YLOG5CAD.js.map → doctor-deep-TB36AVUC.js.map} +0 -0
- /package/dist/{doctor-gateway-report-JNOMZGSQ.js.map → doctor-gateway-report-3IOPQ5ZY.js.map} +0 -0
- /package/dist/{doctor-live-SRNNC37A.js.map → doctor-live-VK7XA7SX.js.map} +0 -0
- /package/dist/{expert-bridge-H4EOOXWB.js.map → expert-bridge-NOHPIEDY.js.map} +0 -0
- /package/dist/{factory-FHJ42ORZ.js.map → factory-2QMQC7MF.js.map} +0 -0
- /package/dist/{factory-VOICDXGX.js.map → factory-NINQ76ZS.js.map} +0 -0
- /package/dist/{improvement-review-OW2MEP4O.js.map → improvement-review-JAX2WDGT.js.map} +0 -0
- /package/dist/{init-opencode-ZO7MEDSW.js.map → init-opencode-TYXXLQCC.js.map} +0 -0
- /package/dist/{issue-triage-KEE4DN4M.js.map → issue-triage-NTSZQ6M5.js.map} +0 -0
- /package/dist/{openai-compat-adapter-WKXMQE62.js.map → openai-compat-adapter-KDVYYW3X.js.map} +0 -0
- /package/dist/{pr-reviewer-helpers-UMNXRN2R.js.map → pr-reviewer-helpers-R3IC24OM.js.map} +0 -0
- /package/dist/{registry-command-A4SZT4UX.js.map → registry-command-S6F5AL2O.js.map} +0 -0
- /package/dist/{repo-security-plan-XF5N6D6R.js.map → repo-security-plan-4ISGRT2F.js.map} +0 -0
- /package/dist/{research-helpers-synthesize-SKK7U6KA.js.map → research-helpers-synthesize-HYDSM5TV.js.map} +0 -0
- /package/dist/{routing-memory-64AEPNLI.js.map → routing-memory-VR36BYAN.js.map} +0 -0
- /package/dist/{session-memory-EWRSQOIF.js.map → session-memory-4SOE5DXW.js.map} +0 -0
- /package/dist/{setup-config-RDVRYJLA.js.map → setup-config-GMMASPIP.js.map} +0 -0
- /package/dist/{setup-custom-api-65DC33O2.js.map → setup-custom-api-5DUXUYZV.js.map} +0 -0
- /package/dist/{setup-data-dir-O7LK4JUO.js.map → setup-data-dir-RPDT6UGI.js.map} +0 -0
- /package/dist/{tool-memory-WVKKXZ4E.js.map → tool-memory-EPQZ2ZY7.js.map} +0 -0
- /package/dist/{unified-registry-6YJ2LONB.js.map → unified-registry-I76W6WEZ.js.map} +0 -0
- /package/dist/{weather-report-GL3FCWG4.js.map → weather-report-G4EUXYN4.js.map} +0 -0
|
@@ -9,8 +9,8 @@ import {
|
|
|
9
9
|
getBuiltInAstRulesPath,
|
|
10
10
|
loadRules,
|
|
11
11
|
runAstQaRules
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import "./chunk-
|
|
12
|
+
} from "./chunk-XEXQG3VV.js";
|
|
13
|
+
import "./chunk-KGLMAIY3.js";
|
|
14
14
|
import "./chunk-UE7A2XHM.js";
|
|
15
15
|
import "./chunk-LWOX65CP.js";
|
|
16
16
|
import "./chunk-PX6F3LHL.js";
|
|
@@ -26,4 +26,4 @@ export {
|
|
|
26
26
|
loadRules,
|
|
27
27
|
runAstQaRules
|
|
28
28
|
};
|
|
29
|
-
//# sourceMappingURL=ast-rule-runner-
|
|
29
|
+
//# sourceMappingURL=ast-rule-runner-XJLYSAGE.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-OITVVSWO.js";
|
|
4
4
|
import {
|
|
5
5
|
createLogger
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-KGLMAIY3.js";
|
|
7
7
|
import "./chunk-UE7A2XHM.js";
|
|
8
8
|
import "./chunk-LWOX65CP.js";
|
|
9
9
|
import "./chunk-PX6F3LHL.js";
|
|
@@ -56,4 +56,4 @@ async function generateMcpConfig(options) {
|
|
|
56
56
|
export {
|
|
57
57
|
generateMcpConfig
|
|
58
58
|
};
|
|
59
|
-
//# sourceMappingURL=child-mcp-config-
|
|
59
|
+
//# sourceMappingURL=child-mcp-config-U6SFHNXN.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
CACHE_TIMEOUTS,
|
|
3
3
|
createLogger,
|
|
4
4
|
getTimeProvider
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-KGLMAIY3.js";
|
|
6
6
|
|
|
7
7
|
// src/security/trust-types.ts
|
|
8
8
|
import { z } from "zod";
|
|
@@ -610,4 +610,4 @@ export {
|
|
|
610
610
|
resolveReputationGatingMode,
|
|
611
611
|
gateWithReputation
|
|
612
612
|
};
|
|
613
|
-
//# sourceMappingURL=chunk-
|
|
613
|
+
//# sourceMappingURL=chunk-24XTED4P.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-W654ME6B.js";
|
|
4
4
|
import {
|
|
5
5
|
resolveToken
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-S6PDNDLL.js";
|
|
7
7
|
import {
|
|
8
8
|
REGISTRY_PATH,
|
|
9
9
|
getProjectRoot,
|
|
@@ -11,10 +11,10 @@ import {
|
|
|
11
11
|
loadTechniquesRegistry,
|
|
12
12
|
resolveInsideRoot,
|
|
13
13
|
savePapersRegistry
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-5LG5RMTM.js";
|
|
15
15
|
import {
|
|
16
16
|
getToolMemory
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-KKGN23Z5.js";
|
|
18
18
|
import {
|
|
19
19
|
capitalizeWords,
|
|
20
20
|
tokenizeFiltered,
|
|
@@ -43,7 +43,7 @@ import {
|
|
|
43
43
|
ok,
|
|
44
44
|
registerPersistentDistillerFactory,
|
|
45
45
|
sigmoidConfidence
|
|
46
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-KGLMAIY3.js";
|
|
47
47
|
import {
|
|
48
48
|
ensureLearningDir,
|
|
49
49
|
getRulesFile
|
|
@@ -4275,4 +4275,4 @@ export {
|
|
|
4275
4275
|
DEFAULT_CONTEXT_BUDGET_TOKENS,
|
|
4276
4276
|
getContextPromptPrefix
|
|
4277
4277
|
};
|
|
4278
|
-
//# sourceMappingURL=chunk-
|
|
4278
|
+
//# sourceMappingURL=chunk-3IZPJAIC.js.map
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
err,
|
|
6
6
|
getErrorMessage,
|
|
7
7
|
ok
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-KGLMAIY3.js";
|
|
9
9
|
import {
|
|
10
10
|
findRepoRoot,
|
|
11
11
|
getActiveWorkspaceRoot,
|
|
@@ -290,4 +290,4 @@ export {
|
|
|
290
290
|
loadPapersRegistry,
|
|
291
291
|
savePapersRegistry
|
|
292
292
|
};
|
|
293
|
-
//# sourceMappingURL=chunk-
|
|
293
|
+
//# sourceMappingURL=chunk-5LG5RMTM.js.map
|
|
@@ -7,12 +7,12 @@ import {
|
|
|
7
7
|
readGatewayTransport,
|
|
8
8
|
requireApiKey,
|
|
9
9
|
validateApiKeyPresence
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ZG6UJP6U.js";
|
|
11
11
|
import {
|
|
12
12
|
assertCustomApiHostResolvesPublic,
|
|
13
13
|
hostnameOf,
|
|
14
14
|
redactApiKey
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-K3QNYYJZ.js";
|
|
16
16
|
import {
|
|
17
17
|
sanitizeErrorDetails
|
|
18
18
|
} from "./chunk-2NDA4DHW.js";
|
|
@@ -40,19 +40,39 @@ import {
|
|
|
40
40
|
readModelAllowlist,
|
|
41
41
|
recordUsageEvent,
|
|
42
42
|
refineGatewayCatalog
|
|
43
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-KGLMAIY3.js";
|
|
44
44
|
|
|
45
45
|
// src/adapters/openai-compat-adapter.ts
|
|
46
46
|
import OpenAI2 from "openai";
|
|
47
47
|
|
|
48
48
|
// src/adapters/gateway-host-status.ts
|
|
49
|
+
var GATEWAY_HOST_LOOKUP_TIMED_OUT = "gateway host check timed out; the gateway is not wired this attempt, will retry";
|
|
49
50
|
var REMEDY = `Set ${CUSTOM_API_ALLOW_PRIVATE_ENV}=1 if the gateway runs on a trusted internal host, then restart the server.`;
|
|
50
|
-
async function checkGatewayHost(baseUrl) {
|
|
51
|
+
async function checkGatewayHost(baseUrl, options = {}) {
|
|
51
52
|
const host = hostnameOf(baseUrl);
|
|
52
|
-
const guard = await
|
|
53
|
+
const guard = await withLookupTimeout(
|
|
54
|
+
assertCustomApiHostResolvesPublic(host),
|
|
55
|
+
options.lookupTimeoutMs ?? GATEWAY_HOST_LOOKUP_TIMEOUT_MS
|
|
56
|
+
);
|
|
57
|
+
if (guard === "timed_out") return { state: "lookup_timed_out", host };
|
|
53
58
|
if (guard.ok) return { state: "allowed", host };
|
|
54
59
|
return { state: "refused_private_host", host, reason: guard.error.message, remedy: REMEDY };
|
|
55
60
|
}
|
|
61
|
+
var GATEWAY_HOST_LOOKUP_TIMEOUT_MS = 5e3;
|
|
62
|
+
async function withLookupTimeout(work, ms) {
|
|
63
|
+
let timer;
|
|
64
|
+
const timeout = new Promise((resolve) => {
|
|
65
|
+
timer = setTimeout(() => {
|
|
66
|
+
resolve("timed_out");
|
|
67
|
+
}, ms);
|
|
68
|
+
timer.unref();
|
|
69
|
+
});
|
|
70
|
+
try {
|
|
71
|
+
return await Promise.race([work, timeout]);
|
|
72
|
+
} finally {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
56
76
|
var GatewayHostRefusedError = class extends ConfigError {
|
|
57
77
|
status;
|
|
58
78
|
constructor(status) {
|
|
@@ -874,6 +894,9 @@ async function discoverGatewayCatalog(config, logger) {
|
|
|
874
894
|
if (hostCheck.state === "refused_private_host") {
|
|
875
895
|
return err(new GatewayHostRefusedError(hostCheck));
|
|
876
896
|
}
|
|
897
|
+
if (hostCheck.state === "lookup_timed_out") {
|
|
898
|
+
return err(new ConfigError(`${GATEWAY_HOST_LOOKUP_TIMED_OUT} (host ${hostCheck.host})`));
|
|
899
|
+
}
|
|
877
900
|
try {
|
|
878
901
|
const client = new OpenAI2({
|
|
879
902
|
baseURL: config.baseUrl,
|
|
@@ -1003,6 +1026,7 @@ export {
|
|
|
1003
1026
|
OPENAI_MODEL_ALIASES,
|
|
1004
1027
|
OpenAIAdapter,
|
|
1005
1028
|
createOpenAIAdapter,
|
|
1029
|
+
GATEWAY_HOST_LOOKUP_TIMED_OUT,
|
|
1006
1030
|
checkGatewayHost,
|
|
1007
1031
|
GatewayHostRefusedError,
|
|
1008
1032
|
readOpencodeGateway,
|
|
@@ -1014,4 +1038,4 @@ export {
|
|
|
1014
1038
|
createOpenAICompatAdapter,
|
|
1015
1039
|
buildOpenAICompatAdapters
|
|
1016
1040
|
};
|
|
1017
|
-
//# sourceMappingURL=chunk-
|
|
1041
|
+
//# sourceMappingURL=chunk-6PB7JUNT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/openai-compat-adapter.ts","../src/adapters/gateway-host-status.ts","../src/adapters/openai-adapter.ts","../src/adapters/openai-types.ts","../src/adapters/openai-mappers.ts","../src/config/opencode-bridge.ts"],"sourcesContent":["/**\n * OpenAI-compatible gateway adapter — talk to any HTTP gateway that exposes\n * the OpenAI Chat Completions API. The gateway may itself be a multi-model\n * router (Bedrock/Vertex/Azure proxy, OpenRouter, vLLM, etc.). nexus-agents\n * sees one adapter, the gateway exposes N models, and the existing routing\n * pipeline picks among them.\n *\n * Source: Issue #2468 (epic #2467 child).\n *\n * Configuration precedence (#2503, child 3 of epic #2500):\n * 1. NEXUS_OPENAI_COMPAT_URL + NEXUS_OPENAI_COMPAT_KEY env vars (both required)\n * 2. NEXUS_OPENCODE_CONFIG path → opencode.json → providers.openai-compat\n * 3. Unconfigured → adapter not built\n *\n * Models are discovered via GET {base}/models at first use, where {base} is\n * NEXUS_OPENAI_COMPAT_URL and already ends in `/v1` (the SDK appends only\n * `/models`, so a base without `/v1` probes the wrong path). Each model\n * the gateway exposes can be selected by ID; the adapter wraps the existing\n * `OpenAIAdapter` for the actual chat-completions request, so streaming +\n * tool use + the full IModelAdapter contract come for free.\n */\n\nimport OpenAI from 'openai';\nimport {\n checkGatewayHost,\n GATEWAY_HOST_LOOKUP_TIMED_OUT,\n GatewayHostRefusedError,\n} from './gateway-host-status.js';\n\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n ILogger,\n ModelError,\n ModelMetadata,\n IModelAdapter,\n} from '../core/index.js';\nimport {\n ok,\n err,\n ConfigError,\n createLogger,\n getErrorMessage,\n getTimeProvider,\n} from '../core/index.js';\nimport { OpenAIAdapter } from './openai-adapter.js';\nimport { recordUsageEvent } from '../learning/usage-log.js';\nimport { gatewayCostDetail } from '../cli-adapters/budget-arm-cost.js';\nimport { readOpencodeGateway } from '../config/opencode-bridge.js';\nimport { isEndpointArmId, type EndpointArmId } from '../cli-adapters/types-core.js';\nimport { gatewayEndpointRejection } from './sdk/gateway-cost.js';\nimport {\n DEFAULT_OPENAI_COMPAT_ENDPOINT,\n OPENAI_COMPAT_ENDPOINT_ENV,\n OPENAI_COMPAT_KEY_ENV,\n OPENAI_COMPAT_MODELS_ENV,\n OPENAI_COMPAT_URL_ENV,\n} from './sdk/types.js';\nimport { hostnameOf, redactApiKey } from './sdk/gateway-env.js';\nimport { readModelAllowlist, refineGatewayCatalog } from './gateway-catalog-filter.js';\nimport {\n gatewayClientOptions,\n readGatewayTransport,\n type GatewayTransport,\n} from './gateway-http.js';\n\nexport interface OpenAICompatConfig extends GatewayTransport {\n /** Gateway base URL — ends in `/v1`; the SDK appends `/models` and `/chat/completions`. */\n readonly baseUrl: string;\n /** API key the gateway expects. */\n readonly apiKey: string;\n /**\n * Endpoint identity the gateway registers as — the `<endpoint>` of its\n * `api:<endpoint>` arm (#4392 increment 2, step 2). Always set by\n * {@link readOpenAICompatEnv}; optional on the type so a hand-built config\n * (tests, embedders) keeps working, with the default applying at\n * registration. Never the URL.\n */\n readonly endpoint?: string;\n /**\n * Model-id allowlist (`NEXUS_OPENAI_COMPAT_MODELS`, #6600), applied before\n * the adapter cap; `*` is a wildcard. Absent or empty means no allowlist.\n */\n readonly modelAllowlist?: readonly string[];\n}\n\n/**\n * A per-model gateway adapter, marked with the `api:<endpoint>` arm it\n * registers under (#4392 increment 2, step 4). The telemetry writers key on\n * this — the usage log here, the vote rollup in `decision-cost-recording` —\n * to price a call by the arm's `NEXUS_GATEWAY_COST` declaration instead of\n * by the model id alone. `providerId` stays `'openai'` on purpose:\n * `inFamilyFallback` and `authRemediation` take their inputs from it.\n * Reached through {@link isGatewayModelAdapter} (narrowing) and\n * {@link createOpenAICompatAdapter} (construction); not exported by name\n * because nothing outside this module needs to spell it.\n */\ninterface GatewayModelAdapter extends IModelAdapter {\n readonly gatewayArm: EndpointArmId;\n /**\n * The `/models` `created` stamp (epoch seconds) discovery listed for this\n * model, when it listed one. Read by the family-slot ranking (#6604).\n */\n readonly created?: number;\n}\n\n/**\n * True iff `adapter` carries a valid gateway arm id. Checked by shape, not\n * by construction site: a hand-built config can name an endpoint that is not\n * an endpoint id, and a marker that fails the id rule is no marker.\n */\nexport function isGatewayModelAdapter(adapter: IModelAdapter): adapter is GatewayModelAdapter {\n const arm: unknown = (adapter as Partial<GatewayModelAdapter>).gatewayArm;\n return typeof arm === 'string' && isEndpointArmId(arm);\n}\n\nexport interface DiscoveredModel {\n readonly id: string;\n /** Unix epoch seconds when the model was created (per OpenAI API). */\n readonly created?: number;\n /** Owning organization or upstream provider name. */\n readonly ownedBy?: string;\n}\n\n/**\n * Read the gateway config with the precedence chain documented in the\n * module docstring: env vars > opencode.json > unconfigured.\n *\n * The env-var path (#2468) wins when both `NEXUS_OPENAI_COMPAT_URL` and\n * `NEXUS_OPENAI_COMPAT_KEY` are set. Otherwise, when `NEXUS_OPENCODE_CONFIG`\n * names a path, the opencode.json bridge tries to source the gateway from\n * `providers.openai-compat.options.{baseURL, apiKey}` (#2503). Returns\n * `null` when neither path yields a config — caller treats unset gateway\n * as \"no adapter from this source.\"\n */\nexport function readOpenAICompatEnv(): OpenAICompatConfig | null {\n const fromEnv = readGatewayFromEnv();\n if (fromEnv !== null) return fromEnv;\n return readGatewayFromOpencode();\n}\n\n/**\n * Reads the NEW names only. The deprecated `NEXUS_CUSTOM_API_*` pair is an\n * alias for the single-model `custom-openai` reader (`sdk/gateway-env.ts`)\n * and deliberately not for this one (#4392 increment 3, panel option C):\n * renaming is what opts an operator into discovery, in-process voters and\n * the `api:<endpoint>` arm, so the legacy pair alone must leave this null.\n */\nfunction readGatewayFromEnv(): OpenAICompatConfig | null {\n const envUrl = process.env[OPENAI_COMPAT_URL_ENV]?.trim();\n const envKey = process.env[OPENAI_COMPAT_KEY_ENV]?.trim();\n if (envUrl === undefined || envUrl === '') return null;\n if (envKey === undefined || envKey === '') return null;\n return {\n baseUrl: envUrl,\n apiKey: envKey,\n endpoint: readOpenAICompatEndpoint(),\n modelAllowlist: readModelAllowlist(),\n ...readGatewayTransport(envUrl, process.env, endpointLogger),\n };\n}\n\nfunction readGatewayFromOpencode(): OpenAICompatConfig | null {\n const opencodePath = process.env['NEXUS_OPENCODE_CONFIG']?.trim();\n if (opencodePath === undefined || opencodePath === '') return null;\n const fromFile = readOpencodeGateway(opencodePath);\n if (fromFile === null) return null;\n return {\n baseUrl: fromFile.baseURL,\n apiKey: fromFile.apiKey,\n endpoint: readOpenAICompatEndpoint(),\n modelAllowlist: readModelAllowlist(),\n ...readGatewayTransport(fromFile.baseURL, process.env, endpointLogger),\n };\n}\n\nconst endpointLogger = createLogger({ component: 'openai-compat-adapter' });\n\n/**\n * The gateway's endpoint identity (#4392 increment 2, step 2):\n * `NEXUS_OPENAI_COMPAT_ENDPOINT` when `api:<value>` is a GATEWAY arm id, else\n * {@link DEFAULT_OPENAI_COMPAT_ENDPOINT}. The fallback is deliberate: the env\n * schema reports an invalid value at startup, and this reader must never turn\n * a pasted URL — or a credential inside one — into an arm id, telemetry key\n * or display string, nor register the gateway as a VENDOR arm (`api:openai`),\n * where its cost declaration is unreachable (#6409). The same rule decides\n * both (`gatewayEndpointRejection`), and the fallback is warned with the\n * reason, never the value. Both config paths (env, opencode.json) share it.\n */\nexport function readOpenAICompatEndpoint(\n env: NodeJS.ProcessEnv = process.env,\n logger: ILogger = endpointLogger\n): string {\n const raw = env[OPENAI_COMPAT_ENDPOINT_ENV]?.trim();\n if (raw === undefined || raw === '') return DEFAULT_OPENAI_COMPAT_ENDPOINT;\n const reason = gatewayEndpointRejection(raw);\n if (reason === undefined) return raw;\n logger.warn(\n `${OPENAI_COMPAT_ENDPOINT_ENV} ignored (${reason}); the gateway registers as api:${DEFAULT_OPENAI_COMPAT_ENDPOINT}`,\n { env: OPENAI_COMPAT_ENDPOINT_ENV, reason, value: '<redacted>' }\n );\n return DEFAULT_OPENAI_COMPAT_ENDPOINT;\n}\n\n/**\n * Ceiling on how many models one gateway may contribute.\n *\n * `buildOpenAICompatAdapters` constructs one adapter per discovered model, so an\n * unbounded list becomes unbounded objects during bootstrap. Aggregators\n * legitimately serve hundreds — models.dev lists 339 for one and 620 for\n * another — so this is a sanity ceiling on adapter construction, not a claim\n * about what a gateway may offer. It is checked AFTER deduplication, the\n * non-chat filter and the operator allowlist (#6600), so a large catalogue is\n * served by allowlisting the models wanted rather than refused.\n */\nconst MAX_DISCOVERED_MODELS = 256;\n\n/** Bound on the discovery call. Bootstrap must not hang on a dead gateway. */\nconst MODEL_DISCOVERY_TIMEOUT_MS = 10_000;\n\n/**\n * Shape of a model id this adapter will dispatch to (#4392 increment 2, step\n * 2). A discovered id becomes a request field, a usage-log key and — through\n * the gateway catalogue — a pricing key, so whitespace and control characters\n * are refused; `/`, `:`, `.` and `_` are kept because aggregators use them\n * (`org/model:tag`). Length is capped at 128.\n */\nconst MODEL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;\n\n/**\n * Keep the ids that satisfy {@link MODEL_ID_PATTERN}. Warns with the dropped\n * COUNT only — an offending id is exactly the string that must not reach a\n * log line, and the count is what tells an operator the gateway's listing\n * needs a look.\n */\nfunction keepValidModelIds<T extends { readonly id: string }>(\n models: readonly T[],\n logger: ILogger | undefined\n): readonly T[] {\n const kept = models.filter((m) => MODEL_ID_PATTERN.test(m.id));\n const dropped = models.length - kept.length;\n if (dropped > 0) {\n logger?.warn(\n `Dropped ${String(dropped)} gateway model id(s) that are not a valid model id shape (whitespace, control characters, or over 128 chars)`,\n { dropped, kept: kept.length }\n );\n }\n return kept;\n}\n\n/**\n * Discover available models by calling `GET {baseUrl}/models` ({baseUrl} ends\n * in `/v1`). Uses the\n * official `openai` SDK's `client.models.list()` so we benefit from its\n * pagination + retry handling. The list is the strongly authoritative\n * source: nexus-agents won't try to dispatch to a model the gateway doesn't\n * expose.\n */\nexport async function discoverModels(\n config: OpenAICompatConfig,\n logger?: ILogger\n): Promise<Result<readonly DiscoveredModel[], ConfigError>> {\n const catalog = await discoverGatewayCatalog(config, logger);\n return catalog.ok ? ok(catalog.value.models) : catalog;\n}\n\n/**\n * {@link discoverModels} plus the raw listing size (#6609), so `doctor\n * --gateway` can report the count before and after the chat filter from the\n * same call the server makes. `listedCount` is the rows `GET /models`\n * returned, before deduplication, the chat filter and the allowlist; `models`\n * is what {@link discoverModels} returns.\n */\nexport async function discoverGatewayCatalog(\n config: OpenAICompatConfig,\n logger?: ILogger\n): Promise<\n Result<{ readonly listedCount: number; readonly models: readonly DiscoveredModel[] }, ConfigError>\n> {\n // Reuse the SDK path's DNS-resolve-time SSRF guard (#3426) rather than\n // growing a second one. This path needs it at least as much: it can read its\n // base URL from a FILE (`NEXUS_OPENCODE_CONFIG` -> opencode.json), not only\n // from an env var, so the input is not always direct operator intent.\n // The guard fails OPEN on transient resolver errors and rejects only a\n // confirmed private/loopback/link-local resolution.\n // #6608: the refusal is a typed error so the bootstrap can say which\n // variable allows it and that the gateway is not in use.\n const hostCheck = await checkGatewayHost(config.baseUrl);\n if (hostCheck.state === 'refused_private_host') {\n return err(new GatewayHostRefusedError(hostCheck));\n }\n if (hostCheck.state === 'lookup_timed_out') {\n // Fail closed for this attempt (#6671 review): a plain ConfigError, so the\n // bootstrap treats it as retryable and lazy re-discovery tries again.\n return err(new ConfigError(`${GATEWAY_HOST_LOOKUP_TIMED_OUT} (host ${hostCheck.host})`));\n }\n try {\n const client = new OpenAI({\n baseURL: config.baseUrl,\n apiKey: config.apiKey,\n // Discovery runs during server bootstrap, so an unresponsive gateway must\n // not stall startup indefinitely. The SDK's own default is far longer.\n timeout: MODEL_DISCOVERY_TIMEOUT_MS,\n maxRetries: 1,\n // Auth header, extra headers and proxy (#6608) — the same options every\n // per-model adapter gets, so discovery cannot pass where completions fail.\n ...gatewayClientOptions(config),\n });\n const list = await client.models.list();\n // `listing` is the raw row: gateways add fields beyond the SDK's `Model`\n // type (`type`, `mode`, `architecture`) that say whether it can chat.\n const listed = list.data.map((m) => ({ id: m.id, listing: m, model: m }));\n const allowlist = config.modelAllowlist ?? [];\n const refined = refineGatewayCatalog(keepValidModelIds(listed, logger), allowlist, logger);\n if (refined.length > MAX_DISCOVERED_MODELS) {\n return err(overCapError(config, list.data.length, refined.length, allowlist.length > 0));\n }\n return ok({\n listedCount: list.data.length,\n models: refined.map(({ model: m }) => ({\n id: m.id,\n created: m.created,\n ownedBy: m.owned_by,\n })),\n });\n } catch (e: unknown) {\n // This message lands on cli-server-gateway's probe-failed warn line, so it\n // names the host (a base URL can carry userinfo) and never the key: a\n // gateway's 401 body may echo the bearer it rejected (#4392 increment 3).\n return err(\n new ConfigError(\n `Failed to discover models from ${hostnameOf(config.baseUrl)}: ` +\n `${redactApiKey(getErrorMessage(e), config.apiKey)}. ` +\n `Verify ${OPENAI_COMPAT_URL_ENV} and ${OPENAI_COMPAT_KEY_ENV}, then retry.`\n )\n );\n }\n}\n\n/**\n * The refusal for a catalogue still above the cap after refinement. It names\n * the allowlist variable, which is the operator's way through (#6600).\n */\nfunction overCapError(\n config: OpenAICompatConfig,\n listed: number,\n refined: number,\n allowlisted: boolean\n): ConfigError {\n const cap = String(MAX_DISCOVERED_MODELS);\n const host = hostnameOf(config.baseUrl);\n const detail = allowlisted\n ? `${OPENAI_COMPAT_MODELS_ENV} matched ${String(refined)} of its ${String(listed)} listed models`\n : `it listed ${String(listed)} models (${String(refined)} chat models)`;\n return new ConfigError(\n `Gateway ${host}: ${detail}, above the ${cap} cap. Refusing to build an adapter per model. ` +\n `Set ${OPENAI_COMPAT_MODELS_ENV} to a comma-separated allowlist of model ids ` +\n `(\\`*\\` is a wildcard) naming at most ${cap} models.`\n );\n}\n\n/**\n * Create an OpenAIAdapter pointed at the gateway for a specific model ID,\n * wrapped with usage recording so every completion appends a UsageEvent\n * to the JSONL log consumed by `nexus-agents usage`.\n *\n * The wrapper is transparent — same IModelAdapter contract, same fields,\n * same error handling — plus the {@link GatewayModelAdapter} arm marker,\n * `api:<config.endpoint>` (the default endpoint when a hand-built config\n * omits it, matching registration). Recording is best-effort (telemetry\n * never fails the user's call).\n *\n * When invoked via MCP, the host harness's model identifier is passed\n * through verbatim — nexus-agents doesn't second-guess what the host is\n * already routing.\n */\nexport function createOpenAICompatAdapter(\n modelId: string,\n config: OpenAICompatConfig,\n created?: number\n): GatewayModelAdapter {\n // Verbatim: the id goes to the gateway exactly as it listed it. The direct\n // adapter's alias table (`gpt-4o` -> a dated snapshot) names models the\n // gateway may not serve, and would make `NEXUS_VOTER_MODEL_*` pins miss\n // (#6605).\n const inner = new OpenAIAdapter({\n modelId,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n verbatimModelId: true,\n ...gatewayClientOptions(config),\n });\n const wrapped = withUsageRecording(\n inner,\n `api:${config.endpoint ?? DEFAULT_OPENAI_COMPAT_ENDPOINT}`\n );\n return created === undefined ? wrapped : Object.assign(wrapped, { created });\n}\n\n/**\n * Wrap a gateway model adapter so that successful + failed `complete()`\n * calls append a UsageEvent to the on-disk usage log. Stream calls aren't\n * yet instrumented (a future PR can add streaming-aware recording).\n *\n * The returned object preserves the IModelAdapter contract identically;\n * downstream code can't tell the difference except that one extra JSONL\n * line gets written per call. The line is priced by `gatewayArm`'s\n * `NEXUS_GATEWAY_COST` declaration ({@link gatewayCostDetail}, #4392 step 4):\n * an undeclared gateway records `priced: false`, never the model id's vendor\n * list price.\n */\nfunction withUsageRecording(inner: IModelAdapter, gatewayArm: EndpointArmId): GatewayModelAdapter {\n const wrapped: GatewayModelAdapter = {\n gatewayArm,\n providerId: inner.providerId,\n modelId: inner.modelId,\n capabilities: inner.capabilities,\n countTokens: (text) => inner.countTokens(text),\n validateConfig: () => inner.validateConfig(),\n stream: (request) => inner.stream(request),\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n const start = getTimeProvider().now();\n const result = await inner.complete(request);\n const latencyMs = getTimeProvider().now() - start;\n try {\n if (result.ok) {\n const u = result.value.usage;\n // No vendor usage ⇒ nothing to record. Zero-filling here would write\n // a fabricated measurement into the usage log, which is the defect\n // #4439 exists to remove — a lost latency datapoint is the cheaper\n // loss than a false token count.\n if (u === undefined) return result;\n // Declaration-first pricing with provenance (#4165, #4392 step 4):\n // `priced: false` marks the $0 as UNPRICED (unmeasured), not a real $0.\n const cost = gatewayCostDetail(gatewayArm, inner.modelId, u.inputTokens, u.outputTokens);\n recordUsageEvent({\n timestamp: new Date().toISOString(),\n modelId: inner.modelId,\n providerId: inner.providerId,\n inputTokens: u.inputTokens,\n outputTokens: u.outputTokens,\n usdCost: cost.costUsd,\n latencyMs,\n success: true,\n priced: cost.priced,\n ...(cost.priced ? { priceSource: cost.resolvedId } : {}),\n });\n } else {\n recordFailedCall(inner, latencyMs, result.error.code);\n }\n } catch {\n // Telemetry must not break user calls.\n }\n return result;\n },\n };\n attachListModels(wrapped, inner);\n return wrapped;\n}\n\n/** The usage line for a failed call: no tokens, no cost — the error code is the datum. */\nfunction recordFailedCall(inner: IModelAdapter, latencyMs: number, errorCode: string): void {\n recordUsageEvent({\n timestamp: new Date().toISOString(),\n modelId: inner.modelId,\n providerId: inner.providerId,\n inputTokens: 0,\n outputTokens: 0,\n usdCost: 0,\n latencyMs,\n success: false,\n errorCode,\n });\n}\n\n/**\n * (#2540) Forward `listModels` through the wrapper when the inner adapter\n * exposes one. Only attach when defined so the wrapper's `listModels?:`\n * hint stays accurate for the resolver. The inner reference is captured\n * by closure so the forwarded call binds `this` to the inner adapter.\n */\nfunction attachListModels(wrapped: IModelAdapter, inner: IModelAdapter): void {\n const list = inner.listModels?.bind(inner);\n if (list === undefined) return;\n wrapped.listModels = (): Promise<readonly ModelMetadata[]> => list();\n}\n\n/**\n * Convenience: read env, discover, return adapter instances for every\n * discovered model. Returns `null` (not an error) when env vars aren't set\n * — the caller treats unset gateway as \"no adapter from this source.\"\n *\n * Use case: the unified registry / factory calls this at startup; if the\n * operator has configured a gateway, every discovered model becomes a\n * dispatch target alongside the existing claude/codex/gemini/opencode\n * adapter slots.\n */\nexport async function buildOpenAICompatAdapters(\n logger?: ILogger\n): Promise<Result<readonly IModelAdapter[], ConfigError> | null> {\n const config = readOpenAICompatEnv();\n if (config === null) return null;\n const discovered = await discoverModels(config, logger);\n if (!discovered.ok) return discovered;\n return ok(discovered.value.map((m) => createOpenAICompatAdapter(m.id, config, m.created)));\n}\n","/**\n * Whether the private-address guard lets the gateway's host through (#6608\n * item 3), as a value a report surface can read.\n *\n * A corporate gateway commonly resolves to a 10.x address, which the SSRF\n * guard refuses unless `NEXUS_CUSTOM_API_ALLOW_PRIVATE=1`. Outside a sandbox\n * that used to surface as a generic \"probe failed\" warn line while the server\n * quietly fell back to CLI subprocesses. {@link checkGatewayHost} is the one\n * place the refusal and its remedy are phrased; discovery refuses with\n * {@link GatewayHostRefusedError}, the bootstrap reports it by name, and\n * `doctor` can call {@link checkGatewayHost} directly (#6609).\n *\n * @module adapters/gateway-host-status\n */\n\nimport { ConfigError } from '../core/index.js';\nimport { assertCustomApiHostResolvesPublic } from './sdk/custom-api-validation.js';\nimport { hostnameOf } from './sdk/gateway-env.js';\nimport { CUSTOM_API_ALLOW_PRIVATE_ENV } from './sdk/types.js';\n\n/** The guard refused the host: the gateway is not used. */\nexport interface GatewayHostRefused {\n readonly state: 'refused_private_host';\n readonly host: string;\n /** The guard's classification (private, loopback, link-local, …). */\n readonly reason: string;\n /** What the operator sets to allow it; names the variable. */\n readonly remedy: string;\n}\n\nexport type GatewayHostStatus =\n | { readonly state: 'allowed'; readonly host: string }\n | GatewayHostRefused\n /**\n * The guard's lookup did not answer in time. Unlike a DNS error (the\n * connection could not resolve either), the connection's own lookup may\n * still answer, with a private address, so the host is NOT allowed. Not a\n * refusal: the next attempt runs the guard again.\n */\n | { readonly state: 'lookup_timed_out'; readonly host: string };\n\n/** The message discovery fails with on `lookup_timed_out`; lazy re-discovery retries it. */\nexport const GATEWAY_HOST_LOOKUP_TIMED_OUT =\n 'gateway host check timed out; the gateway is not wired this attempt, will retry';\n\nconst REMEDY =\n `Set ${CUSTOM_API_ALLOW_PRIVATE_ENV}=1 if the gateway runs on a trusted internal host, ` +\n 'then restart the server.';\n\n/**\n * Run the private-address guard against `baseUrl`'s host. The guard fails\n * OPEN on a DNS error (a flaky resolver must not break a legitimate gateway),\n * so `allowed` means \"not refused\", not \"reachable\". It fails CLOSED on a\n * lookup that does not answer within the bound: `lookup_timed_out`.\n */\nexport async function checkGatewayHost(\n baseUrl: string,\n options: { readonly lookupTimeoutMs?: number } = {}\n): Promise<GatewayHostStatus> {\n const host = hostnameOf(baseUrl);\n const guard = await withLookupTimeout(\n assertCustomApiHostResolvesPublic(host),\n options.lookupTimeoutMs ?? GATEWAY_HOST_LOOKUP_TIMEOUT_MS\n );\n if (guard === 'timed_out') return { state: 'lookup_timed_out', host };\n if (guard.ok) return { state: 'allowed', host };\n return { state: 'refused_private_host', host, reason: guard.error.message, remedy: REMEDY };\n}\n\n/**\n * Upper bound on the guard's DNS lookup (#6671 review). `dns.lookup` has no\n * timeout of its own, and discovery (at boot and on lazy re-discovery) runs\n * the guard before its bounded HTTP request, so an unresponsive resolver\n * would otherwise hold discovery open indefinitely.\n */\nconst GATEWAY_HOST_LOOKUP_TIMEOUT_MS = 5_000;\n\nasync function withLookupTimeout<T>(work: Promise<T>, ms: number): Promise<T | 'timed_out'> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<'timed_out'>((resolve) => {\n timer = setTimeout(() => {\n resolve('timed_out');\n }, ms);\n timer.unref();\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Discovery's refusal when {@link checkGatewayHost} says `refused_private_host`. */\nexport class GatewayHostRefusedError extends ConfigError {\n readonly status: GatewayHostRefused;\n\n constructor(status: GatewayHostRefused) {\n super(`Gateway URL rejected: ${status.reason}`);\n this.name = 'GatewayHostRefusedError';\n this.status = status;\n }\n}\n","/**\n * nexus-agents/adapters - OpenAI Model Adapter\n *\n * Adapter for OpenAI models (GPT-4o, GPT-4-turbo, GPT-3.5-turbo).\n * Implements the IModelAdapter interface with streaming support, rate limiting,\n * and proper error handling.\n *\n * Verified 2026-01-03: openai@6.15.0 is current stable\n * (Source: npm registry)\n */\n\nimport OpenAI, { APIError } from 'openai';\nimport type { ChatCompletionMessageParam, ChatCompletion } from 'openai/resources/chat/completions';\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n ModelMetadata,\n StreamChunk,\n TokenUsage,\n} from '../core/index.js';\nimport { ok, err, ModelError, ConfigError, ErrorCode, getTokenEstimator } from '../core/index.js';\nimport {\n BaseAdapter,\n type BaseAdapterConfig,\n requireApiKey,\n validateApiKeyPresence,\n} from './base-adapter.js';\nimport { createStream } from './streaming.js';\nimport {\n DEFAULT_MAX_TOKENS,\n resolveModelId,\n getModelCapabilities,\n type OpenAIAdapterConfig,\n} from './openai-types.js';\nimport { planOptionalParams, type DroppedParam } from './optional-params.js';\nimport { getMaxTokensParamForModel } from '../config/model-parameter-support.js';\nimport {\n mapMessage,\n mapTool,\n mapStopReason,\n mapChoiceToContentBlocks,\n mapResponseUsage,\n mapStreamChunk,\n createStreamToolCallState,\n detectNonAnswer,\n CONTENT_FILTERED,\n type NonAnswer,\n} from './openai-mappers.js';\nimport { sanitizeErrorDetails } from '../security/output-sanitizer.js';\n\n// Re-export types and constants for public API\nexport { OPENAI_MODELS, OPENAI_MODEL_ALIASES, type OpenAIAdapterConfig } from './openai-types.js';\n\n/**\n * OpenAI model adapter.\n *\n * Provides a unified interface for interacting with OpenAI's GPT models.\n * Supports completion, streaming, tool use, and vision capabilities.\n *\n * @example\n * ```typescript\n * const adapter = new OpenAIAdapter({\n * modelId: 'gpt-4o',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * const result = await adapter.complete({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * maxTokens: 1024,\n * });\n *\n * if (result.ok) {\n * console.log(result.value.content);\n * }\n * ```\n */\n\n/**\n * Compose a diagnostic string from an OpenAI SDK `APIError`'s real fields\n * (#4047). The SDK's `.message` alone can be as useless as\n * `\"400 status code (no body)\"` for an OpenAI-compatible gateway; this pulls the\n * HTTP status, structured error fields, and the raw body so the actual rejection\n * reason is visible.\n */\n/** Typed structural view of the OpenAI SDK `APIError` fields we read (the SDK's\n * generic `APIError<any,…>` otherwise leaks `any`). */\ninterface ApiErrorView {\n readonly status?: number | null;\n readonly type?: string | null;\n readonly code?: string | null;\n readonly param?: string | null;\n readonly requestID?: string | null;\n readonly error?: unknown;\n readonly message?: string;\n}\n\n/** `key=value` tag, or `''` when the value is absent. */\nfunction kvTag(key: string, val: string | number | null | undefined): string {\n return val === null || val === undefined || val === '' ? '' : `${key}=${String(val)}`;\n}\n\nfunction describeOpenAIApiError(v: ApiErrorView, apiKey?: string): string {\n const tags = [\n `HTTP ${String(v.status ?? 'unknown')}`,\n kvTag('type', v.type),\n kvTag('code', v.code),\n kvTag('param', v.param),\n kvTag('request_id', v.requestID),\n ].filter((t) => t !== '');\n let body = '';\n if (v.error !== undefined && v.error !== null) {\n try {\n const raw = JSON.stringify(v.error);\n body = ` body=${raw.length > MAX_ERROR_BODY_CHARS ? `${raw.slice(0, MAX_ERROR_BODY_CHARS)}…` : raw}`;\n } catch {\n body = ' body=<unserializable>';\n }\n }\n return sanitizeErrorDetails(`${tags.join(' ')}: ${v.message ?? ''}${body}`, apiKey);\n}\n\n/** Cap the surfaced gateway error body so a huge response can't bloat logs/messages. */\nconst MAX_ERROR_BODY_CHARS = 600;\n\nexport class OpenAIAdapter extends BaseAdapter {\n private readonly client: OpenAI;\n private readonly resolvedModelId: string;\n private readonly apiKey: string | undefined;\n\n /**\n * Creates a new OpenAIAdapter instance.\n *\n * @param config - OpenAI adapter configuration\n * @throws {ConfigError} If API key is missing\n */\n constructor(config: OpenAIAdapterConfig) {\n const resolvedModelId =\n config.verbatimModelId === true ? config.modelId : resolveModelId(config.modelId);\n\n // Build baseConfig conditionally to satisfy exactOptionalPropertyTypes\n const baseConfig: BaseAdapterConfig = {\n providerId: 'openai',\n modelId: resolvedModelId,\n capabilities: getModelCapabilities(config.modelId),\n apiKey: config.apiKey,\n };\n\n // Only set optional properties if defined\n if (config.baseUrl !== undefined) {\n baseConfig.baseUrl = config.baseUrl;\n }\n if (config.timeout !== undefined) {\n baseConfig.timeout = config.timeout;\n }\n if (config.maxRetries !== undefined) {\n baseConfig.maxRetries = config.maxRetries;\n }\n\n super(baseConfig);\n\n this.apiKey = config.apiKey;\n this.resolvedModelId = resolvedModelId;\n\n // Validate API key presence\n requireApiKey(config.apiKey, 'OpenAI', config.modelId);\n\n this.client = this.createClient(config);\n }\n\n /**\n * Creates the OpenAI client with configuration.\n */\n private createClient(config: OpenAIAdapterConfig): OpenAI {\n const clientOptions: ConstructorParameters<typeof OpenAI>[0] = {\n apiKey: config.apiKey,\n maxRetries: config.maxRetries ?? 2,\n };\n\n if (config.baseUrl !== undefined) {\n clientOptions.baseURL = config.baseUrl;\n }\n if (config.timeout !== undefined) {\n clientOptions.timeout = config.timeout;\n }\n if (config.organization !== undefined) {\n clientOptions.organization = config.organization;\n }\n if (config.defaultHeaders !== undefined) {\n clientOptions.defaultHeaders = config.defaultHeaders;\n }\n if (config.fetchOptions !== undefined) {\n clientOptions.fetchOptions = config.fetchOptions;\n }\n\n return new OpenAI(clientOptions);\n }\n\n /**\n * Validates adapter configuration.\n * Extends base validation with OpenAI-specific checks.\n */\n override validateConfig(): Result<void, ConfigError> {\n const baseResult = super.validateConfig();\n if (!baseResult.ok) {\n return baseResult;\n }\n\n // Validate API key is present\n const keyResult = validateApiKeyPresence(this.config.apiKey, this.providerId, this.modelId);\n if (!keyResult.ok) return keyResult;\n\n return ok(undefined);\n }\n\n /**\n * Send a completion request to OpenAI.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n this.logRequest(request);\n\n try {\n const response = await this.executeCompletion(request);\n this.logResponse(response);\n return ok(response);\n } catch (error) {\n return err(this.transformError(error));\n }\n }\n\n /**\n * Surface an OpenAI / OpenAI-compatible gateway's REAL HTTP status + response\n * body in the error (#4047). The OpenAI SDK's default message collapses a\n * gateway rejection to e.g. `\"400 status code (no body)\"`, which hides WHY a\n * litellm-style gateway rejected a request — exactly the wall hit when\n * diagnosing degraded voter panels on a custom gateway. We re-message with the\n * status/type/code/param/request-id/body. Error-code routing is unchanged: we\n * classify on the ORIGINAL signal (`status`/`code`/`message`) via a clean probe\n * error, so the diagnostic `request_id`/`body` can't pollute the message-\n * substring classifier, then re-message the result with the full detail.\n * Applies to direct OpenAI and the compat gateway alike.\n */\n protected override transformError(error: unknown): ModelError {\n if (error instanceof APIError) {\n const v = error as ApiErrorView;\n // Classify on the original SDK message + status/code/param only. #4069: thread\n // `param` so a param-naming 400 classifies as MODEL_PARAMETER_UNSUPPORTED and\n // the param name reaches the error context.\n const probe: Error & {\n status?: number | undefined;\n code?: string | null | undefined;\n param?: string | undefined;\n } = new Error(typeof v.message === 'string' ? v.message : '');\n probe.status = typeof v.status === 'number' ? v.status : undefined;\n probe.code = v.code ?? undefined;\n probe.param = typeof v.param === 'string' && v.param !== '' ? v.param : undefined;\n probe.cause = error;\n const classified = super.transformError(probe);\n // Surface the full diagnostic detail in the final message (code/cause kept).\n classified.message = `${this.providerId}/${this.modelId}: ${describeOpenAIApiError(v, this.apiKey)}`;\n return classified;\n }\n const err = super.transformError(error);\n err.message = sanitizeErrorDetails(err.message, this.apiKey);\n return err;\n }\n\n /**\n * Stream a completion request from OpenAI.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n this.logRequest(request);\n\n const [controller, iterable] = createStream<StreamChunk>();\n\n // Start streaming in the background\n this.executeStream(request, controller).catch((error: unknown) => {\n const modelError = this.transformError(error);\n controller.error(modelError);\n });\n\n yield* iterable;\n }\n\n /**\n * Count tokens in text using OpenAI-specific estimation.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n override countTokens(text: string): Promise<number> {\n // Use unified TokenEstimator with OpenAI-specific ratio (~4 chars/token)\n return Promise.resolve(getTokenEstimator().estimateText(text, 'openai'));\n }\n\n /**\n * Executes the completion request against the OpenAI API.\n */\n private async executeCompletion(request: CompletionRequest): Promise<CompletionResponse> {\n const { params, dropped } = this.buildRequestParams(request);\n // #3036: forward AbortSignal into the OpenAI SDK so withWatchdog\n // timeouts cancel the HTTP request instead of leaking it past the\n // Promise.race boundary. Branch on signal presence — vitest 4\n // toHaveBeenCalledWith treats `(params, undefined)` as a distinct\n // call shape from `(params)`.\n const response =\n request.signal !== undefined\n ? await this.client.chat.completions.create(params, { signal: request.signal })\n : await this.client.chat.completions.create(params);\n // #4069: surface params dropped by the seam (e.g. temperature) as warnings.\n return this.mapResponse(response, dropped);\n }\n\n /**\n * Executes streaming completion and pushes chunks to the controller.\n */\n private async executeStream(\n request: CompletionRequest,\n controller: {\n push: (chunk: StreamChunk) => Result<void, Error>;\n complete: () => void;\n error: (error: Error) => void;\n }\n ): Promise<void> {\n try {\n const { params } = this.buildRequestParams(request);\n const stream = await this.client.chat.completions.create({ ...params, stream: true });\n\n let contentIndex = 0;\n let hasStarted = false;\n const toolCalls = createStreamToolCallState();\n\n for await (const chunk of stream) {\n // #6607: a filtered stream is a refusal. Error the stream instead of\n // finishing it normally over whatever partial text arrived.\n if (chunk.choices[0]?.finish_reason === 'content_filter') {\n throw nonAnswerError(`${this.providerId}/${this.modelId}`, CONTENT_FILTERED, chunk.model);\n }\n const mappedChunks = mapStreamChunk(chunk, contentIndex, hasStarted, toolCalls);\n\n for (const mappedChunk of mappedChunks) {\n if (mappedChunk.type === 'message_start') {\n hasStarted = true;\n }\n if (mappedChunk.type === 'content_block_start') {\n contentIndex++;\n }\n controller.push(mappedChunk);\n }\n }\n\n controller.complete();\n } catch (error) {\n const modelError = this.transformError(error);\n controller.error(modelError);\n }\n }\n\n /**\n * Builds OpenAI API request parameters from our CompletionRequest.\n */\n private buildRequestParams(request: CompletionRequest): {\n params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming;\n dropped: readonly DroppedParam[];\n } {\n const messages = this.buildMessages(request);\n\n const params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming = {\n model: this.resolvedModelId,\n messages,\n max_completion_tokens: request.maxTokens ?? this.defaultMaxCompletionTokens(),\n };\n\n const dropped = this.addOptionalParams(params, request);\n return { params, dropped };\n }\n\n /**\n * Builds the messages array for the request.\n */\n private buildMessages(request: CompletionRequest): ChatCompletionMessageParam[] {\n const messages: ChatCompletionMessageParam[] = [];\n\n // Add system prompt if provided explicitly\n if (request.systemPrompt !== undefined && request.systemPrompt !== '') {\n messages.push({ role: 'system', content: request.systemPrompt });\n }\n\n // Map and add all messages (filtering out system if already added via systemPrompt)\n for (const msg of request.messages) {\n if (msg.role === 'system' && request.systemPrompt !== undefined) {\n continue;\n }\n messages.push(...mapMessage(msg));\n }\n\n return messages;\n }\n\n /**\n * Adds optional parameters to the request.\n */\n private addOptionalParams(\n params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming,\n request: CompletionRequest\n ): readonly DroppedParam[] {\n // #4068: the temperature drop-decision (#4061: a gateway routing to a Claude\n // model after Opus 4.6, or an OpenAI reasoning model, rejects a non-1.0\n // temperature with a 400; omit it so a gateway-routed voter panel at the\n // default 0.3 does not 400) is centralized in the shared planOptionalParams\n // seam. NOTE: a gateway that injects its OWN default when the field is absent\n // is outside our control — our contract is only to not SEND a rejected value.\n const plan = planOptionalParams(request, this.resolvedModelId);\n if (plan.temperature !== undefined) {\n params.temperature = plan.temperature;\n }\n\n if (request.stop !== undefined && request.stop.length > 0) {\n params.stop = request.stop;\n }\n\n if (request.tools !== undefined && request.tools.length > 0) {\n params.tools = request.tools.map(mapTool);\n }\n\n this.addResponseFormat(params, request);\n\n // #4069: report dropped params so mapResponse can surface them as warnings.\n return plan.dropped;\n }\n\n /**\n * Adds response format to the request if specified.\n */\n private addResponseFormat(\n params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming,\n request: CompletionRequest\n ): void {\n if (request.responseFormat === undefined) {\n return;\n }\n\n if (request.responseFormat.type === 'json_object') {\n params.response_format = { type: 'json_object' };\n } else if (request.responseFormat.type === 'json_schema') {\n params.response_format = {\n type: 'json_schema',\n json_schema: {\n name: 'response',\n schema: request.responseFormat.schema,\n },\n };\n }\n }\n\n /**\n * Maps OpenAI API response to our CompletionResponse format.\n */\n private mapResponse(\n response: ChatCompletion,\n dropped: readonly DroppedParam[] = []\n ): CompletionResponse {\n // #6607: a refusal, an empty `choices` array or a reasoning-exhausted reply\n // is not an answer. Consumers (voters, experts, orchestrate) read any mapped\n // response as one and never branch on `stopReason`, so the only signal they\n // honour is an error.\n const firstChoice = response.choices[0];\n if (firstChoice === undefined) {\n throw nonAnswerError(\n `${this.providerId}/${this.modelId}`,\n { reason: 'no_choices', detail: 'the response contained no choices' },\n response.model\n );\n }\n const nonAnswer = detectNonAnswer(firstChoice, response.usage, this.isReasoningFamily());\n if (nonAnswer !== undefined)\n throw nonAnswerError(`${this.providerId}/${this.modelId}`, nonAnswer, response.model);\n\n const content = mapChoiceToContentBlocks(firstChoice);\n const usage: TokenUsage | undefined = mapResponseUsage(response);\n\n return {\n content,\n ...(usage !== undefined ? { usage } : {}),\n stopReason: mapStopReason(firstChoice.finish_reason),\n model: response.model,\n // #4069: surface dropped params (e.g. an omitted temperature). Omitted\n // entirely when nothing was dropped (exactOptionalPropertyTypes).\n ...(dropped.length > 0 ? { warnings: dropped } : {}),\n };\n }\n\n /**\n * Reasoning families are the models that take `max_completion_tokens`\n * (o-series, gpt-5, codex); the registry answers first, a regex second.\n */\n private isReasoningFamily(): boolean {\n return getMaxTokensParamForModel(this.resolvedModelId) === 'max_completion_tokens';\n }\n\n /**\n * Default completion cap when the request sets none (#6607). On a reasoning\n * model the cap covers hidden reasoning tokens AND the visible reply, and\n * 4,096 can be spent entirely on reasoning, leaving an empty reply. OpenAI's\n * reasoning guide recommends reserving at least 25,000 tokens for reasoning\n * and output when starting out, so that is the reasoning default. It is a\n * ceiling, not a spend: a reply that finishes early is billed for what it\n * used. Other models keep `DEFAULT_MAX_TOKENS`.\n */\n private defaultMaxCompletionTokens(): number {\n return this.isReasoningFamily() ? REASONING_DEFAULT_MAX_COMPLETION_TOKENS : DEFAULT_MAX_TOKENS;\n }\n\n /**\n * (#2529) List models served by this OpenAI-compatible endpoint.\n *\n * Wraps `GET /v1/models`. Result is cached for `LIST_MODELS_TTL_MS`\n * so identity resolution doesn't round-trip on every adapter.\n * Concurrent callers share the in-flight promise.\n *\n * Throws on non-2xx so the harness-side identity resolver knows to\n * fall back to modelId parsing — silent empty-list returns would be\n * indistinguishable from \"this gateway has no models\", which a\n * misconfigured endpoint shouldn't be allowed to claim.\n */\n async listModels(): Promise<readonly ModelMetadata[]> {\n const now = Date.now();\n if (this.modelsCache !== null && now - this.modelsCache.fetchedAt < LIST_MODELS_TTL_MS) {\n return this.modelsCache.value;\n }\n if (this.modelsInFlight !== null) {\n return this.modelsInFlight;\n }\n const inFlight = this.fetchModels();\n this.modelsInFlight = inFlight;\n try {\n const value = await inFlight;\n this.modelsCache = { value, fetchedAt: Date.now() };\n return value;\n } finally {\n this.modelsInFlight = null;\n }\n }\n\n private modelsCache: { value: readonly ModelMetadata[]; fetchedAt: number } | null = null;\n private modelsInFlight: Promise<readonly ModelMetadata[]> | null = null;\n\n private async fetchModels(): Promise<readonly ModelMetadata[]> {\n const list = await this.client.models.list();\n return list.data.map((m): ModelMetadata => {\n const meta: ModelMetadata = { id: m.id };\n if (typeof m.owned_by === 'string') {\n return { ...meta, ownedBy: m.owned_by, createdAt: m.created };\n }\n if (typeof m.created === 'number') {\n return { ...meta, createdAt: m.created };\n }\n return meta;\n });\n }\n}\n\nconst LIST_MODELS_TTL_MS = 5 * 60 * 1000;\n\n/** See `defaultMaxCompletionTokens` for why 25,000 (#6607). */\nconst REASONING_DEFAULT_MAX_COMPLETION_TOKENS = 25_000;\n\n/**\n * A non-answer as a non-retryable `MODEL_ERROR` (#6607). `context.reason`\n * names which kind it was, so telemetry can tell a refusal from a\n * reasoning-exhausted budget. `source` is `provider/model`.\n *\n * Module-level rather than a private method: the API-surface snapshot follows\n * types named anywhere in an exported class, private members included.\n */\nfunction nonAnswerError(source: string, nonAnswer: NonAnswer, servedModel?: string): ModelError {\n return new ModelError(`${source}: ${nonAnswer.detail}`, {\n code: ErrorCode.MODEL_ERROR,\n context: {\n reason: nonAnswer.reason,\n ...(servedModel !== undefined ? { servedModel } : {}),\n ...(nonAnswer.reasoningTokens !== undefined\n ? { reasoningTokens: nonAnswer.reasoningTokens }\n : {}),\n },\n });\n}\n\n/**\n * Creates an OpenAIAdapter with the specified configuration.\n * Factory function for cleaner API.\n *\n * @param config - OpenAI adapter configuration\n * @returns A configured OpenAIAdapter instance\n *\n * @example\n * ```typescript\n * const adapter = createOpenAIAdapter({\n * modelId: 'gpt-4o',\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * ```\n */\nexport function createOpenAIAdapter(config: OpenAIAdapterConfig): OpenAIAdapter {\n return new OpenAIAdapter(config);\n}\n","/**\n * nexus-agents/adapters - OpenAI Type Helpers\n *\n * Type definitions and constants for the OpenAI direct-API SDK adapter.\n *\n * **Architectural boundary (#2200 Child 3):** these constants do NOT live\n * in `config/in-tree-data.ts`. The canonical registry's `cliName`\n * dimension targets CLI tools (`claude` / `gemini` / `codex` / `opencode`)\n * — there is no `openai` CLI binary. Adding `'openai'` to the CLI_NAMES\n * enum would force a fifth case in 4+ exhaustive switches across the\n * codebase, violating the semantic of \"CLI tool name.\"\n *\n * The OpenAI direct adapter is conceptually different from CLI adapters:\n * it talks to the OpenAI HTTPS API directly, not via a subprocess CLI.\n * Its model identifiers are OpenAI's own (`gpt-4o-2024-11-20`,\n * `gpt-3.5-turbo-0125`, etc.) — these are upstream API constants, not\n * versions WE chose. They drift only when OpenAI ships new dated releases.\n *\n * This file is the single source of truth for OpenAI direct-API model\n * identifiers. The model-string drift fitness-guard (#2199) treats it as\n * a documented architectural exception in the allowlist.\n */\n\nimport type { ModelCapability } from '../core/index.js';\nimport { ModelCapability as MC } from '../core/index.js';\nimport { getCliModelName } from '../config/model-config-helpers.js';\n\n/**\n * Supported OpenAI direct-API model identifiers (OpenAI's own dated names).\n *\n * GPT_5_2_CODEX derives from the canonical registry (codex-5.2's cliModelName)\n * because it overlaps with the Codex CLI; the rest are pure-API constants.\n * Since #5091 that entry has been repointed to whatever slug codex serves\n * (`gpt-5.6-luna` as of 2026-09-23), so the key's name lags its value; renaming\n * the key is a public-API change and is tracked separately.\n */\nexport const OPENAI_MODELS = {\n GPT_5_2: 'gpt-5.2',\n GPT_5_2_INSTANT: 'gpt-5.2-chat-latest',\n GPT_5_2_PRO: 'gpt-5.2-pro',\n /**\n * Registry-derived: resolves to `codex-5.2`'s `cliModelName`, which since\n * 2026-09-23 is `gpt-5.6-luna`, not a \"5.2\" model. The key name lags its\n * value; renaming it is a public-API change tracked in #5489.\n */\n GPT_5_2_CODEX: getCliModelName('codex-5.2'),\n GPT_4O: 'gpt-4o-2024-11-20',\n GPT_4O_MINI: 'gpt-4o-mini-2024-07-18',\n GPT_4_TURBO: 'gpt-4-turbo-2024-04-09',\n GPT_35_TURBO: 'gpt-3.5-turbo-0125',\n} as const;\n\n/**\n * User-friendly OpenAI aliases → dated model identifiers.\n *\n * Identity-only mappings (e.g., `'gpt-5.2-pro' → 'gpt-5.2-pro'`) were\n * removed in #2200 Child 3 — `resolveModelId` already passes unknown ids\n * through unchanged via `?? modelId`. Only entries that translate a\n * shorthand into a dated version remain.\n */\nexport const OPENAI_MODEL_ALIASES: Record<string, string> = {\n 'gpt-5.2-instant': OPENAI_MODELS.GPT_5_2_INSTANT,\n 'gpt-4o': OPENAI_MODELS.GPT_4O,\n 'gpt-4o-mini': OPENAI_MODELS.GPT_4O_MINI,\n 'gpt-4-turbo': OPENAI_MODELS.GPT_4_TURBO,\n 'gpt-3.5-turbo': OPENAI_MODELS.GPT_35_TURBO,\n} as const;\n\n/**\n * Configuration specific to OpenAIAdapter.\n */\nexport interface OpenAIAdapterConfig {\n /** Model ID (e.g., 'gpt-4o' or full model identifier) */\n modelId: string;\n /** API key for OpenAI API (required) */\n apiKey: string;\n /** Base URL for API (optional, defaults to OpenAI's API) */\n baseUrl?: string;\n /** Request timeout in milliseconds (optional) */\n timeout?: number;\n /** Maximum retries for failed requests (optional) */\n maxRetries?: number;\n /** Organization ID (optional) */\n organization?: string;\n /**\n * Send `modelId` exactly as given, skipping {@link OPENAI_MODEL_ALIASES}\n * (#6605). Set by the OpenAI-compatible gateway path, whose ids come from\n * the gateway's own listing: rewriting `gpt-4o` to a dated OpenAI snapshot\n * names a model that gateway may not serve. Default `false`.\n */\n verbatimModelId?: boolean;\n /**\n * Headers sent on every request; a `null` value removes a default header\n * (`Authorization: null` drops the bearer). Set by the OpenAI-compatible\n * gateway path for a custom auth header and extra static headers (#6608).\n */\n defaultHeaders?: Readonly<Record<string, string | null>>;\n /**\n * `fetch` options for every request — the gateway path sets a proxy\n * `dispatcher` here when `HTTPS_PROXY` / `HTTP_PROXY` applies (#6608).\n */\n fetchOptions?: Pick<RequestInit, 'dispatcher'>;\n}\n\n// Note: Token estimation moved to core/token-estimator.ts (unified TokenEstimator)\n\n/**\n * Default maximum tokens for OpenAI models.\n */\nexport const DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Tool call type for extracting function info.\n */\nexport interface FunctionToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Type guard for function tool calls.\n * Note: typeof null === 'object' is true, so we need to check tc !== null\n */\nexport function isFunctionToolCall(toolCall: unknown): toolCall is FunctionToolCall {\n if (typeof toolCall !== 'object' || toolCall === null) {\n return false;\n }\n const tc = toolCall as Record<string, unknown>;\n return tc['type'] === 'function' && typeof tc['function'] === 'object' && tc['function'] !== null;\n}\n\n/**\n * Resolves model alias to full model identifier.\n */\nexport function resolveModelId(modelId: string): string {\n return OPENAI_MODEL_ALIASES[modelId] ?? modelId;\n}\n\n/**\n * Determines capabilities based on model ID.\n */\nexport function getModelCapabilities(modelId: string): readonly ModelCapability[] {\n const capabilities: ModelCapability[] = [MC.COMPLETION, MC.STREAMING, MC.TOOL_USE];\n\n const resolvedId = resolveModelId(modelId);\n\n // Vision is available on GPT-4o, GPT-4-turbo, and GPT-5.2 models\n if (\n resolvedId.includes('gpt-4o') ||\n resolvedId.includes('gpt-4-turbo') ||\n resolvedId.includes('gpt-5.2')\n ) {\n capabilities.push(MC.VISION);\n }\n\n // Extended thinking is available on GPT-5.2 models\n if (resolvedId.includes('gpt-5.2')) {\n capabilities.push(MC.EXTENDED_THINKING);\n }\n\n return capabilities;\n}\n","/**\n * nexus-agents/adapters - OpenAI Message Mappers\n *\n * Functions for mapping between Nexus and OpenAI message formats.\n */\n\nimport type OpenAI from 'openai';\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionTool,\n ChatCompletion,\n ChatCompletionChunk,\n} from 'openai/resources/chat/completions';\nimport type {\n ContentBlock,\n Message,\n ToolDefinition,\n TokenUsage,\n StopReason,\n StreamChunk,\n} from '../core/index.js';\nimport { isFunctionToolCall } from './openai-types.js';\n\n/**\n * Maps OpenAI finish reasons to our StopReason type.\n */\nexport function mapStopReason(openaiReason: string | null | undefined): StopReason {\n switch (openaiReason) {\n case 'stop':\n return 'end_turn';\n case 'length':\n return 'max_tokens';\n case 'tool_calls':\n case 'function_call':\n return 'tool_use';\n // `content_filter` is never mapped as a finish: the adapter turns it into an\n // error before a response is built (#6607, see detectNonAnswer), because\n // every consumer reads a mapped response as an answer.\n default:\n return 'end_turn';\n }\n}\n\n/** A reply blocked by the provider's content filter, streamed or not (#6607). */\nexport const CONTENT_FILTERED: NonAnswer = {\n reason: 'content_filter',\n detail: 'the reply was blocked by a content filter',\n};\n\n/** A completion that must surface as an error, never as an empty success (#6607). */\nexport interface NonAnswer {\n /** Why the completion carries no answer. */\n readonly reason: 'content_filter' | 'no_choices' | 'reasoning_truncated';\n readonly detail: string;\n /** Reasoning tokens the vendor reported, when it reported them. */\n readonly reasoningTokens?: number;\n}\n\n/**\n * Classify a completion choice that is not an answer (#6607). The third kind,\n * `no_choices` (an empty `choices` array, which some gateways return for a\n * blocked prompt), has no choice to classify and is raised by the adapter.\n *\n * - `content_filter`: the provider's safety layer blocked or cut the reply. Any\n * partial text is not an answer either.\n * - `reasoning_truncated`: a reasoning model hit the completion cap with no\n * visible output, so the whole budget went to reasoning. This is distinct\n * from an ordinary `length` truncation, which still carries partial text.\n * `reasoningFamily` comes from the model id; a reported non-zero\n * `reasoning_tokens` count is evidence on its own for ids the regex misses.\n *\n * Returns `undefined` for every other completion.\n */\nexport function detectNonAnswer(\n choice: ChatCompletion.Choice,\n usage: ChatCompletion['usage'],\n reasoningFamily: boolean\n): NonAnswer | undefined {\n if (choice.finish_reason === 'content_filter') return CONTENT_FILTERED;\n if (choice.finish_reason !== 'length' || hasVisibleOutput(choice)) return undefined;\n const reasoningTokens = usage?.completion_tokens_details?.reasoning_tokens;\n if (!reasoningFamily && !(reasoningTokens !== undefined && reasoningTokens > 0)) {\n return undefined;\n }\n return {\n reason: 'reasoning_truncated',\n detail:\n 'the completion budget was spent on reasoning before any output (empty reply, finish length)',\n ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),\n };\n}\n\nfunction hasVisibleOutput(choice: ChatCompletion.Choice): boolean {\n const text = choice.message.content;\n if (text !== null && text !== '') return true;\n return (choice.message.tool_calls?.length ?? 0) > 0;\n}\n\n/**\n * Parse a tool call's JSON `arguments` string. Unparseable text is kept under\n * `_raw` rather than dropped, so the caller still sees what the model sent.\n */\nfunction parseToolArguments(args: string): unknown {\n try {\n return JSON.parse(args) as unknown;\n } catch {\n return { _raw: args };\n }\n}\n\n/**\n * Maps OpenAI choice to our ContentBlock array.\n */\nexport function mapChoiceToContentBlocks(choice: ChatCompletion.Choice): ContentBlock[] {\n const blocks: ContentBlock[] = [];\n const message = choice.message;\n\n // Add text content if present\n if (message.content !== null && message.content !== '') {\n blocks.push({ type: 'text', text: message.content });\n }\n\n // Add tool calls if present\n if (message.tool_calls !== undefined && message.tool_calls.length > 0) {\n for (const toolCall of message.tool_calls) {\n if (isFunctionToolCall(toolCall)) {\n blocks.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: parseToolArguments(toolCall.function.arguments),\n });\n }\n }\n }\n\n // If no content at all, return empty text block\n if (blocks.length === 0) {\n blocks.push({ type: 'text', text: '' });\n }\n\n return blocks;\n}\n\n/**\n * Maps our Message format to OpenAI's ChatCompletionMessageParam format.\n *\n * Returns an ARRAY: one user message holding several `tool_result` blocks\n * becomes one `tool` message per result (#6607). OpenAI requires a tool message\n * for every `tool_call_id` the assistant issued; sending only the first made\n * strict gateways reject the request with a 400.\n */\nexport function mapMessage(message: Message): ChatCompletionMessageParam[] {\n if (message.role === 'system') {\n return [mapSystemMessage(message)];\n }\n if (message.role === 'user') {\n return mapUserMessage(message);\n }\n return [mapAssistantMessage(message)];\n}\n\n/**\n * Maps a system message.\n */\nfunction mapSystemMessage(message: Message): ChatCompletionMessageParam {\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('\\n');\n return { role: 'system', content };\n}\n\n/**\n * Maps a user message.\n */\nfunction mapUserMessage(message: Message): ChatCompletionMessageParam[] {\n if (typeof message.content === 'string') {\n return [{ role: 'user', content: message.content }];\n }\n\n // Tool results become one `tool` message each, in order (#6607).\n const toolResults = message.content.filter(\n (b): b is { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean } =>\n b.type === 'tool_result'\n );\n\n if (toolResults.length > 0) {\n return toolResults.map((result) => ({\n role: 'tool' as const,\n tool_call_id: result.tool_use_id,\n content: result.content,\n }));\n }\n\n // Map to user message with content array\n const content = message.content.map((block) => {\n if (block.type === 'text') {\n return { type: 'text' as const, text: block.text };\n }\n if (block.type === 'image') {\n return {\n type: 'image_url' as const,\n image_url: {\n url: `data:${block.source.media_type};base64,${block.source.data}`,\n },\n };\n }\n // Fallback for other types\n return { type: 'text' as const, text: '' };\n });\n\n return [{ role: 'user', content }];\n}\n\n/**\n * Maps an assistant message.\n */\nfunction mapAssistantMessage(message: Message): ChatCompletionMessageParam {\n if (typeof message.content === 'string') {\n return { role: 'assistant', content: message.content };\n }\n\n // Check for tool uses in assistant message\n const toolUses = message.content.filter(\n (b): b is { type: 'tool_use'; id: string; name: string; input: unknown } =>\n b.type === 'tool_use'\n );\n\n const textContent = message.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('');\n\n if (toolUses.length > 0) {\n const assistantMessage: ChatCompletionMessageParam = {\n role: 'assistant',\n content: textContent !== '' ? textContent : null,\n tool_calls: toolUses.map((tool) => ({\n id: tool.id,\n type: 'function' as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input),\n },\n })),\n };\n return assistantMessage;\n }\n\n return { role: 'assistant', content: textContent };\n}\n\n/**\n * Maps our ToolDefinition to OpenAI's tool format.\n */\nexport function mapTool(tool: ToolDefinition): ChatCompletionTool {\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Maps OpenAI API response to our CompletionResponse format.\n */\nexport function mapResponseUsage(response: ChatCompletion): TokenUsage | undefined {\n const u = response.usage;\n // #4439: `?? 0` here synthesised a measurement the vendor never sent. An\n // absent usage block must stay absent so the decision-cost rollup can tell\n // \"zero tokens\" from \"we do not know\".\n if (u === undefined) return undefined;\n const cached = u.prompt_tokens_details?.cached_tokens;\n return {\n inputTokens: u.prompt_tokens,\n outputTokens: u.completion_tokens,\n totalTokens: u.total_tokens,\n ...(cached !== undefined ? { cachedInputTokens: cached } : {}),\n };\n}\n\n/**\n * Maps content delta from stream chunk.\n */\nfunction mapContentDelta(\n delta: OpenAI.Chat.ChatCompletionChunk.Choice.Delta,\n currentIndex: number,\n hasStarted: boolean\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n\n if (delta.content !== undefined && delta.content !== null && delta.content !== '') {\n // Start content block if this is the first content\n if (currentIndex === 0 && !hasStarted) {\n chunks.push({\n type: 'content_block_start',\n index: 0,\n contentBlock: { type: 'text', text: '' },\n });\n }\n\n chunks.push({\n type: 'content_block_delta',\n index: currentIndex,\n delta: { type: 'text_delta', text: delta.content },\n });\n }\n\n return chunks;\n}\n\n/**\n * Tool calls being assembled across a stream, keyed by the OpenAI tool index\n * (#6607). OpenAI sends the id and name in the first delta for a call and the\n * JSON `arguments` in fragments after it, so a call is only complete when the\n * choice finishes. Create one per stream with {@link createStreamToolCallState}.\n */\ninterface StreamToolCallState {\n readonly calls: Map<number, { id: string; name: string; args: string }>;\n}\n\n/** A fresh accumulator for one stream (#6607). */\nexport function createStreamToolCallState(): StreamToolCallState {\n return { calls: new Map() };\n}\n\n/**\n * Accumulates tool-call deltas. Emits nothing: the `tool_use` block is emitted\n * once, complete, at the finish chunk (see {@link flushToolCalls}). Emitting it\n * on the first delta, as this used to, fixed its `input` at `{}` (#6607).\n */\nfunction accumulateToolCallsDelta(\n delta: OpenAI.Chat.ChatCompletionChunk.Choice.Delta,\n state: StreamToolCallState\n): void {\n for (const toolCall of delta.tool_calls ?? []) {\n const entry = state.calls.get(toolCall.index) ?? { id: '', name: '', args: '' };\n if (toolCall.id !== undefined) entry.id = toolCall.id;\n if (toolCall.function?.name !== undefined) entry.name = toolCall.function.name;\n if (toolCall.function?.arguments !== undefined) entry.args += toolCall.function.arguments;\n state.calls.set(toolCall.index, entry);\n }\n}\n\n/** Emit each assembled tool call as one complete `tool_use` block, in index order. */\nfunction flushToolCalls(state: StreamToolCallState): StreamChunk[] {\n const chunks: StreamChunk[] = [...state.calls.entries()]\n .sort(([a], [b]) => a - b)\n .map(([index, call]) => ({\n type: 'content_block_start' as const,\n index,\n contentBlock: {\n type: 'tool_use' as const,\n id: call.id,\n name: call.name,\n input: call.args === '' ? {} : parseToolArguments(call.args),\n },\n }));\n state.calls.clear();\n return chunks;\n}\n\n/**\n * Maps finish reason from stream chunk.\n */\nfunction mapFinishChunks(\n choice: ChatCompletionChunk.Choice,\n chunk: ChatCompletionChunk,\n currentIndex: number,\n toolCalls: StreamToolCallState\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n\n if (choice.finish_reason !== null) {\n chunks.push(...flushToolCalls(toolCalls));\n\n // End current content block\n chunks.push({\n type: 'content_block_stop',\n index: currentIndex,\n });\n\n // Emit message_delta with stop reason.\n //\n // NO `usage` on this path. OpenAI populates `chunk.usage` on a streaming\n // response only when the request sets `stream_options: { include_usage:\n // true }`, and nothing in this tree does — so both `??` fallbacks always\n // took the `0` branch and every stream emitted\n // `{inputTokens: 0, outputTokens: 0, totalTokens: 0}`: a usage block in\n // which nothing whatsoever was measured.\n //\n // `inputTokensMeasured: false` covered only the first of those three. Its\n // own contract is \"whether `inputTokens` is a measurement\", and there is no\n // `outputTokensMeasured`, so a consumer honouring the flag correctly\n // discounted `inputTokens` and then read `outputTokens: 0` as a measured\n // zero. That is the #4439 policy this violated, stated on the field itself:\n // \"Where NOTHING is known, prefer omitting `usage` entirely.\" The SDK\n // adapter's stream path already does exactly that (#4835), for the same\n // reason.\n chunks.push({\n type: 'message_delta',\n delta: { stop_reason: mapStopReason(choice.finish_reason) },\n // A stream whose usage IS reported keeps it — when `include_usage` is\n // wired, this is the branch that carries a real measurement.\n ...(chunk.usage !== undefined && chunk.usage !== null\n ? {\n usage: {\n // OpenAI still omits prompt_tokens on the final chunk (#4835).\n inputTokens: 0,\n inputTokensMeasured: false,\n outputTokens: chunk.usage.completion_tokens,\n totalTokens: chunk.usage.total_tokens,\n },\n }\n : {}),\n });\n\n // Emit message_stop\n chunks.push({ type: 'message_stop' });\n }\n\n return chunks;\n}\n\n/**\n * Maps OpenAI stream chunks to our StreamChunk format.\n */\nexport function mapStreamChunk(\n chunk: ChatCompletionChunk,\n currentIndex: number,\n hasStarted: boolean,\n toolCalls: StreamToolCallState\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n const choice = chunk.choices[0];\n\n // Emit message_start on first chunk\n if (!hasStarted) {\n chunks.push({\n type: 'message_start',\n message: { model: chunk.model },\n });\n }\n\n if (choice === undefined) {\n return chunks;\n }\n\n const delta = choice.delta;\n\n // Map content delta\n chunks.push(...mapContentDelta(delta, currentIndex, hasStarted));\n\n // Accumulate tool calls; they are emitted whole at the finish chunk.\n accumulateToolCallsDelta(delta, toolCalls);\n\n // Map finish reason\n chunks.push(...mapFinishChunks(choice, chunk, currentIndex, toolCalls));\n\n return chunks;\n}\n","/**\n * opencode.json gateway-config bridge (#2503, child 3 of epic #2500).\n *\n * When nexus-agents runs as an MCP loaded by OpenCode (typically inside a\n * Docker sandbox), OpenCode's `opencode.json` already declares the\n * OpenAI-compatible gateway the harness uses. Reading it from there saves\n * the operator from re-declaring the same `baseURL` + `apiKey` as\n * NEXUS_OPENAI_COMPAT_* env vars.\n *\n * Scope (per direction discussion 2026-05-09):\n * - **Only** reads `providers.openai-compat.options.{baseURL, apiKey}`.\n * Does NOT read OpenCode's MCP config, model list, logging, or other\n * settings. nexus-agents' own behaviour stays driven by\n * `nexus-agents.yaml` + `NEXUS_*` env vars.\n * - Resolves OpenCode's `{env:VAR}` interpolation in the apiKey field.\n * - Returns `null` on any failure path (missing file, parse error,\n * missing fields, unset interpolated env var) — caller falls back to\n * env-var precedence; we don't throw.\n *\n * Precedence (applied in `openai-compat-adapter.ts`):\n * 1. `NEXUS_OPENAI_COMPAT_URL` + `NEXUS_OPENAI_COMPAT_KEY` env vars (if both set)\n * 2. `NEXUS_OPENCODE_CONFIG` → `opencode.json` → `providers.openai-compat`\n * 3. Unconfigured → `null`, no adapter registered\n *\n * Sanitised logging (#4392 increment 3 tightened it): never log the resolved\n * apiKey, never log file contents — Node's JSON parse error embeds a source\n * snippet, so only the error NAME is logged — and log the gateway's hostname\n * rather than the baseURL, which can carry userinfo.\n *\n * @module config/opencode-bridge\n */\n\nimport { readFileSync } from 'node:fs';\n\nimport type { ILogger } from '../core/index.js';\nimport { createLogger } from '../core/index.js';\nimport { hostnameOf } from '../adapters/sdk/gateway-env.js';\n\nconst defaultLogger = createLogger({ component: 'opencode-bridge' });\n\nexport interface OpencodeGatewayConfig {\n readonly baseURL: string;\n readonly apiKey: string;\n}\n\n/**\n * Read `providers.openai-compat.options.{baseURL, apiKey}` from the given\n * opencode.json path. Returns `null` on any failure — the caller falls\n * back to env-var precedence.\n */\nexport function readOpencodeGateway(\n path: string,\n logger: ILogger = defaultLogger\n): OpencodeGatewayConfig | null {\n const raw = readFileOrNull(path, logger);\n if (raw === null) return null;\n\n const parsed = parseJsonOrNull(raw, path, logger);\n if (parsed === null) return null;\n\n const options = extractOpenAICompatOptions(parsed);\n if (options === null) {\n logger.debug('opencode.json has no providers.openai-compat.options block', { path });\n return null;\n }\n\n const baseURL = typeof options.baseURL === 'string' ? options.baseURL.trim() : '';\n const apiKeyRaw = typeof options.apiKey === 'string' ? options.apiKey.trim() : '';\n if (baseURL === '' || apiKeyRaw === '') {\n logger.warn('opencode.json providers.openai-compat missing baseURL or apiKey', { path });\n return null;\n }\n\n const apiKey = resolveEnvInterpolation(apiKeyRaw);\n if (apiKey === null) {\n logger.warn(\n 'opencode.json apiKey references an env var that is not set; gateway not configured',\n { path }\n );\n return null;\n }\n\n logger.info('Gateway config sourced from opencode.json', { host: hostnameOf(baseURL), path });\n return { baseURL, apiKey };\n}\n\nfunction readFileOrNull(path: string, logger: ILogger): string | null {\n try {\n return readFileSync(path, 'utf8');\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n logger.debug('Could not read opencode.json', { path, error: msg });\n return null;\n }\n}\n\n/**\n * Logs the error NAME only. On Node 22 a `SyntaxError` from `JSON.parse`\n * quotes the offending source (`... \"{\"apiKey\": sk-...\" is not valid JSON`),\n * so the message is a channel for the file's contents (#4392 increment 3).\n */\nfunction parseJsonOrNull(raw: string, path: string, logger: ILogger): unknown {\n try {\n return JSON.parse(raw);\n } catch (err: unknown) {\n const name = err instanceof Error ? err.name : 'unknown error';\n logger.warn('opencode.json is not valid JSON; ignoring', { path, error: name });\n return null;\n }\n}\n\n/**\n * Pull `providers.openai-compat.options` out of the parsed JSON without\n * coupling to a Zod schema. OpenCode's config has many keys we don't\n * care about; we only navigate to the one we need.\n */\nfunction extractOpenAICompatOptions(\n parsed: unknown\n): { baseURL?: unknown; apiKey?: unknown } | null {\n if (typeof parsed !== 'object' || parsed === null) return null;\n const root = parsed as { providers?: unknown };\n const providers = root.providers;\n if (typeof providers !== 'object' || providers === null) return null;\n const provider = (providers as Record<string, unknown>)['openai-compat'];\n if (typeof provider !== 'object' || provider === null) return null;\n const options = (provider as { options?: unknown }).options;\n if (typeof options !== 'object' || options === null) return null;\n return options;\n}\n\n/**\n * Resolve OpenCode's `{env:VAR}` interpolation. Only the literal pattern\n * is supported (no shell expansion, no defaults). Returns the string as-is\n * when no interpolation is present; returns `null` when the referenced\n * env var is not set.\n */\nfunction resolveEnvInterpolation(value: string): string | null {\n const match = /^\\{env:([A-Z0-9_]+)\\}$/.exec(value);\n if (match === null) return value;\n const envName = match[1];\n if (envName === undefined) return null;\n const resolved = process.env[envName];\n if (resolved === undefined || resolved === '') return null;\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,OAAOA,aAAY;;;ACoBZ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;","names":["OpenAI","err","err","OpenAI"]}
|
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ensureGatewayDiscovered,
|
|
3
|
+
gatewayDiscoveryGeneration
|
|
4
|
+
} from "./chunk-JX7D7GXS.js";
|
|
1
5
|
import {
|
|
2
6
|
createAutoAdapter
|
|
3
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-BNRWICG7.js";
|
|
4
8
|
import {
|
|
5
9
|
getDefaultCliCircuitBreakerRegistry,
|
|
6
10
|
mapModelErrorToCategory
|
|
7
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-QDELEGK7.js";
|
|
8
12
|
import {
|
|
9
13
|
CircularBuffer,
|
|
10
14
|
ConfigError,
|
|
@@ -30,7 +34,7 @@ import {
|
|
|
30
34
|
resolveModelIdentitySync,
|
|
31
35
|
toRateLimitError,
|
|
32
36
|
warnIfGatewayCostUndeclared
|
|
33
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-KGLMAIY3.js";
|
|
34
38
|
|
|
35
39
|
// src/config/model-equivalence.ts
|
|
36
40
|
var VARIANT_QUIRKS = /* @__PURE__ */ new Set(["small", "image"]);
|
|
@@ -404,6 +408,8 @@ var ResilientAdapter = class {
|
|
|
404
408
|
defaultCliTimeoutMs;
|
|
405
409
|
/** Inflight detection promise for coalescing concurrent calls (Issue #1423). */
|
|
406
410
|
detectionPromise;
|
|
411
|
+
/** The {@link gatewayDiscoveryGeneration} the current selection was made under (#6659). */
|
|
412
|
+
detectedAtGeneration = 0;
|
|
407
413
|
constructor(config) {
|
|
408
414
|
this.logger = config?.logger ?? createLogger({ component: "resilient-adapter" });
|
|
409
415
|
this.preferredCli = config?.preferredCli;
|
|
@@ -534,6 +540,16 @@ var ResilientAdapter = class {
|
|
|
534
540
|
}
|
|
535
541
|
// --- Private methods ---
|
|
536
542
|
async ensureAdapter() {
|
|
543
|
+
if (this.currentAdapter === void 0) {
|
|
544
|
+
await ensureGatewayDiscovered();
|
|
545
|
+
} else {
|
|
546
|
+
void ensureGatewayDiscovered();
|
|
547
|
+
}
|
|
548
|
+
if (this.currentAdapter !== void 0 && this.detectedAtGeneration !== gatewayDiscoveryGeneration()) {
|
|
549
|
+
this.currentAdapter = void 0;
|
|
550
|
+
this.currentSelection = void 0;
|
|
551
|
+
this.hasEverDetected = false;
|
|
552
|
+
}
|
|
537
553
|
if (this.currentAdapter !== void 0) {
|
|
538
554
|
return this.currentAdapter;
|
|
539
555
|
}
|
|
@@ -543,6 +559,7 @@ var ResilientAdapter = class {
|
|
|
543
559
|
return this.detectionPromise;
|
|
544
560
|
}
|
|
545
561
|
async detectAdapter() {
|
|
562
|
+
const generation = gatewayDiscoveryGeneration();
|
|
546
563
|
try {
|
|
547
564
|
this.logger.info("Detecting model adapter (lazy)");
|
|
548
565
|
const config = {
|
|
@@ -554,6 +571,7 @@ var ResilientAdapter = class {
|
|
|
554
571
|
};
|
|
555
572
|
const selection = await createAutoAdapter(config);
|
|
556
573
|
this.applySelection(selection);
|
|
574
|
+
this.detectedAtGeneration = generation;
|
|
557
575
|
return this.currentAdapter;
|
|
558
576
|
} catch (error) {
|
|
559
577
|
const message = getErrorMessage(error);
|
|
@@ -1050,4 +1068,4 @@ export {
|
|
|
1050
1068
|
getGlobalRegistry,
|
|
1051
1069
|
resetGlobalRegistry
|
|
1052
1070
|
};
|
|
1053
|
-
//# sourceMappingURL=chunk-
|
|
1071
|
+
//# sourceMappingURL=chunk-73Y7XRKL.js.map
|