-
Notifications
You must be signed in to change notification settings - Fork 10.6k
Expand file tree
/
Copy pathconnectionTest.ts
More file actions
3241 lines (3086 loc) · 113 KB
/
Copy pathconnectionTest.ts
File metadata and controls
3241 lines (3086 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Smoke tests for the Settings dialog. Two entry points:
//
// - testProviderConnection: posts a tiny "Reply with only: ok" request to
// a BYOK API endpoint and reports a categorized result.
// - testAgentConnection: spawns a Local CLI adapter with the same prompt,
// drives the existing stream parser through a collector sink, and treats
// assistant text as proof that the CLI can run unless the text is an
// explicit model-selection error.
//
// Both functions persist nothing — no project, no chat record, no
// media-config write. The intent is to give Settings a definite "your
// configuration works" answer without users having to send a real chat to
// discover that the API key, model, base URL, or CLI is broken.
//
// The streaming counterpart for chat lives in `server.ts` under the
// `/api/proxy/*/stream` routes; both paths share the base URL policy from
// contracts so Settings and daemon-side checks reject the same hosts.
import { spawn } from 'node:child_process';
import { promises as dnsPromises, lookup as dnsLookupCb } from 'node:dns';
import { promises as fsp } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Agent, EnvHttpProxyAgent, Socks5ProxyAgent } from 'undici';
import type { Dispatcher, Pool } from 'undici';
import {
applyAgentLaunchEnv,
getAgentDef,
resolveAgentLaunch,
spawnEnvForAgent,
} from './agents.js';
import {
createCommandInvocation,
mergeProxyAwareEnv,
resolveSystemProxyEnv,
} from '@open-design/platform';
import { attachAcpSession } from './agent-protocol/index.js';
import { attachPiRpcSession } from './agent-protocol/index.js';
import { attachDshProfileSession } from './agent-protocol/index.js';
import { createClaudeStreamHandler } from './runtimes/claude-stream.js';
import { diagnoseClaudeCliFailure } from './claude-diagnostics.js';
import { createCopilotStreamHandler } from './copilot-stream.js';
import { createJsonEventStreamHandler } from './runtimes/json-event-stream.js';
import { agentCliEnvForAgent, validateAgentCliEnv } from './app-config.js';
import {
antigravityAuthGuidance,
antigravityQuotaGuidance,
classifyAgentAuthFailure,
classifyAgentServiceFailure,
cursorAuthGuidance,
normalizeDeepSeekHarnessFailure,
probeAgentAuthStatus,
} from './runtimes/auth.js';
import { loadMmdRouteLaunchEnv } from './runtimes/mmd-routes.js';
import {
buildLegacyMaxTokensParam,
buildMaxCompletionTokensParam,
buildOpenAIChatTokenParam,
isAzureOpenAIHostname,
isUnsupportedMaxTokensError,
} from './integrations/openai-chat-token-params.js';
import { aihubmixHeaders } from './integrations/aihubmix.js';
import { aimlapiHeaders } from './integrations/aimlapi.js';
import type { AgentCliEnvPrefs } from './app-config.js';
import type { RuntimeAgentDef } from './runtimes/types.js';
import { preparePromptFileForAgent, type PreparedPromptFile } from './runtimes/prompt-file.js';
import { configuredAllowedInternalHosts } from './origin-validation.js';
import {
isAllowlistedInternalHost,
isBlockedExternalApiHostname,
isLoopbackApiHost,
validateBaseUrl,
type AgentTestRequest,
type BaseUrlValidationResult,
type ValidateBaseUrlOptions,
type ConnectionTestDiagnostics,
type ConnectionTestKind,
type ConnectionTestPhase,
type ConnectionTestProtocol,
type ConnectionTestResponse,
type ParsedBaseUrl,
type ProviderTestRequest,
} from '@open-design/contracts/api/connectionTest';
import { googleGenerateContentUrl } from './integrations/google-models.js';
import { readVelaCredentialRevision, resolveAmrProfile } from './integrations/vela.js';
import { amrModelLoadingCache } from './runtimes/amr-model-cache.js';
import { buildAmrModelCacheKey } from './runtimes/amr-model-probe.js';
import {
fetchVelaPresetModels,
fetchVelaRemoteModelsWithRetry,
} from './runtimes/defs/amr.js';
import {
getRememberedLiveModels,
preferFreshLiveModels,
resolveDefaultModelFromOptions,
resolveModelForAgent,
} from './runtimes/models.js';
import {
BYOK_OPENCODE_PROVIDER_ID,
buildOpenCodeByokProviderConfig,
} from './runtimes/byok-opencode.js';
export { validateBaseUrl } from '@open-design/contracts/api/connectionTest';
// DNS-aware companion to `validateBaseUrl`. The contracts-side check only
// inspects the literal hostname string, so a public DNS name pointing at
// internal infrastructure (`internal.example.com → 10.0.0.5`) slips through
// and the daemon ends up issuing a request to a private address on behalf of
// whichever caller supplied the base URL. Resolve the hostname and re-run
// the block-list against every address the system would actually connect to.
//
// Loopback is intentionally allowed for local LLM providers like Ollama; any
// hostname that resolves to a loopback address (including `*.localhost` per
// RFC 6761 and IPv4-mapped IPv6 loopback) follows that same carve-out.
//
// DNS lookup failures are *not* treated as a security signal — the caller is
// going to surface a connection error from `fetch` anyway, and turning a
// transient resolver hiccup into a 403 would just confuse users. The sync
// hostname check still rejected the obvious literal-IP cases before we ever
// got here.
export type DnsLookupAddress = { address: string; family: number };
export type DnsLookupFn = (hostname: string) => Promise<DnsLookupAddress[]>;
const defaultDnsLookup: DnsLookupFn = async (hostname) => {
const result = await dnsPromises.lookup(hostname, { all: true, family: 0 });
return result.map(({ address, family }) => ({ address, family }));
};
function looksLikeIpLiteral(hostname: string): boolean {
const host = hostname.startsWith('[') && hostname.endsWith(']')
? hostname.slice(1, -1)
: hostname;
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host)) return true;
return host.includes(':');
}
export async function validateBaseUrlResolved(
baseUrl: string,
lookup: DnsLookupFn = defaultDnsLookup,
options: ValidateBaseUrlOptions = {},
): Promise<BaseUrlValidationResult> {
const sync = validateBaseUrl(baseUrl, options);
if (sync.error || !sync.parsed) return sync;
const hostname = sync.parsed.hostname.toLowerCase();
// When forbidLoopback is set, do NOT short-circuit on loopback — let it
// fall through to the block check (issue #5478).
if (!options.forbidLoopback && isLoopbackApiHost(hostname)) return sync;
// Issue #3225 — an operator who trusts this hostname has opted it out of the
// guard entirely, so skip the resolved-IP block even though it points into
// private space. The sync check above already honored a literal-IP allowlist
// entry; this covers the hostname-that-resolves-private case.
if (isAllowlistedInternalHost(hostname, options.allowedInternalHosts)) return sync;
if (looksLikeIpLiteral(hostname)) return sync;
let addresses: DnsLookupAddress[];
try {
addresses = await lookup(hostname);
} catch {
// When forbidLoopback is set (attacker-controllable asset URLs), a DNS
// lookup failure must fail closed. An attacker who controls the resolver
// can make the validation lookup throw (ENOTFOUND / ETIMEOUT / SERVFAIL)
// and then answer loopback for the fetch-time lookup, bypassing the guard.
// (issue #5478)
if (options.forbidLoopback) {
return { error: 'DNS resolution failed for asset URL', forbidden: true };
}
return sync;
}
for (const addr of addresses) {
const ip = String(addr.address).toLowerCase();
// When forbidLoopback is set (asset download URLs from issue #5478),
// a DNS name that resolves to loopback is just as dangerous as a
// literal loopback host — reject it instead of skipping.
if (isLoopbackApiHost(ip)) {
if (options.forbidLoopback) {
return {
error: `DNS-resolved loopback address blocked (${ip})`,
forbidden: true,
};
}
continue;
}
// A resolved address the operator explicitly allowlisted (they listed the
// IP rather than the hostname) is permitted; everything else in private
// space is still blocked.
if (isAllowlistedInternalHost(ip, options.allowedInternalHosts)) continue;
if (isBlockedExternalApiHostname(ip)) {
return { error: 'Internal IPs blocked', forbidden: true };
}
}
// Attach validated addresses so the caller can pin the actual fetch to them.
// This prevents DNS rebinding: without pinning, the attacker's DNS can return
// a public IP here and then 127.0.0.1 at fetch time, so the daemon connects
// to loopback despite the validation having passed (issue #5478).
return { ...sync, resolvedAddresses: addresses };
}
/**
* Validate a base URL that the USER deliberately configured as a provider
* endpoint (connection test, model discovery, BYOK chat dispatch). Identical
* to {@link validateBaseUrlResolved} except it honors the operator's
* `OD_ALLOWED_INTERNAL_HOSTS` allowlist (issue #3225), so an internally hosted
* gateway on an RFC1918 address can be reached when — and only when — the
* operator opted in.
*
* INVARIANT: use this ONLY for user-configured endpoints. URLs that arrive
* inside an upstream response (image/video download links) are
* attacker-controllable and MUST stay on the strict {@link assertExternalAssetUrl}
* / {@link validateBaseUrlResolved} path, which never consults the allowlist.
*/
export function validateUserProviderBaseUrl(
baseUrl: string,
lookup: DnsLookupFn = defaultDnsLookup,
): Promise<BaseUrlValidationResult> {
return validateBaseUrlResolved(baseUrl, lookup, {
allowedInternalHosts: configuredAllowedInternalHosts(),
});
}
/**
* SSRF guard for asset URLs handed back inside a successful API
* response — typically a `data.url` or `data.video_url` that points
* at the gateway's CDN, but is attacker-controllable when the
* upstream gateway is compromised or misconfigured. Routes the URL
* through `validateBaseUrlResolved` (DNS-resolve → reject loopback,
* RFC1918, link-local, CGNAT, metadata-service IPs) and returns a
* discriminated union so callers don't have to repeat the
* `validated.error || !validated.parsed` plumbing.
*
* Two callers today:
* - `byok-tools.ts` for the chat-tool image/video downloads
* - `media.ts` `renderSenseAudioImage` for the CLI agent path
* Both hand the URL straight to `fetch(...)` next, so pair this
* guard with `redirect: 'error'` on the fetch to also block a
* 3xx hop into private space.
*
* Returns the DNS-resolved addresses that passed validation on the `ok` branch
* so callers (e.g. {@link assertAndFetchExternalAsset}) can pin the actual
* connection to those addresses and prevent DNS rebinding (issue #5478).
*/
export async function assertExternalAssetUrl(
rawUrl: string,
lookup?: DnsLookupFn,
): Promise<
| { ok: true; resolvedAddresses?: ReadonlyArray<{ address: string; family: number }> }
| { ok: false; error: string }
> {
if (typeof rawUrl !== 'string' || !rawUrl) {
return { ok: false, error: 'empty download url' };
}
// Asset URLs come from upstream API responses (data.url / data.video_url)
// and are attacker-controllable. They MUST NOT point at loopback or
// internal addresses, regardless of operator allowlists (issue #5478).
const validated = await validateBaseUrlResolved(rawUrl, lookup, {
forbidLoopback: true,
});
if (validated.error || !validated.parsed) {
return {
ok: false,
error: validated.forbidden
? `blocked download url (${validated.error ?? 'internal address'})`
: `invalid download url: ${validated.error ?? 'unknown reason'}`,
};
}
// Only include resolvedAddresses when present — exactOptionalPropertyTypes
// forbids assigning `undefined` to an optional property.
if (validated.resolvedAddresses) {
return { ok: true, resolvedAddresses: validated.resolvedAddresses };
}
return { ok: true };
}
/**
* Connection-time DNS validator for asset-download requests. Wraps `dns.lookup`
* and rejects any resolved address that is loopback, RFC1918, link-local,
* CGNAT, metadata-service, or multicast — the same predicate used during
* pre-validation. Installed as the Undici Agent's `connect.lookup` so the
* address we validate IS the address the socket connects to, closing the
* DNS-rebinding / TOCTOU gap that a separate pre-validation lookup leaves open
* (issue #5478). Same pattern as `brands/safe-fetch.ts` and
* `plugins/plugin-asset-cache.ts`.
*
* Exported so the guard can be unit-tested without a live server.
*/
export function createAssetValidatingLookup(
lookupImpl: typeof dnsLookupCb = dnsLookupCb,
): (hostname: string, options: unknown, callback: (...args: unknown[]) => void) => void {
return (
hostname: string,
options: unknown,
callback: (...args: unknown[]) => void,
): void => {
const cb = (typeof options === 'function' ? options : callback) as (
err: Error | null,
address?: unknown,
family?: number,
) => void;
const opts = (typeof options === 'function' ? {} : (options ?? {})) as Record<string, unknown>;
lookupImpl(hostname, opts as never, (err, address, family) => {
if (err) return cb(err);
const list = Array.isArray(address) ? address : [{ address, family }];
for (const entry of list) {
const addr = typeof entry === 'string' ? entry : (entry as { address: string }).address;
if (isLoopbackApiHost(String(addr)) || isBlockedExternalApiHostname(String(addr))) {
return cb(new Error(`asset host resolves to non-public address: ${addr}`));
}
}
return cb(null, address, family);
});
};
}
// Long-lived dispatcher reused across calls. A per-request Agent leaks
// keep-alive sockets; a shared dispatcher avoids that while still pinning the
// connection-time validating lookup (same approach as plugin-asset-cache.ts).
// Used by `createAssetValidatingLookup` consumers in production; the default
// fetch in `assertAndFetchExternalAsset` is `globalThis.fetch` so test stubs
// still intercept.
const assetDispatcher = new Agent({
connect: { lookup: createAssetValidatingLookup() as never },
});
/**
* Test-visible accessor for the shared asset-validating dispatcher attached by
* `assertAndFetchExternalAsset`. Tests key dispatcher assertions on the asset
* URL and compare against this exact instance (`toBe`), so a regression that
* reverts to forwarding the caller's turn-proxy dispatcher on the asset hop
* fails loudly (issue #5478).
*/
export function getAssetValidatingDispatcher(): NonNullable<RequestInit['dispatcher']> {
return assetDispatcher as unknown as NonNullable<RequestInit['dispatcher']>;
}
/**
* Validate an upstream-controlled asset URL and fetch it with the SSRF guard
* pinned through redirects and DNS resolution. Runs `assertExternalAssetUrl`
* on the literal URL (fail-closed on DNS errors), forces `redirect: 'error'`
* (blocking a 3xx hop into private space), and routes the fetch through a
* long-lived Undici dispatcher whose connection-time `lookup` rejects any
* non-public address — so even if an attacker's DNS returns a public address
* during pre-validation and loopback at connect time, the socket is refused
* (issue #5478).
*
* For non-IP-literal hostnames, if DNS validation did not attach a vetted
* address set (e.g., lookup failure), the function throws rather than falling
* back to an unpinned fetch. IP literals are safe to fetch unpinned because
* they were validated synchronously and have no hostname to rebind.
*
* Throws on a blocked host or unpinned-fetch refusal. Callers keep their own
* `!resp.ok` HTTP-status handling. The forced `redirect` is spread last so it
* overrides any value the caller passed in `init`.
*/
export async function assertAndFetchExternalAsset(
url: string,
init: RequestInit = {},
lookup?: DnsLookupFn,
fetchImpl: typeof fetch = fetch,
): Promise<Response> {
const check = await assertExternalAssetUrl(url, lookup);
if (!check.ok) throw new Error(check.error);
// Determine whether the hostname is an IP literal. If so, the synchronous
// validation already vetted it — no DNS rebind is possible.
let parsedUrl: URL;
try {
parsedUrl = new URL(url);
} catch {
throw new Error(`invalid asset url: ${url}`);
}
const hostname = parsedUrl.hostname.toLowerCase();
const isIpLiteral = looksLikeIpLiteral(hostname);
// For non-IP-literal hostnames, require validated resolved addresses. If
// they are missing (DNS lookup failed and was caught → fail-closed in
// validateBaseUrlResolved), never fall back to an unpinned fetch — that
// would allow the attacker to rebind at fetch time (issue #5478).
if (!isIpLiteral && (!check.resolvedAddresses || check.resolvedAddresses.length === 0)) {
throw new Error('asset URL hostname was not DNS-validated — refusing unpinned fetch');
}
// Route through the long-lived asset dispatcher whose connection-time lookup
// rejects non-public addresses. The dispatcher is attached to the init object
// so injected fetch stubs (vi.stubGlobal) still see redirect:'error' and
// can ignore dispatcher, while production globalThis.fetch (Node/undici)
// uses it to refuse a connect-time rebind to loopback/metadata (issue #5478).
// Same pattern as plugins/plugin-asset-cache.ts safeExternalFetch.
const requestInit: RequestInit = { ...init, redirect: 'error' };
(requestInit as { dispatcher?: unknown }).dispatcher = assetDispatcher;
return fetchImpl(url, requestInit);
}
// Aggressive but not punitive — happy paths usually return in under 2 s.
// Override with OD_CONNECTION_TEST_PROVIDER_TIMEOUT_MS for slow networks
// or distant providers; invalid values fall back to the default.
const DEFAULT_PROVIDER_TIMEOUT_MS = 12_000;
const LOOPBACK_NO_PROXY_TOKENS = ['localhost', '127.0.0.1', '[::1]'] as const;
// CLI boot time is dominated by adapter auth/session restore; the heavy
// adapters (Codex, Cursor Agent) regularly take 5–10 s on a cold first
// run, so 45 s leaves headroom without making a hung child invisible.
// Override with OD_CONNECTION_TEST_AGENT_TIMEOUT_MS.
const DEFAULT_AGENT_TIMEOUT_MS = 45_000;
const AGENT_STDOUT_DRAIN_MS = 25;
// Node's `setTimeout` silently clamps any delay above this to ~1 ms
// (with a TimeoutOverflowWarning), so an override meant to *extend*
// the budget — e.g. `OD_CONNECTION_TEST_AGENT_TIMEOUT_MS=3000000000` —
// would actually make every connection test fail almost immediately.
// Reject above the cap so the safety timeout cannot be accidentally
// disarmed by an oversized env value.
const MAX_CONNECTION_TEST_TIMEOUT_MS = 2_147_483_647;
export function resolveConnectionTestTimeoutMs(
key: 'OD_CONNECTION_TEST_PROVIDER_TIMEOUT_MS' | 'OD_CONNECTION_TEST_AGENT_TIMEOUT_MS',
fallback: number,
env: NodeJS.ProcessEnv = process.env,
): number {
const raw = env[key];
if (raw === undefined || raw === '') return fallback;
const n = Number(raw);
if (!Number.isSafeInteger(n) || n < 1 || n > MAX_CONNECTION_TEST_TIMEOUT_MS) {
console.warn(
`connection-test: ignoring ${key}=${JSON.stringify(raw)} (must be a positive integer between 1 and ${MAX_CONNECTION_TEST_TIMEOUT_MS} ms); using ${fallback}ms`,
);
return fallback;
}
return n;
}
function providerTimeoutMs(): number {
return resolveConnectionTestTimeoutMs(
'OD_CONNECTION_TEST_PROVIDER_TIMEOUT_MS',
DEFAULT_PROVIDER_TIMEOUT_MS,
);
}
function agentTimeoutMs(): number {
return resolveConnectionTestTimeoutMs(
'OD_CONNECTION_TEST_AGENT_TIMEOUT_MS',
DEFAULT_AGENT_TIMEOUT_MS,
);
}
export function mergeNoProxyWithLoopbackDefaults(noProxy: string | undefined): string | null {
if (noProxy?.split(/[\s,]+/).some((token) => token.trim() === '*')) return '*';
const seen = new Set<string>();
const values: string[] = [];
for (const rawToken of [
...(noProxy ? noProxy.split(/[\s,]+/) : []),
...LOOPBACK_NO_PROXY_TOKENS,
]) {
const token = rawToken.trim() === '::1' ? '[::1]' : rawToken.trim();
if (!token || seen.has(token)) continue;
seen.add(token);
values.push(token);
}
return values.length > 0 ? values.join(',') : null;
}
function defaultPortForProtocol(protocol: string): string {
if (protocol === 'http:') return '80';
if (protocol === 'https:') return '443';
return '';
}
function splitNoProxyHostAndPort(token: string): { host: string; port: string } {
const trimmed = token.trim();
if (!trimmed) return { host: '', port: '' };
if (trimmed.startsWith('[')) {
const closingBracket = trimmed.indexOf(']');
if (closingBracket === -1) return { host: trimmed.toLowerCase(), port: '' };
const host = trimmed.slice(0, closingBracket + 1).toLowerCase();
const port = trimmed.slice(closingBracket + 1).replace(/^:/, '');
return { host, port };
}
const firstColon = trimmed.indexOf(':');
const lastColon = trimmed.lastIndexOf(':');
if (firstColon !== -1 && firstColon === lastColon) {
return {
host: trimmed.slice(0, firstColon).toLowerCase(),
port: trimmed.slice(firstColon + 1),
};
}
return { host: trimmed.toLowerCase(), port: '' };
}
function noProxyTokenMatchesUrl(token: string, url: URL): boolean {
const trimmed = token.trim();
if (!trimmed) return false;
if (trimmed === '*') return true;
if (trimmed === '<local>') return !url.hostname.includes('.') && !url.hostname.includes(':');
const { host, port } = splitNoProxyHostAndPort(trimmed.replace(/^\*\./, '.'));
if (!host) return false;
const normalizedHost = host === '::1' ? '[::1]' : host;
const hostname = url.hostname.toLowerCase();
const matchesHost = normalizedHost.startsWith('.')
? hostname === normalizedHost.slice(1) || hostname.endsWith(normalizedHost)
: hostname === normalizedHost || hostname.endsWith(`.${normalizedHost}`);
if (!matchesHost) return false;
if (!port) return true;
return (url.port || defaultPortForProtocol(url.protocol)) === port;
}
function shouldBypassProxyForUrl(target: string | URL, noProxy: string | null): boolean {
if (!noProxy) return false;
let url: URL;
try {
url = target instanceof URL ? target : new URL(target);
} catch {
return false;
}
return noProxy.split(/[\s,]+/).some((token) => noProxyTokenMatchesUrl(token, url));
}
function socksProxyAgentOptions(
options: Pool.Options,
): ConstructorParameters<typeof Socks5ProxyAgent>[1] {
return {
...(options.bodyTimeout === undefined ? {} : { bodyTimeout: options.bodyTimeout }),
...(options.headersTimeout === undefined ? {} : { headersTimeout: options.headersTimeout }),
};
}
class NoProxyAwareSocksProxyAgent {
private readonly directAgent: Agent;
private readonly socksAgent: Socks5ProxyAgent;
private readonly socksDispatchTimeouts: Pick<Dispatcher.DispatchOptions, 'bodyTimeout' | 'headersTimeout'>;
constructor(
private readonly noProxy: string | null,
socksProxy: string,
options: Pool.Options,
) {
this.directAgent = new Agent(options as ConstructorParameters<typeof Agent>[0]);
this.socksAgent = new Socks5ProxyAgent(socksProxy, socksProxyAgentOptions(options));
this.socksDispatchTimeouts = {
...(options.bodyTimeout === undefined ? {} : { bodyTimeout: options.bodyTimeout }),
...(options.headersTimeout === undefined
? {}
: { headersTimeout: options.headersTimeout }),
};
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const origin = options.origin;
const targetUrl =
typeof origin === 'string' || origin instanceof URL
? new URL(options.path, origin)
: null;
const dispatcher =
targetUrl && shouldBypassProxyForUrl(targetUrl, this.noProxy)
? this.directAgent
: this.socksAgent;
return dispatcher.dispatch(
dispatcher === this.socksAgent ? { ...this.socksDispatchTimeouts, ...options } : options,
handler,
);
}
async close(): Promise<void> {
await Promise.all([this.directAgent.close(), this.socksAgent.close()]);
}
async destroy(error?: Error | null): Promise<void> {
await Promise.all([
this.directAgent.destroy(error ?? null),
this.socksAgent.destroy(error ?? null),
]);
}
}
class NoProxyAwareEnvProxyAgent {
private readonly directAgent: Agent;
constructor(
private readonly noProxy: string,
private readonly proxyAgent: EnvHttpProxyAgent,
options: Pool.Options,
) {
this.directAgent = new Agent(options as ConstructorParameters<typeof Agent>[0]);
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const origin = options.origin;
const targetUrl =
typeof origin === 'string' || origin instanceof URL
? new URL(options.path, origin)
: null;
return (targetUrl && shouldBypassProxyForUrl(targetUrl, this.noProxy) ? this.directAgent : this.proxyAgent).dispatch(
options,
handler,
);
}
async close(): Promise<void> {
await Promise.all([this.directAgent.close(), this.proxyAgent.close()]);
}
async destroy(error?: Error | null): Promise<void> {
await Promise.all([
this.directAgent.destroy(error ?? null),
this.proxyAgent.destroy(error ?? null),
]);
}
}
class NoProxyAwareMixedProxyAgent {
private readonly directAgent: Agent;
private readonly proxyAgent: EnvHttpProxyAgent;
private readonly socksAgent: Socks5ProxyAgent;
private readonly socksDispatchTimeouts: Pick<Dispatcher.DispatchOptions, 'bodyTimeout' | 'headersTimeout'>;
constructor(
private readonly noProxy: string | null,
private readonly hasHttpProxy: boolean,
private readonly hasHttpsProxy: boolean,
proxyOptions: ConstructorParameters<typeof EnvHttpProxyAgent>[0],
socksProxy: string,
options: Pool.Options,
) {
this.directAgent = new Agent(options as ConstructorParameters<typeof Agent>[0]);
this.proxyAgent = new EnvHttpProxyAgent(proxyOptions);
this.socksAgent = new Socks5ProxyAgent(socksProxy, socksProxyAgentOptions(options));
this.socksDispatchTimeouts = {
...(options.bodyTimeout === undefined ? {} : { bodyTimeout: options.bodyTimeout }),
...(options.headersTimeout === undefined
? {}
: { headersTimeout: options.headersTimeout }),
};
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const origin = options.origin;
const targetUrl =
typeof origin === 'string' || origin instanceof URL
? new URL(options.path, origin)
: null;
if (targetUrl && shouldBypassProxyForUrl(targetUrl, this.noProxy)) {
return this.directAgent.dispatch(options, handler);
}
if (
targetUrl && ((targetUrl.protocol === 'http:' && this.hasHttpProxy) ||
(targetUrl.protocol === 'https:' && this.hasHttpsProxy))
) {
return this.proxyAgent.dispatch(options, handler);
}
return this.socksAgent.dispatch({ ...this.socksDispatchTimeouts, ...options }, handler);
}
async close(): Promise<void> {
await Promise.all([this.directAgent.close(), this.proxyAgent.close(), this.socksAgent.close()]);
}
async destroy(error?: Error | null): Promise<void> {
await Promise.all([
this.directAgent.destroy(error ?? null),
this.proxyAgent.destroy(error ?? null),
this.socksAgent.destroy(error ?? null),
]);
}
}
type ConnectionTestProxyDispatcher =
| EnvHttpProxyAgent
| NoProxyAwareEnvProxyAgent
| NoProxyAwareMixedProxyAgent
| NoProxyAwareSocksProxyAgent;
function envProxyAgentOptions(
options: Pool.Options,
httpProxy: string | undefined,
httpsProxy: string | undefined,
noProxy: string | null,
): ConstructorParameters<typeof EnvHttpProxyAgent>[0] {
return {
...options,
...(httpProxy ? { httpProxy } : {}),
...(httpsProxy ? { httpsProxy } : {}),
...(noProxy ? { noProxy } : {}),
};
}
function buildConnectionTestProxyDispatcher(
env: NodeJS.ProcessEnv = process.env,
options: Pool.Options = {},
): ConnectionTestProxyDispatcher | null {
const proxyEnv = mergeProxyAwareEnv(
process.platform,
resolveSystemProxyEnv(),
env,
);
const allProxy = proxyEnv.ALL_PROXY ?? proxyEnv.all_proxy;
const socksProxy = socksProxyUrl(allProxy);
const httpProxyFromAll = isHttpOrHttpsProxy(allProxy);
const httpProxy = proxyEnv.HTTP_PROXY ?? proxyEnv.http_proxy ?? httpProxyFromAll;
const httpsProxy = proxyEnv.HTTPS_PROXY ?? proxyEnv.https_proxy ?? httpProxyFromAll;
const noProxy = mergeNoProxyWithLoopbackDefaults(proxyEnv.NO_PROXY ?? proxyEnv.no_proxy);
const proxyOptions = envProxyAgentOptions(options, httpProxy, httpsProxy, noProxy);
if (socksProxy && (httpProxy || httpsProxy) && (!httpProxy || !httpsProxy)) {
return new NoProxyAwareMixedProxyAgent(
noProxy,
Boolean(httpProxy),
Boolean(httpsProxy),
proxyOptions,
socksProxy,
options,
);
}
if (!httpProxy && !httpsProxy && socksProxy) {
return new NoProxyAwareSocksProxyAgent(noProxy, socksProxy, options);
}
if (!httpProxy && !httpsProxy) return null;
const proxyAgent = new EnvHttpProxyAgent(proxyOptions);
return noProxy?.split(/[\s,]+/).some((token) => token.trim() === '<local>')
? new NoProxyAwareEnvProxyAgent(noProxy, proxyAgent, options)
: proxyAgent;
}
function isHttpOrHttpsProxy(proxyUrl: string | undefined): string | undefined {
const trimmed = proxyUrl?.trim();
if (!trimmed) return undefined;
try {
const { protocol } = new URL(trimmed);
return protocol === 'http:' || protocol === 'https:' ? trimmed : undefined;
} catch {
return undefined;
}
}
function socksProxyUrl(proxyUrl: string | undefined): string | undefined {
const trimmed = proxyUrl?.trim();
if (!trimmed) return undefined;
try {
const url = new URL(trimmed);
if (url.protocol === 'socks:' || url.protocol === 'socks5:') return trimmed;
if (url.protocol === 'socks5h:') {
url.protocol = 'socks5:';
return url.toString();
}
return undefined;
} catch {
return undefined;
}
}
export function proxyDispatcherRequestInit(
env: NodeJS.ProcessEnv = process.env,
options: Pool.Options = {},
): {
close(): Promise<void>;
requestInit: Pick<RequestInit, 'dispatcher'>;
} {
const dispatcher = buildConnectionTestProxyDispatcher(env, options);
if (dispatcher == null) {
return {
async close() {},
requestInit: {},
};
}
return {
close: () => dispatcher.close(),
requestInit: {
dispatcher: dispatcher as unknown as NonNullable<RequestInit['dispatcher']>,
},
};
}
const AGENT_COMPLETION_DEBOUNCE_MS = 500;
const AGENT_KILL_GRACE_MS = 2_000;
// Truncates the assistant reply we surface in the success copy so a
// chatty model can't dump kilobytes into the inline status node.
const SAMPLE_MAX_CHARS = 120;
// Generation budget for the smoke prompt. Keep this small, but not tiny:
// reasoning models can spend the first few dozen tokens in hidden reasoning
// before producing a visible `ok`.
const PROVIDER_MAX_TOKENS = 100;
const SMOKE_PROMPT = 'Reply with only: ok';
function formatPromptForAgentStdin(
def: Pick<RuntimeAgentDef, 'promptInputFormat'>,
prompt: string,
): string {
const promptInputFormat = def.promptInputFormat ?? 'text';
if (promptInputFormat === 'stream-json') {
return `${JSON.stringify({
type: 'user',
message: {
role: 'user',
content: [{ type: 'text', text: prompt }],
},
})}\n`;
}
return prompt;
}
function codexExecutableGuidance(
agentId: string,
configuredOverridePath: string | null,
pathResolvedPath: string | null,
): string {
if (
agentId !== 'codex' ||
!configuredOverridePath ||
!pathResolvedPath ||
configuredOverridePath === pathResolvedPath
) {
return '';
}
return ` Configured Codex path failed: ${configuredOverridePath}. OpenDesign also detected a PATH Codex CLI at ${pathResolvedPath}. Update CODEX_BIN or clear the custom path to use the detected binary.`;
}
function codexExecutableFallbackSuccessDetail(
configuredOverridePath: string,
pathResolvedPath: string,
): string {
return `Configured Codex path failed: ${configuredOverridePath}. This test succeeded with the PATH Codex CLI at ${pathResolvedPath}. Update CODEX_BIN or clear the custom path to use the detected binary.`;
}
function codexConfiguredPathSuccessDetail(
configuredOverridePath: string,
): string {
return `This test used the configured Codex path: ${configuredOverridePath}.`;
}
function codexInvalidConfiguredPathFallbackDetail(
configuredValue: string,
pathResolvedPath: string,
): string {
return `Configured Codex path is invalid or not executable: ${configuredValue}. This test used the PATH Codex CLI at ${pathResolvedPath}. Update CODEX_BIN or clear the custom path to use the detected binary.`;
}
function stripCodexBinOverride(
prefs: AgentCliEnvPrefs | undefined,
): AgentCliEnvPrefs | undefined {
if (!prefs?.codex?.CODEX_BIN) return prefs;
const nextCodex = { ...prefs.codex };
delete nextCodex.CODEX_BIN;
const next: AgentCliEnvPrefs = {
...prefs,
codex: nextCodex,
};
if (Object.keys(nextCodex).length === 0) delete next.codex;
return Object.keys(next).length > 0 ? next : undefined;
}
// Catches `Bearer …`, `x-api-key`/`api-key`/`x-goog-api-key` headers, and
// `?key=…` query strings. The provider helpers all funnel error text
// through this before logging; if a vendor surfaces the key in body text
// (some do for 401s), it stays out of the daemon log too.
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function redactSecrets(
text: string,
exactSecrets: Array<string | undefined | null> = [],
): string {
if (typeof text !== 'string' || text.length === 0) return '';
let redacted = text
.replace(/Bearer\s+[A-Za-z0-9_\-.+/=]+/gi, 'Bearer [REDACTED]')
.replace(/(x-api-key|api-key|x-goog-api-key)\s*[:=]\s*[^\s,;"']+/gi, '$1: [REDACTED]')
.replace(/([?&]key=)[^&\s]+/gi, '$1[REDACTED]');
for (const secret of exactSecrets) {
if (typeof secret !== 'string' || secret.length === 0) continue;
redacted = redacted.replace(new RegExp(escapeRegExp(secret), 'g'), '[REDACTED]');
}
return redacted;
}
type ProviderConnectionInput = ProviderTestRequest & { signal?: AbortSignal };
type AgentConnectionInput = AgentTestRequest & { signal?: AbortSignal };
function appendVersionedApiPath(baseUrl: string, suffix: string): string {
const url = new URL(baseUrl);
const pathname = url.pathname.replace(/\/+$/, '');
url.pathname = /\/v\d+(\/|$)/.test(pathname)
? `${pathname}${suffix}`
: `${pathname}/v1${suffix}`;
return url.toString();
}
function truncateSample(text: unknown): string {
if (typeof text !== 'string') return '';
const trimmed = text.replace(/\s+/g, ' ').trim();
if (trimmed.length <= SAMPLE_MAX_CHARS) return trimmed;
return `${trimmed.slice(0, SAMPLE_MAX_CHARS - 1)}…`;
}
export function isSmokeOkReply(text: unknown): boolean {
return typeof text === 'string' && text.trim().toLowerCase() === 'ok';
}
function isLikelyModelErrorText(text: string): boolean {
return (
/model/i.test(text) &&
/(not found|not exist|does not exist|unknown|invalid|unsupported|not supported|not have access|no access|issue with the selected model)/i.test(
text,
)
);
}
function isLikelyAuthErrorText(text: string): boolean {
return /(?:api[_ -]?key|x-goog-api-key|unauthorized|unauthenticated|permission denied|invalid credentials|authentication credentials|access denied|invalid key)/i.test(
text,
);
}
const GOOGLE_GEMINI_DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com';
function normalizeProviderTestInput(
input: ProviderConnectionInput,
): ProviderConnectionInput {
const baseUrl = String(input.baseUrl ?? '').trim();
if (input.protocol === 'google' && !baseUrl) {
return { ...input, baseUrl: GOOGLE_GEMINI_DEFAULT_BASE_URL };
}
return input;
}
function googleBaseUrlMismatchDetail(hostname: string): string | null {
if (hostname === 'api.anthropic.com' || hostname === 'api.openai.com') {
return `Base URL points to ${hostname}. For Google Gemini use ${GOOGLE_GEMINI_DEFAULT_BASE_URL}.`;
}
return null;
}
function smokeFailureDetail(sample: string): string {
return sample
? `Expected smoke test reply "ok"; got "${sample}"`
: 'Provider returned a 2xx response without assistant text';
}
function inspectProviderCompletion(
protocol: ConnectionTestProtocol,
data: unknown,
requestedModel: string,
enforceResponseModel: boolean,
): { valid: boolean; sample?: string; kind?: ConnectionTestKind; detail?: string } {
const obj = data && typeof data === 'object' ? data as Record<string, unknown> : null;
if (!obj) return { valid: false };
if (
protocol === 'openai' ||
protocol === 'azure' ||
protocol === 'senseaudio' ||
protocol === 'aihubmix' ||
protocol === 'aimlapi'
) {
const responseModel = typeof obj.model === 'string' ? obj.model : '';
if (
// AIHubMix is omitted from the strict response-model check (like Azure):
// its gateway routes by model name and may echo a normalized id.
(protocol === 'openai' || protocol === 'senseaudio') &&
enforceResponseModel &&
responseModel &&
requestedModel &&
responseModel !== requestedModel
) {
return {
valid: false,
kind: 'not_found_model',
detail: `Provider responded with model "${responseModel}" instead of requested "${requestedModel}".`,
};
}
const choices = obj.choices;
if (!Array.isArray(choices) || choices.length === 0) return { valid: false };
const first = choices[0] as { finish_reason?: unknown } | undefined;
const finishReason =
typeof first?.finish_reason === 'string' ? first.finish_reason : '';
return {
valid: true,
sample: finishReason
? `valid completion (${finishReason})`
: 'valid completion',
};
}
if (protocol === 'anthropic') {
return {
valid:
Array.isArray((obj as { content?: unknown }).content) ||
typeof (obj as { stop_reason?: unknown }).stop_reason === 'string',
sample: 'valid completion',
};
}
if (protocol === 'google') {
return {
valid: Array.isArray((obj as { candidates?: unknown }).candidates),
sample: 'valid completion',
};
}