-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_router.mjs
More file actions
733 lines (677 loc) · 28.6 KB
/
Copy pathmodel_router.mjs
File metadata and controls
733 lines (677 loc) · 28.6 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
import crypto from "crypto";
import net from "net";
function env(name, fallback = "") {
const v = process.env[name];
return (v === undefined || v === null || String(v).trim() === "") ? fallback : String(v);
}
function normalizeBackend(value) {
const raw = String(value ?? "").trim().toLowerCase();
if (raw === "openrouter") return "openai_compat";
if (raw === "gemini" || raw === "openai_compat") return raw;
return "";
}
function normalizeId(value, fallback = "") {
const trimmed = String(value ?? "").trim();
if (!trimmed) return fallback;
const raw = trimmed.toLowerCase().replace(/[^a-z0-9_.:-]+/g, "_").replace(/^_+|_+$/g, "");
return raw || trimmed;
}
function defaultOllamaBaseUrl() {
return String(env("OLLAMA_BASE_URL", "")).trim() || "http://127.0.0.1:11434/v1";
}
function hostnameForBaseUrl(baseUrl) {
try {
return new URL(String(baseUrl || "").trim()).hostname;
} catch {
return "";
}
}
function hostMatches(host, suffix) {
const h = String(host || "").trim().toLowerCase();
const s = String(suffix || "").trim().toLowerCase();
return h === s || h.endsWith(`.${s}`);
}
export const VALID_DATA_BOUNDARIES = Object.freeze([
"google_gemini_api",
"openai_compatible_api",
"local_machine",
"private_lan",
"internal_only",
"filtered_carryover",
"none",
]);
export const VALID_COST_BANDS = Object.freeze([
"free_local",
"free",
"low",
"standard",
"unknown",
]);
export const VALID_MODEL_ORIGIN_RISKS = Object.freeze([
"low",
"medium",
"high",
"unknown",
]);
export const VALID_BLOCKED_REASONS = Object.freeze([
"local_offline_cloud_blocked",
"private_zone_cloud_disallowed",
"redirect_to_cloud_disallowed",
"provider_network_offline",
"provider_http_error",
"chat_backend_not_configured",
"no_model_execution",
"tool_only_no_model",
"provider_call_failed",
"provider_execution_failed",
"post_model_parse_failed",
"post_model_policy_failed",
"post_model_write_failed",
"invalid_configuration",
"fallback_paused_global_limit",
"fallback_paused_conversation_limit",
"invalid_url_format",
"trust_zone_blocks_repo_retrieval",
"security_exception_non_loopback",
"security_exception_non_private_lan",
"other",
]);
/**
* 8-division router roster. This is route metadata, not operator authority.
*/
export const EIGHT_DIVISIONS_ROSTER = Object.freeze({
DIV_I: {
id: "DIV_I",
name: "Division I: Non-Transformer & Continuous Dynamics",
roles: {
liquid_dynamics_critic: {
primary: "liquid-ai/lfm-40b",
fallbacks: ["gemma3:4b"],
description: "Continuous-time state and sequence dynamics modeling",
},
},
},
DIV_II: {
id: "DIV_II",
name: "Division II: Program Synthesis & Code Foundations",
roles: {
program_synthesis_specialist: { primary: "poolside/laguna", fallbacks: ["qwen-2.5-coder-32b", "qwen2.5-coder:7b"], description: "Execution-guided program synthesis" },
code_synthesizer_32b: { primary: "qwen-2.5-coder-32b", fallbacks: ["codestral-22b", "qwen2.5-coder:7b"], description: "Massive multi-file code synthesis" },
devstral_specialist: { primary: "codestral-22b", fallbacks: ["yi-coder", "qwen2.5-coder:7b"], description: "Codebase refactoring and bug hunting" },
repository_ingestor: { primary: "yi-coder", fallbacks: ["magic-dev", "qwen2.5-coder:7b"], description: "128k long-context cross-file dependency mapping" },
technical_search_engineer: { primary: "phind-34b", fallbacks: ["starcoder2-15b"], description: "Technical Q&A and algorithm synthesis" },
python_script_automator: { primary: "wizardcoder-34b", fallbacks: ["qwen2.5-coder:7b"], description: "Python and automation script specialist" },
bigcode_foundation: { primary: "starcoder2-15b", fallbacks: ["codegemma-7b"], description: "Open-community code generation foundation" },
local_code_probe: { primary: "codegemma-7b", fallbacks: ["qwen2.5-coder:7b"], description: "Lightweight Google open code model probe" },
junsong_hf_specialist: { primary: "junsong-hf", fallbacks: ["codegemma-7b"], description: "Fine-tuned open-source code & reasoning checkpoints" },
},
},
DIV_III: {
id: "DIV_III",
name: "Division III: Adversarial & Security Red-Team",
roles: {
adversarial_critic: { primary: "x-ai/grok-2", fallbacks: ["nvidia/nemotron-70b", "llama-audit:latest"], description: "Unfiltered edge-case hunting and security auditing" },
redteam_security_harness: { primary: "promptfoo", fallbacks: ["llama-audit:latest"], description: "Automated prompt injection & schema drift security fuzzer" },
deepgrove_code_auditor: { primary: "deepgrove", fallbacks: ["llama-audit:latest"], description: "Codebase vulnerability detection" },
inclusion_audit_critic: { primary: "inclusion-ai", fallbacks: ["llama-audit:latest"], description: "Governance and financial security auditor" },
"alignment_&_reward_critic": { primary: "nvidia/nemotron-70b", fallbacks: ["llama-audit:latest"], description: "RLHF alignment & safety reward critic" },
local_security_auditor: { primary: "llama-audit:latest", fallbacks: ["gemma3:4b"], description: "Custom local audit Modelfile" },
},
},
DIV_IV: {
id: "DIV_IV",
name: "Division IV: Chain-of-Thought & Logic",
roles: {
chain_of_thought_critic: { primary: "deepseek-r1", fallbacks: ["deepseek-r1:7b"], description: "Deep math & algorithmic reasoning" },
deliberate_reasoning_probe: { primary: "openai/o3-mini", fallbacks: ["openai/o1", "deepseek-r1:7b"], description: "Multi-step reasoning probes" },
moe_logic_titan: { primary: "deepseek-v3", fallbacks: ["deepseek-r1"], description: "671B MoE universal logic" },
},
},
DIV_V: {
id: "DIV_V",
name: "Division V: Multimodal & Asian Frontier Labs",
roles: {
tencent_hy3_synthesizer: { primary: "hy3", fallbacks: ["yi-zero"], description: "Multi-task code & math synthesis" },
multimodal_step_reasoner: { primary: "stepfun-step-2", fallbacks: ["mimo"], description: "Multi-step visual & procedural reasoning" },
mimo_edge_reasoner: { primary: "mimo", fallbacks: ["gemma3:4b"], description: "Compact edge & multimodal reasoning" },
zero_foundation_model: { primary: "yi-zero", fallbacks: ["kimi-128k"], description: "01.AI Zero foundation model series" },
minimax_long_context: { primary: "minimax-abab6.5t", fallbacks: ["kimi-128k"], description: "High-speed long-context reasoning" },
kimi_128k_reasoner: { primary: "moonshot-k2", fallbacks: ["minimax-abab6.5t"], description: "128k long-context reasoning" },
},
},
DIV_VI: {
id: "DIV_VI",
name: "Division VI: Systems Architects & High-Judgment Judges",
roles: {
systems_architect: { primary: "claude-3-7-sonnet", fallbacks: ["gpt-4o", "gemma3:4b"], description: "Gold standard architecture and code hygiene" },
universal_judge: { primary: "gpt-4o", fallbacks: ["claude-3-7-sonnet", "gemma3:4b"], description: "Universal execution judge" },
context_grounding_judge: { primary: "gemini-2.5-pro", fallbacks: ["gemini-2.0-flash"], description: "Long-context retrieval & system prompt grounding" },
open_weights_titan: { primary: "llama-3.1-405b", fallbacks: ["llama-3.3-70b"], description: "Heavyweight open-weights consensus titan" },
schema_compliance_auditor: { primary: "command-r-plus", fallbacks: ["gpt-4o"], description: "Structured JSON schema & RAG auditor" },
abacus_reasoning_judge: { primary: "smaug-72b", fallbacks: ["deepseek-r1"], description: "Fine-tuned reasoning champion" },
long_context_architect: { primary: "magic-dev", fallbacks: ["gemini-2.5-pro"], description: "100M token context code architect" },
},
},
DIV_VII: {
id: "DIV_VII",
name: "Division VII: Local Offline Resident Ensemble",
roles: {
gemma3_local: { primary: "gemma3:4b", fallbacks: ["gemma3:12b"], description: "Default local synthesizer and judge" },
qwen_local: { primary: "qwen2.5-coder:7b", fallbacks: ["gemma3:4b"], description: "Fast local code synthesizer" },
r1_local: { primary: "deepseek-r1:7b", fallbacks: ["deepseek-r1:1.5b"], description: "Local chain-of-thought logic critic" },
mistral_local: { primary: "mistral:latest", fallbacks: ["gemma3:4b"], description: "Local instruction follower" },
},
},
DIV_VIII: {
id: "DIV_VIII",
name: "Division VIII: Operator-Gated Developer Tool Frameworks",
roles: {
git_diff_engine: { primary: "aider", fallbacks: ["qwen2.5-coder:7b"], description: "Surgical multi-file diff generation & clean commit formatting" },
prompt_compiler: { primary: "dspy", fallbacks: ["systems_architect"], description: "Operator-reviewed prompt compilation from execution traces" },
github_issue_resolver: { primary: "swe-agent", fallbacks: ["devstral_specialist"], description: "Repo navigation & test suite execution" },
sandbox_executor: { primary: "openhands", fallbacks: ["mistral:latest"], description: "Isolated container/loopback sandbox execution engine" },
},
},
});
export const COUNCIL_SELECTION_HARNESSES = Object.freeze({
native_chat: Object.freeze({
harness_id: "native_chat",
label: "Native Chat Dispatch",
description: "Current chat adapter path with routing-policy receipts",
implemented: true,
task_class: "chat",
response_contract: "text.v1",
}),
dizzy_json_review: Object.freeze({
harness_id: "dizzy_json_review",
label: "Bounded JSON Reviewer",
description: "Review-model harness; not exposed through dashboard chat yet",
implemented: false,
blocked_reason: "review_harness_not_wired_to_chat_selection",
}),
});
const EXECUTABLE_LOCAL_SEATS = Object.freeze({
gemma3_local: Object.freeze({
seat_id: "gemma3_local",
label: "Gemma 3 Local",
division_key: "DIV_VII",
model_id: "gemma3:4b",
adapter: "ollama",
backend: "openai_compat",
provider_boundary: "local_machine",
seat_class: "local_open_weight",
baseline_role: "local_open_weight",
}),
qwen_local: Object.freeze({
seat_id: "qwen_local",
label: "Qwen Coder Local",
division_key: "DIV_VII",
model_id: "qwen2.5-coder:7b",
adapter: "ollama",
backend: "openai_compat",
provider_boundary: "local_machine",
seat_class: "local_open_weight",
baseline_role: "local_open_weight",
}),
llama_audit_local: Object.freeze({
seat_id: "llama_audit_local",
label: "Llama Audit Local",
division_key: "DIV_VII",
model_id: "llama-audit:latest",
adapter: "ollama",
backend: "openai_compat",
provider_boundary: "local_machine",
seat_class: "local_open_weight",
baseline_role: "local_open_weight",
}),
r1_local: Object.freeze({
seat_id: "r1_local",
label: "DeepSeek R1 Local",
division_key: "DIV_VII",
model_id: "deepseek-r1:7b",
adapter: "ollama",
backend: "openai_compat",
provider_boundary: "local_machine",
seat_class: "local_open_weight",
baseline_role: "local_open_weight",
native_chat_enabled: false,
blocked_reason: "reasoning_adapter_required",
}),
mistral_local: Object.freeze({
seat_id: "mistral_local",
label: "Mistral Local",
division_key: "DIV_VII",
model_id: "mistral:latest",
adapter: "ollama",
backend: "openai_compat",
provider_boundary: "local_machine",
seat_class: "local_open_weight",
baseline_role: "local_open_weight",
}),
});
export function normalizeCouncilSelection(selection = {}) {
const src = selection && typeof selection === "object" && !Array.isArray(selection) ? selection : {};
const rawSeat = src.seat_id ?? src.seat;
const rawModel = src.model_id ?? src.model;
const rawHarness = src.harness_id ?? src.harness;
return {
seat_id: rawSeat !== undefined && rawSeat !== null ? normalizeId(rawSeat) : "",
model_id: rawModel !== undefined && rawModel !== null ? String(rawModel).trim() : "",
harness_id: normalizeId(rawHarness ?? "native_chat", "native_chat"),
};
}
export function getCouncilSelectionOptions() {
const harness = COUNCIL_SELECTION_HARNESSES.native_chat;
return Object.values(EXECUTABLE_LOCAL_SEATS).map((seat) => ({
seat_id: seat.seat_id,
label: seat.label,
division_key: seat.division_key,
model_id: seat.model_id,
harness_id: harness.harness_id,
harness_label: harness.label,
adapter: seat.adapter,
backend: seat.backend,
provider_boundary: seat.provider_boundary,
seat_class: seat.seat_class,
evidence_state: "configured_unverified",
authority: "operator_requested_not_availability_proof",
enabled: seat.native_chat_enabled !== false,
blocked_reason: seat.native_chat_enabled === false ? (seat.blocked_reason || "seat_not_enabled_for_native_chat") : "",
}));
}
const COUNCIL_REVIEW_SEAT_IDS = Object.freeze([
"qwen_local",
"mistral_local",
"gemma3_local",
"llama_audit_local",
]);
export function getCouncilReviewSelectionOptions() {
const harness = COUNCIL_SELECTION_HARNESSES.dizzy_json_review;
return COUNCIL_REVIEW_SEAT_IDS
.map((seatId) => EXECUTABLE_LOCAL_SEATS[seatId])
.filter(Boolean)
.map((seat) => ({
seat_id: seat.seat_id,
label: seat.label,
division_key: seat.division_key,
model_id: seat.model_id,
harness_id: harness.harness_id,
harness_label: harness.label,
adapter: seat.adapter,
backend: seat.backend,
provider_boundary: seat.provider_boundary,
seat_class: seat.seat_class,
evidence_state: "configured_unverified",
authority: "advisory_supplied_evidence_review_only",
enabled: true,
blocked_reason: "",
}));
}
export function resolveCouncilSelection(selection = {}) {
const normalized = normalizeCouncilSelection(selection);
if (!normalized.seat_id && !normalized.model_id && (!normalized.harness_id || normalized.harness_id === "native_chat")) {
return { ok: false, empty: true, reason: "selection_not_requested" };
}
const harness = COUNCIL_SELECTION_HARNESSES[normalized.harness_id];
if (!harness) return { ok: false, reason: "unknown_harness", selection: normalized };
if (harness.implemented !== true) return { ok: false, reason: harness.blocked_reason || "harness_not_implemented", selection: normalized };
const seatById = normalized.seat_id && Object.prototype.hasOwnProperty.call(EXECUTABLE_LOCAL_SEATS, normalized.seat_id)
? EXECUTABLE_LOCAL_SEATS[normalized.seat_id]
: null;
if (normalized.seat_id && !seatById) return { ok: false, reason: "unknown_seat", selection: normalized };
const seatByModel = normalized.model_id
? Object.values(EXECUTABLE_LOCAL_SEATS).find((candidate) => candidate.model_id === normalized.model_id)
: null;
if (normalized.seat_id && normalized.model_id && seatById && seatByModel && seatById.seat_id !== seatByModel.seat_id) {
return { ok: false, reason: "seat_model_mismatch", selection: normalized };
}
const seat = seatById || seatByModel;
if (!seat) return { ok: false, reason: "unknown_seat", selection: normalized };
if (normalized.harness_id === "native_chat" && seat.native_chat_enabled === false) {
return { ok: false, reason: seat.blocked_reason || "seat_not_enabled_for_native_chat", selection: normalized };
}
if (normalized.model_id && normalized.model_id !== seat.model_id) {
return { ok: false, reason: "seat_model_mismatch", selection: normalized };
}
const baseUrl = defaultOllamaBaseUrl();
const classifiedBaseUrl = classifyOpenAICompatBaseUrl(baseUrl);
if (classifiedBaseUrl.provider !== "ollama") {
return { ok: false, reason: "local_seat_requires_loopback_or_private_lan_ollama", selection: normalized };
}
if (classifiedBaseUrl.isPrivateLan && env("DIZZY_ALLOW_LAN_LOCAL_BACKEND") !== "1") {
return { ok: false, reason: "local_seat_private_lan_requires_opt_in", selection: normalized };
}
const routeId = `${seat.adapter}:${seat.model_id}`;
return {
ok: true,
selection: normalized,
seat_id: seat.seat_id,
seat_label: seat.label,
model_id: seat.model_id,
harness_id: harness.harness_id,
harness_label: harness.label,
backend: seat.backend,
adapter: seat.adapter,
base_url: baseUrl,
api_key: "local_nop",
route_id: routeId,
provider_boundary: classifiedBaseUrl.isLoopback ? "local_machine" : "private_lan",
seat_class: seat.seat_class,
evidence_state: "configured_unverified",
authority: "operator_requested_not_availability_proof",
};
}
export function resolveCouncilReviewSelection(selection = {}) {
const normalized = normalizeCouncilSelection(selection);
if (!normalized.seat_id && !normalized.model_id && (!normalized.harness_id || normalized.harness_id === "native_chat")) {
return { ok: false, empty: true, reason: "selection_not_requested", selection: normalized };
}
if (normalized.harness_id !== "dizzy_json_review") {
return { ok: false, reason: "harness_not_supported_for_local_review", selection: normalized };
}
const harness = COUNCIL_SELECTION_HARNESSES.dizzy_json_review;
const reviewSeats = COUNCIL_REVIEW_SEAT_IDS
.map((seatId) => EXECUTABLE_LOCAL_SEATS[seatId])
.filter(Boolean);
const seatById = normalized.seat_id
? reviewSeats.find((candidate) => candidate.seat_id === normalized.seat_id)
: null;
if (normalized.seat_id && !seatById) return { ok: false, reason: "unknown_review_seat", selection: normalized };
const seatByModel = normalized.model_id
? reviewSeats.find((candidate) => candidate.model_id === normalized.model_id)
: null;
if (normalized.seat_id && normalized.model_id && seatById && seatByModel && seatById.seat_id !== seatByModel.seat_id) {
return { ok: false, reason: "seat_model_mismatch", selection: normalized };
}
const seat = seatById || seatByModel;
if (!seat) return { ok: false, reason: "unknown_review_seat", selection: normalized };
if (normalized.model_id && normalized.model_id !== seat.model_id) {
return { ok: false, reason: "seat_model_mismatch", selection: normalized };
}
const baseUrl = defaultOllamaBaseUrl();
const classifiedBaseUrl = classifyOpenAICompatBaseUrl(baseUrl);
if (classifiedBaseUrl.provider !== "ollama") {
return { ok: false, reason: "local_review_requires_loopback_or_private_lan_ollama", selection: normalized };
}
if (classifiedBaseUrl.isPrivateLan && env("DIZZY_ALLOW_LAN_LOCAL_BACKEND") !== "1") {
return { ok: false, reason: "local_review_private_lan_requires_opt_in", selection: normalized };
}
return {
ok: true,
selection: normalized,
seat_id: seat.seat_id,
seat_label: seat.label,
model_id: seat.model_id,
harness_id: harness.harness_id,
harness_label: harness.label,
backend: seat.backend,
adapter: seat.adapter,
base_url: baseUrl,
api_key: "local_nop",
route_id: `${seat.adapter}:${seat.model_id}`,
provider_boundary: classifiedBaseUrl.isLoopback ? "local_machine" : "private_lan",
seat_class: seat.seat_class,
evidence_state: "configured_unverified",
authority: "advisory_supplied_evidence_review_only",
};
}
export function isLoopbackHost(host) {
const raw = String(host || "").trim().toLowerCase();
const h = raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
if (h === "localhost") return true;
const ipVer = net.isIP(h);
if (ipVer === 4) return h === "127.0.0.1";
if (ipVer === 6) return h === "::1";
return false;
}
export function isPrivateLanHost(host) {
const raw = String(host || "").trim().toLowerCase();
const h = raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
const ipVer = net.isIP(h);
if (ipVer === 4) {
if (h.startsWith("10.")) return true;
if (h.startsWith("192.168.")) return true;
if (h.startsWith("169.254.")) return true;
if (/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(h)) return true;
return false;
}
if (ipVer === 6) {
if (/^f[cd][0-9a-f]{2}:/i.test(h)) return true;
if (/^fe[89ab][0-9a-f]:/i.test(h)) return true;
return false;
}
return false;
}
export function isRemoteCloudBackend(backend, baseUrl = "") {
const b = String(backend || "").trim().toLowerCase();
if (b === "gemini") return true;
if (b === "openai_compat" || b === "openrouter") {
const urlStr = String(baseUrl || "").trim();
if (!urlStr) return true;
try {
const urlObj = new URL(urlStr);
const host = urlObj.hostname;
return !isLoopbackHost(host) && !isPrivateLanHost(host);
} catch {
return true;
}
}
return false;
}
export function classifyOpenAICompatBaseUrl(baseUrl = "") {
const raw = String(baseUrl || "").trim();
const host = hostnameForBaseUrl(raw);
if (!host) {
return { provider: "unknown", host: "", isLoopback: false, isPrivateLan: false, isLocalHost: false };
}
const lowerHost = host.toLowerCase();
const isLoopback = isLoopbackHost(lowerHost);
const isPrivateLan = isPrivateLanHost(lowerHost);
const isLocalHost = isLoopback || isPrivateLan;
if (isLocalHost) {
return { provider: "ollama", host: lowerHost, isLoopback, isPrivateLan, isLocalHost };
}
if (hostMatches(lowerHost, "openrouter.ai")) {
return { provider: "openrouter", host: lowerHost, isLoopback, isPrivateLan, isLocalHost };
}
if (hostMatches(lowerHost, "groq.com")) {
return { provider: "groq", host: lowerHost, isLoopback, isPrivateLan, isLocalHost };
}
return { provider: "generic", host: lowerHost, isLoopback, isPrivateLan, isLocalHost };
}
export function normalizeOpenAICompatModelForBaseUrl({ baseUrl = "", model = "", localFallbackModel = "gemma3:4b" } = {}) {
const m = String(model || "").trim();
if (!m) return "";
const { provider } = classifyOpenAICompatBaseUrl(baseUrl);
if (provider === "ollama") {
if (
m.includes("/") ||
m.toLowerCase().includes("openrouter") ||
m.toLowerCase().includes("gemini") ||
m.toLowerCase().includes("groq")
) {
return String(localFallbackModel || "gemma3:4b").trim() || "gemma3:4b";
}
return m;
}
if (provider === "openrouter") {
if (m === "qwen/qwen-2.5-coder-32b-instruct" || m === "qwen/qwen3-32b" || m === "qwen3-32b") {
return "openrouter/auto";
}
return m;
}
if (provider === "groq") {
if (m === "qwen/qwen-2.5-coder-32b-instruct" || m === "qwen/qwen3-32b" || m === "qwen3-32b") {
return "qwen-2.5-coder-32b";
}
return m;
}
if (m === "qwen/qwen3-32b" || m === "qwen3-32b") {
return "qwen/qwen-2.5-coder-32b-instruct";
}
return m;
}
export function resolveOpenAICompatTimeoutMs({ baseUrl = "", timeoutMs, remoteDefaultMs = 20000, localDefaultMs = 120000 } = {}) {
const requested = Number(timeoutMs);
const { isLocalHost } = classifyOpenAICompatBaseUrl(baseUrl);
const fallback = isLocalHost ? localDefaultMs : remoteDefaultMs;
const floor = isLocalHost ? 10000 : 1000;
return Math.max(floor, Number.isFinite(requested) && requested > 0 ? requested : fallback);
}
export function computePromptPrefixHash(systemPrompt) {
const prefix = String(systemPrompt || "").slice(0, 512).trim();
if (!prefix) return "none";
return crypto.createHash("sha256").update(prefix).digest("hex").slice(0, 16);
}
export function evaluateLocalIsolationPolicy({ trustZone, dataBoundary, isLocalBackend }) {
const isPrivateZone = trustZone === "private_self";
const isInternalBoundary = dataBoundary === "internal_only" || dataBoundary === "local_machine" || dataBoundary === "private_lan";
const isLocal = Boolean(isLocalBackend) || String(env("DIZZY_CHAT_BACKEND", "")).trim().toLowerCase() === "local";
const isLocalIsolationRequired = isLocal || isPrivateZone || isInternalBoundary;
return {
isLocalIsolationRequired,
allowCloudFallback: !isLocalIsolationRequired,
blockedReason: isLocalIsolationRequired ? "local_offline_cloud_blocked" : "",
};
}
export function getDivisionForRole(roleKey) {
const r = String(roleKey || "").trim().toLowerCase();
for (const [divKey, divInfo] of Object.entries(EIGHT_DIVISIONS_ROSTER)) {
if (divInfo.roles[r] || divInfo.roles[roleKey]) {
return {
division_key: divKey,
division_name: divInfo.name,
role_key: roleKey,
role_info: divInfo.roles[r] || divInfo.roles[roleKey],
};
}
}
return null;
}
export function resolveDivisionModelRoute(roleKey, options = {}) {
const divMatch = getDivisionForRole(roleKey);
if (!divMatch) {
// Fallback to legacy chat/utility route
const legacyRoute = getModelRoute(roleKey);
return {
ok: false,
role: roleKey,
division: "DIV_VII",
primary_model: "gemma3:4b",
fallbacks: ["qwen2.5-coder:7b"],
backend: legacyRoute.backend || "openai_compat",
data_boundary: "local_machine",
};
}
const roleInfo = divMatch.role_info;
const primaryModel = roleInfo.primary;
const fallbacks = roleInfo.fallbacks || [];
let backend = "openai_compat";
let dataBoundary = "openai_compatible_api";
if (primaryModel.includes("gemini")) {
backend = "gemini";
dataBoundary = "google_gemini_api";
} else if (primaryModel.includes(":latest") || primaryModel.includes(":4b") || primaryModel.includes(":7b") || primaryModel.includes(":12b")) {
backend = "ollama";
dataBoundary = "local_machine";
} else if (["aider", "dspy", "swe-agent", "openhands", "promptfoo"].includes(primaryModel.toLowerCase())) {
backend = "framework";
dataBoundary = "local_machine";
}
return {
ok: true,
role: divMatch.role_key,
division_key: divMatch.division_key,
division_name: divMatch.division_name,
primary_model: primaryModel,
fallbacks,
description: roleInfo.description,
backend,
data_boundary: dataBoundary,
};
}
export function getModelRoute(role = "chat") {
const r = String(role || "chat").trim().toLowerCase();
// Check if role is an 8-Division specialized role
const divMatch = getDivisionForRole(r);
if (divMatch) {
const route = resolveDivisionModelRoute(r);
return {
role: r,
division: divMatch.division_key,
backend: route.backend,
primary_model: route.primary_model,
reason: `division:${divMatch.division_key}`,
log: `${r}:${route.backend}:division:${divMatch.division_key}`,
};
}
const normalizedRole = r === "utility" ? "utility" : "chat";
if (String(env("DIZZY_CHAT_BACKEND", "")).trim().toLowerCase() === "local") {
return {
role: normalizedRole,
backend: "openai_compat",
reason: "local_backend_mapped_to_ollama",
log: `${normalizedRole}:openai_compat:local_backend_mapped_to_ollama`,
};
}
const chatBackend = normalizeBackend(env("DIZZY_CHAT_BACKEND", ""));
const utilityBackend = normalizeBackend(env("DIZZY_UTILITY_BACKEND", "")) || chatBackend;
const backend = normalizedRole === "utility" ? utilityBackend : chatBackend;
const reason = normalizedRole === "utility"
? (utilityBackend === chatBackend ? "utility_uses_chat_backend" : "utility_backend_override")
: "chat_backend";
return {
role: normalizedRole,
backend,
reason: `cloud:${reason}`,
log: `${normalizedRole}:${backend || "none"}:cloud:${reason}`,
};
}
export function getOpenAICompatModelForRoute(route) {
if (route?.primary_model) return route.primary_model;
if (route?.role === "utility") {
return String(env("DIZZY_UTILITY_OPENAI_COMPAT_MODEL", env("OPENAI_COMPAT_MODEL", ""))).trim();
}
return String(env("OPENAI_COMPAT_MODEL", "")).trim();
}
export function getGeminiModelForRoute(route) {
if (route?.primary_model && route.primary_model.includes("gemini")) return route.primary_model;
if (route?.role === "utility") {
return String(env("DIZZY_UTILITY_GEMINI_MODEL", env("GEMINI_MODEL", "gemini-1.5-flash"))).trim();
}
return String(env("GEMINI_MODEL", "gemini-1.5-flash")).trim();
}
export function getChosenModelString(role = "chat") {
const route = getModelRoute(role);
if (route.primary_model) return `${route.backend}:${route.primary_model}`;
if (String(env("DIZZY_CHAT_BACKEND", "")).trim().toLowerCase() === "local") {
const localModel = String(env("OLLAMA_MODEL", "gemma3:4b")).trim();
return `openai_compat:${localModel}`;
}
if (!route.backend) return "none:chat_backend_not_configured";
if (route.backend === "gemini") {
return `gemini:${getGeminiModelForRoute(route)}`;
}
if (route.backend === "openai_compat") {
const baseUrl = String(env("DIZZY_CHAT_BACKEND", "")).trim().toLowerCase() === "local"
? env("OLLAMA_BASE_URL", "http://127.0.0.1:11434/v1")
: env("OPENAI_COMPAT_BASE_URL", "");
const model = normalizeOpenAICompatModelForBaseUrl({
baseUrl,
model: getOpenAICompatModelForRoute(route),
localFallbackModel: env("OLLAMA_MODEL", "gemma3:4b"),
});
return `openai_compat:${model}`;
}
return "unknown:default";
}
export function getAllDivisions() {
return EIGHT_DIVISIONS_ROSTER;
}
export function getAllRoles() {
const allRoles = {};
for (const divInfo of Object.values(EIGHT_DIVISIONS_ROSTER)) {
Object.assign(allRoles, divInfo.roles);
}
return allRoles;
}