@mcoda/mswarm 0.1.135-codali.29 → 0.1.135-codali.35
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/codali-executor.d.ts +6 -0
- package/dist/codali-executor.d.ts.map +1 -1
- package/dist/codali-executor.js +8 -0
- package/dist/codali-executor.js.map +1 -1
- package/dist/runtime.d.ts +3 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2 -1
- package/dist/runtime.js.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.d.ts +2 -1
- package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.js +27 -27
- package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts +2 -0
- package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalPresentation.js +77 -2
- package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalTui.js +14 -3
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts +7 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.js +15 -2
- package/dist/vendor/codali/docdex/DocdexClient.d.ts +1 -0
- package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/DocdexClient.js +1 -1
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +3 -0
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/ManagedDocdex.js +17 -1
- package/dist/vendor/codali/gateway/GroundingMode.d.ts.map +1 -1
- package/dist/vendor/codali/gateway/GroundingMode.js +23 -3
- package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.js +7 -5
- package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ConfiguredModelScope.js +2 -1
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +5 -1
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ConfiguredProvider.js +55 -32
- package/dist/vendor/codali/providers/ModelCapacityWait.d.ts +21 -0
- package/dist/vendor/codali/providers/ModelCapacityWait.d.ts.map +1 -0
- package/dist/vendor/codali/providers/ModelCapacityWait.js +40 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts +11 -2
- package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ModelServiceError.js +13 -5
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +20 -5
- package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
- package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
- package/dist/vendor/codali/providers/RequestSize.d.ts +5 -0
- package/dist/vendor/codali/providers/RequestSize.d.ts.map +1 -0
- package/dist/vendor/codali/providers/RequestSize.js +10 -0
- package/dist/vendor/codali/runtime/AnswerVerification.d.ts +17 -0
- package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/AnswerVerification.js +39 -0
- package/dist/vendor/codali/runtime/CompletionReport.d.ts +2 -0
- package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/CompletionReport.js +17 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts +19 -3
- package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ContextCompression.js +224 -14
- package/dist/vendor/codali/runtime/GatewayRequest.d.ts +5 -0
- package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/GatewayRequest.js +19 -0
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts +4 -1
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InspectionBudget.js +14 -16
- package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +24 -0
- package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/InspectionConvergence.js +67 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts +2 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionContract.js +14 -0
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts +6 -4
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionRouter.js +15 -11
- package/dist/vendor/codali/runtime/PlanCoverage.d.ts +9 -0
- package/dist/vendor/codali/runtime/PlanCoverage.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/PlanCoverage.js +12 -0
- package/dist/vendor/codali/runtime/ProgressTracker.d.ts +1 -0
- package/dist/vendor/codali/runtime/ProgressTracker.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ProgressTracker.js +25 -5
- package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +19 -0
- package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ResearchEvidence.js +55 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +2 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ReviewCoordinator.js +3 -1
- package/dist/vendor/codali/runtime/SessionController.d.ts +33 -4
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/SessionController.js +936 -216
- package/dist/vendor/codali/runtime/SpecialistTools.d.ts +8 -0
- package/dist/vendor/codali/runtime/SpecialistTools.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/SpecialistTools.js +81 -0
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +4 -2
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/StructuralEvidence.js +22 -5
- package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts +2 -0
- package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/WorkspaceLedger.js +44 -20
- package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/WorkspaceLock.js +9 -1
- package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/WorkspaceSnapshot.js +3 -2
- package/dist/vendor/codali/runtime/WriteSyntaxCheck.d.ts +10 -0
- package/dist/vendor/codali/runtime/WriteSyntaxCheck.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/WriteSyntaxCheck.js +34 -0
- package/dist/vendor/codali/session/SessionStoragePath.d.ts.map +1 -1
- package/dist/vendor/codali/session/SessionStoragePath.js +7 -2
- package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -1
- package/dist/vendor/codali/session/SkillCatalog.js +6 -3
- package/dist/vendor/codali/session/WorkState.d.ts +2 -0
- package/dist/vendor/codali/session/WorkState.d.ts.map +1 -1
- package/dist/vendor/codali/session/WorkState.js +14 -2
- package/dist/vendor/codali/session/WorkspaceScope.d.ts +3 -0
- package/dist/vendor/codali/session/WorkspaceScope.d.ts.map +1 -0
- package/dist/vendor/codali/session/WorkspaceScope.js +19 -0
- package/dist/vendor/codali/tools/ToolTypes.d.ts +5 -0
- package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
- package/dist/vendor/codali/tools/browser/BrowserSessionTool.d.ts +16 -0
- package/dist/vendor/codali/tools/browser/BrowserSessionTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/BrowserSessionTool.js +326 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +8 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/browser/BrowserTool.js +152 -13
- package/dist/vendor/codali/tools/browser/BrowserWorker.js +74 -4
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/calculation/CalculatorTool.js +33 -7
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +17 -3
- package/dist/vendor/codali/tools/deterministic/python-worker.py +18 -3
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +2 -1
- package/dist/vendor/codali/tools/docdex/DocdexTools.js +10 -2
- package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/filesystem/FileTools.js +62 -11
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +4 -0
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/AsyncProcess.js +9 -3
- package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/HostToolchain.js +19 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +4 -2
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +99 -29
- package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
- package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/ShellTool.js +19 -4
- package/dist/vendor/codali/tools/system/CalendarTool.d.ts +15 -0
- package/dist/vendor/codali/tools/system/CalendarTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/system/CalendarTool.js +44 -0
- package/dist/vendor/codali/tools/system/TextTool.d.ts +4 -0
- package/dist/vendor/codali/tools/system/TextTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/system/TextTool.js +39 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts +3 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/verification/VitestTool.js +65 -9
- package/dist/vendor/config/AGENTS.md +6 -0
- package/dist/vendor/config/deterministic/python-worker.py +18 -3
- package/dist/vendor/config/skills/architecture-design/SKILL.md +14 -0
- package/dist/vendor/config/skills/browser-session/SKILL.md +16 -0
- package/dist/vendor/config/skills/browser-use/SKILL.md +14 -0
- package/dist/vendor/config/skills/code-implementation/SKILL.md +18 -0
- package/dist/vendor/config/skills/code-review/SKILL.md +14 -0
- package/dist/vendor/config/skills/docdex-research/SKILL.md +18 -0
- package/dist/vendor/config/skills/docdex-research/references/catalog.md +111 -0
- package/dist/vendor/config/skills/docdex-research/references/memory.md +22 -0
- package/dist/vendor/config/skills/docdex-research/references/operations.md +19 -0
- package/dist/vendor/config/skills/docdex-research/references/retrieval.md +13 -0
- package/dist/vendor/config/skills/planning/SKILL.md +9 -8
- package/dist/vendor/config/skills/system-diagnostics/SKILL.md +14 -0
- package/dist/vendor/config/skills/system-services/SKILL.md +17 -0
- package/dist/vendor/config/skills/system-services/references/docker.md +11 -0
- package/dist/vendor/config/skills/system-services/references/linux.md +9 -0
- package/dist/vendor/config/skills/system-services/references/macos.md +9 -0
- package/dist/vendor/config/skills/systematic-debugging/SKILL.md +14 -0
- package/dist/vendor/config/skills/testing-and-verification/SKILL.md +16 -0
- package/dist/vendor/config/skills/tool-selection/SKILL.md +16 -0
- package/dist/vendor/config/skills/ui-ux-design/SKILL.md +16 -0
- package/dist/vendor/config/skills/ui-ux-design/references/validation.md +13 -0
- package/dist/vendor/config/skills/webapp-testing/SKILL.md +12 -0
- package/package.json +3 -3
|
@@ -36,8 +36,26 @@ const POSSESSIVE = /\b(?:my|mine|our|ours|assigned to me|do i have|have i got)\b
|
|
|
36
36
|
const FRESHNESS_NOUNS = /\b(?:today|todays|current|currently|latest|most recent|recently|right now|this (?:week|month|year)|as of|news headline|stock price|weather|who is the)\b/i;
|
|
37
37
|
/** "when did X last change", "how recently", "what is the newest" — asked about, not mentioned. */
|
|
38
38
|
const RECENCY_QUESTION = /\b(?:when (?:did|was|has).{0,40}\b(?:last|most recently)\b|how recently|what(?:'s| is) the (?:newest|latest))/i;
|
|
39
|
+
/**
|
|
40
|
+
* Turkish forms of the anchors above, for Turkish-language deployments.
|
|
41
|
+
*
|
|
42
|
+
* Matched against Turkish-lowercased text, since the `i` flag folds neither
|
|
43
|
+
* I/ı nor İ/i correctly. JavaScript's `\b` is ASCII-only and cannot bound a word
|
|
44
|
+
* starting with ş or ü, so these use a Unicode lookbehind and leave the end open:
|
|
45
|
+
* Turkish carries case and possession in suffixes ("bugünkü", "projedeki").
|
|
46
|
+
*/
|
|
47
|
+
const TR_WORD = "(?<![\\p{L}\\p{N}])";
|
|
48
|
+
const TR_CONTEXT_NOUNS = new RegExp(`${TR_WORD}(?:bu depo|bu proje|bu kod|kod taban|depodaki|projedeki)`, "u");
|
|
49
|
+
const TR_POSSESSIVE = new RegExp(`${TR_WORD}(?:benim|bizim|bana (?:atanan|ait)|bize (?:atanan|ait)|elimdeki|hesabım|takvimim)` +
|
|
50
|
+
// Plural plus first-person possessive: faturalarım, görevlerimiz.
|
|
51
|
+
`|\\p{L}{2,}l[ae]r[ıiuü]m(?:[ıiuü]z)?(?![\\p{L}\\p{N}])`, "u");
|
|
52
|
+
const TR_FRESHNESS = new RegExp(`${TR_WORD}(?:bugün|dün|şu an|şuan|şimdi|güncel|en son|son durum|bu (?:hafta|ay|yıl)|geçen (?:hafta|ay|yıl)|hava durumu|döviz kuru|hisse fiyat)`, "u");
|
|
53
|
+
/** Turkish is verb-final, so the request verb is found at the end, not the start. */
|
|
54
|
+
const TR_GENERATION_CLOSERS = new RegExp(`${TR_WORD}(?:yaz|oluştur|üret|hazırla|tasarla|çiz)(?:y?[ıiuü]n(?:[ıiuü]z)?|y?[ae]bilir|[ıiuü]r|[ae]r)?(?:\\s+m[ıiuü]s[ıiuü]n(?:[ıiuü]z)?)?\\s*[.!?]*\\s*$`, "u");
|
|
55
|
+
const turkishLowered = (query) => query.toLocaleLowerCase("tr");
|
|
39
56
|
export const decideGroundingMode = (input) => {
|
|
40
57
|
const query = input.query ?? "";
|
|
58
|
+
const lowered = turkishLowered(query);
|
|
41
59
|
const classifier = input.classifier;
|
|
42
60
|
// Never answer about someone's own data from memory, whatever the phrasing.
|
|
43
61
|
if (classifier.needsPrivateData) {
|
|
@@ -46,20 +64,21 @@ export const decideGroundingMode = (input) => {
|
|
|
46
64
|
if (classifier.needsAppTools) {
|
|
47
65
|
return { mode: "grounded", reason: "request needs product tools" };
|
|
48
66
|
}
|
|
49
|
-
if (CONTEXT_NOUNS.test(query)) {
|
|
67
|
+
if (CONTEXT_NOUNS.test(query) || TR_CONTEXT_NOUNS.test(lowered)) {
|
|
50
68
|
return { mode: "grounded", reason: "request names something in the workspace" };
|
|
51
69
|
}
|
|
52
|
-
if (POSSESSIVE.test(query)) {
|
|
70
|
+
if (POSSESSIVE.test(query) || TR_POSSESSIVE.test(lowered)) {
|
|
53
71
|
return { mode: "grounded", reason: "request is about the user's own data" };
|
|
54
72
|
}
|
|
55
73
|
if (FRESHNESS_NOUNS.test(query) ||
|
|
74
|
+
TR_FRESHNESS.test(lowered) ||
|
|
56
75
|
RECENCY_QUESTION.test(query) ||
|
|
57
76
|
classifier.needsFreshData) {
|
|
58
77
|
return { mode: "grounded", reason: "request needs current information" };
|
|
59
78
|
}
|
|
60
79
|
// A generation request with no workspace or freshness anchor has nothing to
|
|
61
80
|
// retrieve. Checked after the anchors above so they always win.
|
|
62
|
-
if (GENERATION_OPENERS.test(query)) {
|
|
81
|
+
if (GENERATION_OPENERS.test(query) || TR_GENERATION_CLOSERS.test(lowered)) {
|
|
63
82
|
return { mode: "open", reason: "generation request with nothing to retrieve" };
|
|
64
83
|
}
|
|
65
84
|
if (!classifier.needsDocdex) {
|
|
@@ -121,4 +140,5 @@ const OWNED_SYSTEM_NOUNS = /\b(?:github|gitlab|bitbucket|jira|confluence|outlook
|
|
|
121
140
|
export const requestTouchesOwnData = (query, classifier) => classifier.needsPrivateData === true ||
|
|
122
141
|
classifier.needsAppTools === true ||
|
|
123
142
|
POSSESSIVE.test(query ?? "") ||
|
|
143
|
+
TR_POSSESSIVE.test(turkishLowered(query ?? "")) ||
|
|
124
144
|
OWNED_SYSTEM_NOUNS.test(query ?? "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PermissionGate.d.ts","sourceRoot":"","sources":["../../src/permissions/PermissionGate.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGhF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,KAAK,GAAG,WAAW,GAAG,MAAM,CAAC;AACtE,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;AAClG,MAAM,WAAW,iBAAiB;IAAG,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;CAAE;AACrH,MAAM,WAAW,gBAAgB;IAAG,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAAE;AACjF,MAAM,WAAW,gBAAgB;IAAG,aAAa,EAAE,CAAC,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAC;CAAE;AAC5F,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,iBAAiB,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,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AO,CAAC,QAAQ,CAAC,MAAM,CAAC;IAAoB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAH3H,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAK;gBACF,OAAO,GAAE,iBAAyB,EAAmB,MAAM,CAAC,EAAE,gBAAgB,YAAA,EAAmB,OAAO,GAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;KAAO;IAEtP,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIlC,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI;IAK5C,WAAW,IAAI,IAAI;IAEnB,YAAY,IAAI,gBAAgB;IAEhC,aAAa,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IAKtC,SAAS,CAAC,IAAI,EAAE,cAAc,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;CAwB1F"}
|
|
@@ -2,9 +2,9 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { ToolExecutionError } from "../tools/ToolTypes.js";
|
|
3
3
|
import { docdexCatalogKind } from "../docdex/DocdexCatalog.js";
|
|
4
4
|
const fileRead = new Set(["prepare_edit", "read_file", "list_directory", "list_files", "stat_path", "diff_summary", "search", "search_files", "search_text", "glob", "file_search"]);
|
|
5
|
-
const fileWrite = new Set(["write_file", "apply_patch", "apply_diff", "media_export_artifact"]);
|
|
6
|
-
const controlRead = new Set(["work_status", "work_refine", "work_plan", "work_claim", "work_release", "work_reopen", "work_checkpoint", "work_decision", "work_verify", "work_complete", "work_block"]);
|
|
7
|
-
const executionWork = new Set(["work_claim", "work_verify", "work_complete"]);
|
|
5
|
+
const fileWrite = new Set(["write_file", "create_directory", "apply_patch", "apply_diff", "media_export_artifact"]);
|
|
6
|
+
const controlRead = new Set(["work_status", "work_refine", "work_plan", "work_claim", "work_release", "work_rescope", "work_reopen", "work_checkpoint", "work_decision", "work_verify", "work_complete", "work_block"]);
|
|
7
|
+
const executionWork = new Set(["work_claim", "work_rescope", "work_verify", "work_complete"]);
|
|
8
8
|
export const isExecutionWorkTool = (name) => executionWork.has(name);
|
|
9
9
|
const docdexReads = /^(docdex_(search|batch_search|rerank|open|files|tree|stats|symbols|ast|repo_inspect|impact_graph|impact_diagnostics|dag_export|memory_recall|get_profile|wakeup|diary_read|capabilities|conversation_search|conversation_read|conversation_list|kg_query))$/;
|
|
10
10
|
export const permissionKind = (tool) => {
|
|
@@ -20,11 +20,11 @@ export const permissionKind = (tool) => {
|
|
|
20
20
|
return "read";
|
|
21
21
|
if (tool.name === "tools_describe" && tool.capability === "discovery" && tool.readOnly)
|
|
22
22
|
return "read";
|
|
23
|
-
if (tool.name === "calculate" && tool.capability === "calculation" && tool.readOnly)
|
|
23
|
+
if ((tool.name === "calculate" || tool.name === "calendar_calculate") && tool.capability === "calculation" && tool.readOnly)
|
|
24
24
|
return "read";
|
|
25
25
|
if (["verify_javascript", "verify_tests"].includes(tool.name) && tool.capability === "verification" && tool.readOnly)
|
|
26
26
|
return "read";
|
|
27
|
-
if (["decimal_calculate", "numerical_calculate", "validate_json", "symbolic_math", "solve_constraints", "query_data", "transform_data"].includes(tool.name) && tool.capability === "deterministic" && tool.readOnly)
|
|
27
|
+
if (["transform_text", "decimal_calculate", "numerical_calculate", "validate_json", "symbolic_math", "solve_constraints", "query_data", "transform_data"].includes(tool.name) && tool.capability === "deterministic" && tool.readOnly)
|
|
28
28
|
return "read";
|
|
29
29
|
if (tool.name === "server_time" && tool.capability === "clock" && tool.readOnly)
|
|
30
30
|
return "read";
|
|
@@ -42,6 +42,8 @@ export const permissionKind = (tool) => {
|
|
|
42
42
|
return "web";
|
|
43
43
|
if (["media_job_status", "media_job_wait", "delegate_helper"].includes(tool.name))
|
|
44
44
|
return "read";
|
|
45
|
+
if (["delegate_coding", "delegate_frontend"].includes(tool.name) && tool.capability === "helper" && tool.readOnly)
|
|
46
|
+
return "read";
|
|
45
47
|
if (tool.name === "media_job_cancel")
|
|
46
48
|
return "media";
|
|
47
49
|
if (/image.*generat|audio.*generat|video.*generat|media.*generat/.test(tool.name) || /^(image|audio|video|media)_generation$/.test(tool.capability))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfiguredModelScope.d.ts","sourceRoot":"","sources":["../../src/providers/ConfiguredModelScope.ts"],"names":[],"mappings":"AACA,OAAO,EAAwD,KAAK,WAAW,EAAE,KAAK,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAC5J,OAAO,EAA4C,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAElI,OAAO,KAAK,EAAE,QAAQ,EAAqC,aAAa,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"ConfiguredModelScope.d.ts","sourceRoot":"","sources":["../../src/providers/ConfiguredModelScope.ts"],"names":[],"mappings":"AACA,OAAO,EAAwD,KAAK,WAAW,EAAE,KAAK,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAC5J,OAAO,EAA4C,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAElI,OAAO,KAAK,EAAE,QAAQ,EAAqC,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGrG,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IACnF,SAAS,EAAE,OAAO,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;CAC1C;AACD,MAAM,WAAW,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WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;KAC3C;IAWN,IAAI,MAAM,IAAI,WAAW,CAAmC;IAC5D,IAAI,UAAU,IAAI,MAAM,CAA+B;IACvD,IAAI,MAAM,IAAI,WAAW,CAA4C;IACrE,aAAa,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO;IAClD,MAAM;;;;;;;;IACN,IAAI,SAAS,IAAI,MAAM,CAA2B;IAClD,WAAW,IAAI,IAAI;IASnB,MAAM,CAAC,OAAO,EAAE,MAAM;;;;IACtB,QAAQ,IAAI,gBAAgB;IAC5B,KAAK,IAAI,IAAI;IAEb,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ;YAKrB,QAAQ;CAqDvB"}
|
|
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { effortBudget, pinOrchestrationConfig, resolveBinding } from "../config/OrchestrationConfig.js";
|
|
3
3
|
import { ConfiguredProvider, normalizeModelCaller } from "./ConfiguredProvider.js";
|
|
4
4
|
import { ModelServiceError } from "./ModelServiceError.js";
|
|
5
|
+
import { estimateProviderInputTokens } from "./RequestSize.js";
|
|
5
6
|
/** Invalid upstream accounting cannot lower a shared budget or turn it into NaN. */
|
|
6
7
|
export const verifiedTokenUsage = (usage) => {
|
|
7
8
|
const valid = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
@@ -74,7 +75,7 @@ export class ConfiguredModelScope {
|
|
|
74
75
|
linked.signal.throwIfAborted();
|
|
75
76
|
if (this.invocationIds.has(route.id))
|
|
76
77
|
throw new Error("Model requestId has already been used in this scope; use a new UUID for each inference attempt");
|
|
77
|
-
const reservation =
|
|
78
|
+
const reservation = estimateProviderInputTokens(bounded) + (bounded.maxTokens ?? this.limits.maxOutputTokens);
|
|
78
79
|
if (this.usage.modelCalls >= this.limits.maxModelCalls || this.usage.totalTokens + reservation > this.limits.maxTotalTokens)
|
|
79
80
|
throw new Error("Shared model budget exhausted");
|
|
80
81
|
invocation = route;
|
|
@@ -19,7 +19,10 @@ export interface ModelCallerContext {
|
|
|
19
19
|
export declare const normalizeModelCaller: (caller?: ModelCallerContext) => ModelCallerContext;
|
|
20
20
|
/** Discovery failed before inference; a caller may release its local token reservation. */
|
|
21
21
|
export declare class NativeReasoningTransportError extends Error {
|
|
22
|
-
|
|
22
|
+
readonly cause?: unknown;
|
|
23
|
+
constructor(message: string, options?: {
|
|
24
|
+
cause?: unknown;
|
|
25
|
+
});
|
|
23
26
|
}
|
|
24
27
|
export declare const providerCredential: (provider: OrchestrationProvider) => Promise<string | undefined>;
|
|
25
28
|
export declare class ModelServiceClient {
|
|
@@ -53,6 +56,7 @@ export interface ModelInvocation {
|
|
|
53
56
|
catalogId: string;
|
|
54
57
|
backend?: string;
|
|
55
58
|
host?: string;
|
|
59
|
+
resolvedCatalogId?: string;
|
|
56
60
|
nativeReasoningRequest?: Record<string, unknown>;
|
|
57
61
|
}
|
|
58
62
|
export declare class ConfiguredProvider implements Provider {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfiguredProvider.d.ts","sourceRoot":"","sources":["../../src/providers/ConfiguredProvider.ts"],"names":[],"mappings":"AAKA,OAAO,EAAkB,KAAK,qBAAqB,EAAE,KAAK,2BAA2B,EAAE,KAAK,cAAc,EAAE,KAAK,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAGvK,OAAO,EAAqB,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAEhF,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"ConfiguredProvider.d.ts","sourceRoot":"","sources":["../../src/providers/ConfiguredProvider.ts"],"names":[],"mappings":"AAKA,OAAO,EAAkB,KAAK,qBAAqB,EAAE,KAAK,2BAA2B,EAAE,KAAK,cAAc,EAAE,KAAK,WAAW,EAAE,MAAM,k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AAC,OAAO;IAL/G,QAAQ,CAAC,IAAI,gBAAgB;IAC7B,QAAQ,CAAC,iBAAiB,QAAQ;IAClC,OAAO,CAAC,OAAO,CAAyC;IACxD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmC;gBAC1C,QAAQ,EAAE,2BAA2B,EAAW,OAAO,SAAS,EAAmB,OAAO,GAAE;QAC/G,MAAM,CAAC,EAAE,kBAAkB,CAAC;QAC5B,yFAAyF;QACzF,WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;QAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,aAAa,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;QACzF,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACtF;IASN,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,kBAAkB;IAOxC,MAAM,CAAC,SAAS,EAAE,cAAc,EAAE,MAAM,CAAC,EAAE,WAAW,EAAE,YAAY,UAAQ;;;;;;IAwC5E,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;CA2BpE"}
|
|
@@ -8,6 +8,7 @@ import { OpenAiCompatibleProvider } from "./OpenAiCompatibleProvider.js";
|
|
|
8
8
|
import { ModelServiceError } from "./ModelServiceError.js";
|
|
9
9
|
import { parseRequestUsage } from "./RequestUsage.js";
|
|
10
10
|
import { registerSecretValue } from "../runtime/SecretRedaction.js";
|
|
11
|
+
import { estimateProviderInputTokens } from "./RequestSize.js";
|
|
11
12
|
export const normalizeModelCaller = (caller = {}) => {
|
|
12
13
|
const clientIdentity = caller.clientIdentity?.trim();
|
|
13
14
|
const clientProduct = caller.clientProduct?.trim().toLowerCase() ?? "codali";
|
|
@@ -24,7 +25,7 @@ const modelCallerHeaders = (caller) => ({
|
|
|
24
25
|
const record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
25
26
|
/** Discovery failed before inference; a caller may release its local token reservation. */
|
|
26
27
|
export class NativeReasoningTransportError extends Error {
|
|
27
|
-
constructor(message) { super(message); this.name = "NativeReasoningTransportError"; }
|
|
28
|
+
constructor(message, options) { super(message); this.name = "NativeReasoningTransportError"; this.cause = options?.cause; }
|
|
28
29
|
}
|
|
29
30
|
export const providerCredential = async (provider) => {
|
|
30
31
|
if (!provider.credentialRef)
|
|
@@ -134,19 +135,21 @@ export class ModelServiceClient {
|
|
|
134
135
|
if (!refresh && this.cache?.key === key && this.cache.expires > Date.now())
|
|
135
136
|
return this.cache.entries;
|
|
136
137
|
const base = new URL(this.provider.baseUrl);
|
|
137
|
-
const url = this.provider.catalogUrl ?? (this.provider.adapter === "mswarm" ? new URL("/v1/swarm/self-hosted/agents", base).toString() : `${this.provider.baseUrl.replace(/\/$/, "")}/models`);
|
|
138
|
+
const url = this.provider.catalogUrl ?? (this.provider.adapter === "mswarm" ? new URL("/v1/swarm/self-hosted/agents?include_load_balanced=true", base).toString() : `${this.provider.baseUrl.replace(/\/$/, "")}/models`);
|
|
138
139
|
const payload = record(await this.discoveryJson(url, signal));
|
|
139
140
|
const items = payload.agents ?? payload.data;
|
|
140
141
|
if (!Array.isArray(items))
|
|
141
142
|
throw new Error("Invalid model catalog response");
|
|
142
143
|
const entries = items.map(item => {
|
|
143
144
|
const raw = record(item);
|
|
144
|
-
const aliases = [raw.slug, raw.public_model_id, raw.default_model, raw.id].filter((v) => typeof v === "string" && !!v);
|
|
145
|
+
const aliases = [raw.slug, raw.public_model_id, raw.default_model, raw.id, ...(raw.pool_scope === "owner" ? [raw.canonical_model_id] : [])].filter((v) => typeof v === "string" && !!v);
|
|
145
146
|
return { id: aliases[0] ?? "", aliases, backend: raw.adapter === "strata-local" ? "strata" : typeof raw.backend === "string" ? raw.backend : typeof raw.adapter === "string" ? raw.adapter : undefined,
|
|
146
147
|
health: String(raw.health_status ?? "unknown"), supportsTools: raw.supports_tools === true,
|
|
147
148
|
contextWindow: typeof raw.context_window === "number" ? raw.context_window : undefined,
|
|
148
149
|
operations: Array.isArray(raw.operations) ? raw.operations.map(v => typeof v === "string" ? v : String(record(v).type ?? "")) : [], raw };
|
|
149
150
|
}).filter(x => x.id);
|
|
151
|
+
entries.sort((a, b) => Number(b.raw.pool_scope === "owner") - Number(a.raw.pool_scope === "owner")
|
|
152
|
+
|| Number(b.raw.member_count ?? 0) - Number(a.raw.member_count ?? 0) || a.id.localeCompare(b.id));
|
|
150
153
|
this.cache = { key, expires: Date.now() + 30000, entries };
|
|
151
154
|
return entries;
|
|
152
155
|
}
|
|
@@ -173,7 +176,9 @@ export class ModelServiceClient {
|
|
|
173
176
|
endpoint.pathname = ["", "/v1"].includes(endpoint.pathname)
|
|
174
177
|
? "/v1/swarm/self-hosted/openai/models" : `${endpoint.pathname}/models`;
|
|
175
178
|
const payload = record(await this.discoveryJson(endpoint.href, signal).catch(error => {
|
|
176
|
-
|
|
179
|
+
// Keep the service error as the cause so the controller can tell a
|
|
180
|
+
// temporary outage from a real contract mismatch and wait it out.
|
|
181
|
+
throw new NativeReasoningTransportError(`Native reasoning preflight failed before inference: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
177
182
|
}));
|
|
178
183
|
const models = Array.isArray(payload.data) ? payload.data.map(record) : [];
|
|
179
184
|
const model = models.find(item => [item.id, item.agent_slug, item.remote_slug].includes(modelId));
|
|
@@ -211,31 +216,48 @@ export class ConfiguredProvider {
|
|
|
211
216
|
async select(operation, signal, requireTools = false) {
|
|
212
217
|
const candidates = resolveBinding(this.resolved.config, this.binding, operation);
|
|
213
218
|
const reasons = [];
|
|
219
|
+
const refreshed = new Set();
|
|
214
220
|
for (const candidate of candidates) {
|
|
215
221
|
const { id, model } = candidate;
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
222
|
+
const client = this.client(model.provider);
|
|
223
|
+
let catalog = await client.catalog(signal);
|
|
224
|
+
for (;;) {
|
|
225
|
+
// A canonical model alias can identify several pools/backends. Inspect
|
|
226
|
+
// every matching entry, but never widen an explicitly pinned pool ID.
|
|
227
|
+
const exact = catalog.filter(entry => entry.id === model.catalogId);
|
|
228
|
+
const matches = exact.length ? exact : catalog.filter(entry => entry.aliases.includes(model.catalogId));
|
|
229
|
+
let transient = false;
|
|
230
|
+
const failures = [];
|
|
231
|
+
for (const actual of matches) {
|
|
232
|
+
if (model.backend && actual.backend !== model.backend) {
|
|
233
|
+
failures.push("backend identity not verified");
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (actual.operations.length && !actual.operations.includes(operation)) {
|
|
237
|
+
failures.push("unsupported operation");
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (requireTools && (!model.supportsTools || this.resolved.config.providers[model.provider].adapter === "mswarm" && !actual.supportsTools)) {
|
|
241
|
+
failures.push("tools unavailable");
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (!["healthy", "unknown", "ready"].includes(actual.health)) {
|
|
245
|
+
failures.push(actual.health);
|
|
246
|
+
transient || (transient = ["unreachable", "unhealthy", "offline"].includes(actual.health));
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
return { id, model, actual, provider: this.resolved.config.providers[model.provider] };
|
|
250
|
+
}
|
|
251
|
+
// Revalidate temporary health once instead of failing from a stale
|
|
252
|
+
// 30-second cache. Entitlement/quota/capability denials remain final.
|
|
253
|
+
if (transient && !refreshed.has(model.provider)) {
|
|
254
|
+
refreshed.add(model.provider);
|
|
255
|
+
catalog = await client.catalog(signal, true);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
reasons.push(`${id}: ${failures.join(", ") || "not entitled/advertised"}`);
|
|
259
|
+
break;
|
|
237
260
|
}
|
|
238
|
-
return { id, model, actual, provider: this.resolved.config.providers[model.provider] };
|
|
239
261
|
}
|
|
240
262
|
throw new Error(`No eligible configured ${this.binding} route: ${reasons.join("; ")}`);
|
|
241
263
|
}
|
|
@@ -246,20 +268,21 @@ export class ConfiguredProvider {
|
|
|
246
268
|
throw new Error("Model requestId must be a UUID for this inference attempt");
|
|
247
269
|
}
|
|
248
270
|
const { id, model, provider, actual } = await this.select("chat.completions", request.signal, !!request.tools?.length);
|
|
249
|
-
const invocation = { id: requestId, binding: this.binding, configHash: this.resolved.hash, modelId: id, catalogId: model.catalogId, backend: actual.backend, host: model.host };
|
|
271
|
+
const invocation = { id: requestId, binding: this.binding, configHash: this.resolved.hash, modelId: id, catalogId: model.catalogId, resolvedCatalogId: actual.id, backend: actual.backend, host: model.host };
|
|
250
272
|
const nativeReasoning = this.options.effort ? model.reasoning?.[this.options.effort] : undefined;
|
|
251
273
|
if (nativeReasoning)
|
|
252
274
|
invocation.nativeReasoningRequest = { ...nativeReasoning };
|
|
253
275
|
if (nativeReasoning)
|
|
254
|
-
await this.client(model.provider).requireNativeReasoning(
|
|
255
|
-
const
|
|
256
|
-
const
|
|
257
|
-
if (
|
|
276
|
+
await this.client(model.provider).requireNativeReasoning(actual.id, Object.keys(nativeReasoning), request.signal);
|
|
277
|
+
const inputEstimate = estimateProviderInputTokens(request);
|
|
278
|
+
const available = Math.floor(Math.min(model.contextWindow, actual.contextWindow ?? model.contextWindow) - inputEstimate);
|
|
279
|
+
if (available < 128)
|
|
258
280
|
throw new Error("Context budget exceeded; checkpoint and compact before continuing");
|
|
281
|
+
const maxTokens = Math.min(request.maxTokens ?? model.maxOutputTokens, model.maxOutputTokens, available);
|
|
259
282
|
const bounded = { ...request, requestId, maxTokens, stream: request.stream === true && model.supportsStreaming === true };
|
|
260
283
|
await this.options.beforeRequest?.(invocation, bounded);
|
|
261
284
|
const adapter = new OpenAiCompatibleProvider({
|
|
262
|
-
model: model.catalogId, baseUrl: provider.baseUrl, apiKey: this.credentials[model.provider] ?? await providerCredential(provider), timeoutMs:
|
|
285
|
+
model: provider.adapter === "mswarm" ? actual.id : model.catalogId, baseUrl: provider.baseUrl, apiKey: this.credentials[model.provider] ?? await providerCredential(provider), timeoutMs: 86400000,
|
|
263
286
|
supportsStreaming: model.supportsStreaming ?? true, supportsTools: model.supportsTools,
|
|
264
287
|
headers: provider.adapter === "mswarm" ? { ...modelCallerHeaders(this.caller), "x-request-id": requestId } : undefined, retryTransient: false,
|
|
265
288
|
extraBody: nativeReasoning,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ModelServiceError } from "./ModelServiceError.js";
|
|
2
|
+
import type { ProviderRequest, ProviderResponse } from "./ProviderTypes.js";
|
|
3
|
+
export declare const MODEL_CAPACITY_WAIT_MS: number;
|
|
4
|
+
/** An explicit shared-pool refusal: the service rejected the request before any
|
|
5
|
+
* inference ran, so it costs nothing and waiting is the correct response. */
|
|
6
|
+
export declare const isCapacityRefusal: (error: unknown) => error is ModelServiceError;
|
|
7
|
+
/** Delay before the next capacity retry, or undefined when waiting should stop.
|
|
8
|
+
* Long Retry-After values remain refusals rather than silent multi-minute stalls. */
|
|
9
|
+
export declare function capacityRetryDelayMs(error: unknown, attempt: number, waitedMs: number, maxWaitMs?: number, random?: () => number): number | undefined;
|
|
10
|
+
/** Shared capacity policy for callers without Codali's session recovery, so a
|
|
11
|
+
* comparison arm is not failed by contention the other arm waits through. */
|
|
12
|
+
export declare function generateWithCapacityWait(generate: (request: ProviderRequest) => Promise<ProviderResponse>, request: ProviderRequest, options?: {
|
|
13
|
+
maxWaitMs?: number;
|
|
14
|
+
onWait?: (details: {
|
|
15
|
+
attempt: number;
|
|
16
|
+
waitMs: number;
|
|
17
|
+
waitedMs: number;
|
|
18
|
+
error: ModelServiceError;
|
|
19
|
+
}) => void | Promise<void>;
|
|
20
|
+
}): Promise<ProviderResponse>;
|
|
21
|
+
//# sourceMappingURL=ModelCapacityWait.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ModelCapacityWait.d.ts","sourceRoot":"","sources":["../../src/providers/ModelCapacityWait.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE5E,eAAO,MAAM,sBAAsB,QAAc,CAAC;AAIlD;6EAC6E;AAC7E,eAAO,MAAM,iBAAiB,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,iBAC4C,CAAC;AAEzG;qFACqF;AACrF,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,SAAyB,EAAE,MAAM,eAAc,GAAG,MAAM,GAAG,SAAS,CAOpK;AAED;6EAC6E;AAC7E,wBAAsB,wBAAwB,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,eAAe,EACxI,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,iBAAiB,CAAA;KAAE,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAa9L"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { ModelServiceError } from "./ModelServiceError.js";
|
|
3
|
+
export const MODEL_CAPACITY_WAIT_MS = 30 * 60000;
|
|
4
|
+
const MAX_HONORED_RETRY_AFTER_SECONDS = 30;
|
|
5
|
+
const MAX_BACKOFF_MS = 60000;
|
|
6
|
+
/** An explicit shared-pool refusal: the service rejected the request before any
|
|
7
|
+
* inference ran, so it costs nothing and waiting is the correct response. */
|
|
8
|
+
export const isCapacityRefusal = (error) => error instanceof ModelServiceError
|
|
9
|
+
&& error.code === "rate_limited" && (error.responseReason === "capacity_busy" || error.status === 429);
|
|
10
|
+
/** Delay before the next capacity retry, or undefined when waiting should stop.
|
|
11
|
+
* Long Retry-After values remain refusals rather than silent multi-minute stalls. */
|
|
12
|
+
export function capacityRetryDelayMs(error, attempt, waitedMs, maxWaitMs = MODEL_CAPACITY_WAIT_MS, random = Math.random) {
|
|
13
|
+
if (!isCapacityRefusal(error))
|
|
14
|
+
return undefined;
|
|
15
|
+
const retryAfter = error.retryAfterSeconds ?? 0;
|
|
16
|
+
if (retryAfter > MAX_HONORED_RETRY_AFTER_SECONDS)
|
|
17
|
+
return undefined;
|
|
18
|
+
const backoff = Math.min(MAX_BACKOFF_MS, 2000 * 2 ** Math.min(attempt, 10)) * (0.75 + random() * 0.5);
|
|
19
|
+
const waitMs = Math.round(Math.max(backoff, retryAfter * 1000));
|
|
20
|
+
return waitedMs + waitMs > maxWaitMs ? undefined : waitMs;
|
|
21
|
+
}
|
|
22
|
+
/** Shared capacity policy for callers without Codali's session recovery, so a
|
|
23
|
+
* comparison arm is not failed by contention the other arm waits through. */
|
|
24
|
+
export async function generateWithCapacityWait(generate, request, options = {}) {
|
|
25
|
+
let waitedMs = 0;
|
|
26
|
+
for (let attempt = 0;; attempt++) {
|
|
27
|
+
try {
|
|
28
|
+
return await generate(request);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const waitMs = capacityRetryDelayMs(error, attempt, waitedMs, options.maxWaitMs);
|
|
32
|
+
if (waitMs === undefined)
|
|
33
|
+
throw error;
|
|
34
|
+
request.signal?.throwIfAborted();
|
|
35
|
+
await options.onWait?.({ attempt: attempt + 1, waitMs, waitedMs, error: error });
|
|
36
|
+
await delay(waitMs, undefined, { signal: request.signal });
|
|
37
|
+
waitedMs += waitMs;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -1,13 +1,22 @@
|
|
|
1
|
-
export type ModelServiceErrorCode = "authentication_failed" | "entitlement_missing" | "quota_exhausted" | "rate_limited" | "service_unavailable" | "model_unavailable" | "invalid_request" | "invalid_response" | "context_length_exceeded";
|
|
1
|
+
export type ModelServiceErrorCode = "authentication_failed" | "entitlement_missing" | "quota_exhausted" | "rate_limited" | "service_unavailable" | "model_unavailable" | "invalid_request" | "request_conflict" | "invalid_response" | "context_length_exceeded";
|
|
2
2
|
/** Transport diagnostics contain stable classifications, never an upstream body. */
|
|
3
3
|
export declare class ModelServiceError extends Error {
|
|
4
4
|
readonly code: ModelServiceErrorCode;
|
|
5
5
|
readonly status: number;
|
|
6
6
|
readonly retryAfterSeconds?: number | undefined;
|
|
7
7
|
readonly nativeContextRefused: boolean;
|
|
8
|
+
readonly responseReason?: "output_limit" | "incomplete_stream" | "capacity_busy" | undefined;
|
|
9
|
+
/** A rejected completion can still carry real usage and recoverable prose.
|
|
10
|
+
* Partial tool arguments are deliberately never exposed for execution. */
|
|
11
|
+
responseUsage?: {
|
|
12
|
+
inputTokens?: number;
|
|
13
|
+
outputTokens?: number;
|
|
14
|
+
totalTokens?: number;
|
|
15
|
+
};
|
|
16
|
+
partialText?: string;
|
|
8
17
|
/** Set by Runner, not inferred from an HTTP status or upstream payload. */
|
|
9
18
|
completedModelCalls?: number;
|
|
10
|
-
constructor(code: ModelServiceErrorCode, status: number, retryAfterSeconds?: number | undefined, nativeContextRefused?: boolean);
|
|
19
|
+
constructor(code: ModelServiceErrorCode, status: number, retryAfterSeconds?: number | undefined, nativeContextRefused?: boolean, responseReason?: "output_limit" | "incomplete_stream" | "capacity_busy" | undefined);
|
|
11
20
|
/** A relay may already have sent HTTP 200 headers when the model fails. */
|
|
12
21
|
static fromRelayError(error: unknown): ModelServiceError | undefined;
|
|
13
22
|
static fromResponse(response: Response): Promise<ModelServiceError>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelServiceError.d.ts","sourceRoot":"","sources":["../../src/providers/ModelServiceError.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG,qBAAqB,GAAG,iBAAiB,GAAG,cAAc,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,kBAAkB,GAAG,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"ModelServiceError.d.ts","sourceRoot":"","sources":["../../src/providers/ModelServiceError.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG,qBAAqB,GAAG,iBAAiB,GAAG,cAAc,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,kBAAkB,GAAG,kBAAkB,GAAG,yBAAyB,CAAC;AAUjQ,oFAAoF;AACpF,qBAAa,iBAAkB,SAAQ,KAAK;IAO9B,QAAQ,CAAC,IAAI,EAAE,qBAAqB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM;IAAE,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM;IAC5G,QAAQ,CAAC,oBAAoB;IAAU,QAAQ,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,mBAAmB,GAAG,eAAe;IAPzH;8EAC0E;IAC1E,aAAa,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACtF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,2EAA2E;IAC3E,mBAAmB,CAAC,EAAE,MAAM,CAAC;gBACR,IAAI,EAAE,qBAAqB,EAAW,MAAM,EAAE,MAAM,EAAW,iBAAiB,CAAC,EAAE,MAAM,YAAA,EACnG,oBAAoB,UAAQ,EAAW,cAAc,CAAC,EAAE,cAAc,GAAG,mBAAmB,GAAG,eAAe,YAAA;IAOzH,2EAA2E;IAC3E,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,GAAG,SAAS;WAOvD,YAAY,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC;CA6B1E"}
|
|
@@ -8,13 +8,18 @@ function nativeContextRefusal(error) {
|
|
|
8
8
|
}
|
|
9
9
|
/** Transport diagnostics contain stable classifications, never an upstream body. */
|
|
10
10
|
export class ModelServiceError extends Error {
|
|
11
|
-
constructor(code, status, retryAfterSeconds, nativeContextRefused = false) {
|
|
12
|
-
super(`Model service HTTP ${status}: ${code}${code === "authentication_failed" ? "; authenticate with codali login" : code === "context_length_exceeded" ? "; checkpoint and reduce context before continuing" : ""}`);
|
|
11
|
+
constructor(code, status, retryAfterSeconds, nativeContextRefused = false, responseReason) {
|
|
12
|
+
super(`Model service HTTP ${status}: ${code}${responseReason === "output_limit" ? "; the model reached its per-response output limit before finishing. No partial tool call was executed; continue with smaller file patches" : responseReason === "incomplete_stream" ? "; the response stream ended before completion. No partial tool call was executed" : code === "authentication_failed" ? "; authenticate with codali login" : code === "context_length_exceeded" ? "; checkpoint and reduce context before continuing" : ""}`);
|
|
13
13
|
this.code = code;
|
|
14
14
|
this.status = status;
|
|
15
15
|
this.retryAfterSeconds = retryAfterSeconds;
|
|
16
16
|
this.nativeContextRefused = nativeContextRefused;
|
|
17
|
+
this.responseReason = responseReason;
|
|
17
18
|
this.name = "ModelServiceError";
|
|
19
|
+
if (responseReason === "capacity_busy")
|
|
20
|
+
this.message += "; all compatible model workers are busy; retry after capacity becomes available";
|
|
21
|
+
if (code === "request_conflict")
|
|
22
|
+
this.message += "; the service reported a request conflict. Completion and usage are unconfirmed; inspect request status before retrying";
|
|
18
23
|
}
|
|
19
24
|
/** A relay may already have sent HTTP 200 headers when the model fails. */
|
|
20
25
|
static fromRelayError(error) {
|
|
@@ -29,6 +34,7 @@ export class ModelServiceError extends Error {
|
|
|
29
34
|
let serverCode = "";
|
|
30
35
|
let contextRefused = false;
|
|
31
36
|
let nativeRefused = false;
|
|
37
|
+
let capacityBusy = false;
|
|
32
38
|
if (response.body) {
|
|
33
39
|
const reader = response.body.getReader();
|
|
34
40
|
const chunks = [];
|
|
@@ -46,6 +52,7 @@ export class ModelServiceError extends Error {
|
|
|
46
52
|
const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
47
53
|
if (typeof (payload.error?.code ?? payload.code) === "string")
|
|
48
54
|
serverCode = String(payload.error?.code ?? payload.code);
|
|
55
|
+
capacityBusy = response.status === 409 && serverCode === "conflict" && payload.details?.reason_code === "all_compatible_nodes_busy";
|
|
49
56
|
nativeRefused = response.status === 400 && !!payload.error && nativeContextRefusal(payload.error);
|
|
50
57
|
contextRefused = response.status === 400 && (serverCode === "context_length_exceeded" || nativeRefused);
|
|
51
58
|
}
|
|
@@ -58,12 +65,13 @@ export class ModelServiceError extends Error {
|
|
|
58
65
|
const code = response.status === 401 ? "authentication_failed"
|
|
59
66
|
: response.status === 403 ? "entitlement_missing"
|
|
60
67
|
: ["quota_exceeded", "quota_exhausted", "insufficient_quota", "credits_exhausted", "insufficient_credits"].includes(serverCode) || response.status === 402 ? "quota_exhausted"
|
|
61
|
-
: response.status === 429 ? "rate_limited"
|
|
68
|
+
: response.status === 429 || capacityBusy ? "rate_limited"
|
|
62
69
|
: response.status === 404 ? "model_unavailable"
|
|
63
70
|
: contextRefused ? "context_length_exceeded"
|
|
64
71
|
: ["structured_output_failed", "invalid_response"].includes(serverCode) ? "invalid_response"
|
|
65
|
-
: response.status
|
|
72
|
+
: response.status === 409 ? "request_conflict"
|
|
73
|
+
: response.status >= 500 ? "service_unavailable" : "invalid_request";
|
|
66
74
|
const retry = Number(response.headers.get("retry-after"));
|
|
67
|
-
return new ModelServiceError(code, response.status, response.headers.has("retry-after") && Number.isFinite(retry) && retry >= 0 ? Math.min(retry, 3600) : undefined, nativeRefused);
|
|
75
|
+
return new ModelServiceError(code, response.status, response.headers.has("retry-after") && Number.isFinite(retry) && retry >= 0 ? Math.min(retry, 3600) : capacityBusy ? 2 : undefined, nativeRefused, capacityBusy ? "capacity_busy" : undefined);
|
|
68
76
|
}
|
|
69
77
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenAiCompatibleProvider.d.ts","sourceRoot":"","sources":["../../src/providers/OpenAiCompatibleProvider.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,QAAQ,EACR,cAAc,EAEd,eAAe,EACf,gBAAgB,EAGjB,MAAM,oBAAoB,CAAC;AAmK5B,eAAO,MAAM,uBAAuB,GAClC,KAAK,MAAM,EACX,MAAM,WAAW,EACjB,aAAa,eAAe,KAC3B,OAAO,CAAC,QAAQ,CAclB,CAAC;AAEF,qBAAa,wBAAyB,YAAW,QAAQ;IAS3C,OAAO,CAAC,MAAM;IAR1B,+EAA+E;IAC/E,QAAQ,CAAC,iBAAiB,QAAQ;IAElC,IAAI,SAAuB;IAC3B,OAAO,CAAC,WAAW,CAAoC;IACvD,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,sBAAsB,CAAoC;gBAE9C,MAAM,EAAE,cAAc;IAWpC,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"OpenAiCompatibleProvider.d.ts","sourceRoot":"","sources":["../../src/providers/OpenAiCompatibleProvider.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,QAAQ,EACR,cAAc,EAEd,eAAe,EACf,gBAAgB,EAGjB,MAAM,oBAAoB,CAAC;AAmK5B,eAAO,MAAM,uBAAuB,GAClC,KAAK,MAAM,EACX,MAAM,WAAW,EACjB,aAAa,eAAe,KAC3B,OAAO,CAAC,QAAQ,CAclB,CAAC;AAEF,qBAAa,wBAAyB,YAAW,QAAQ;IAS3C,OAAO,CAAC,MAAM;IAR1B,+EAA+E;IAC/E,QAAQ,CAAC,iBAAiB,QAAQ;IAElC,IAAI,SAAuB;IAC3B,OAAO,CAAC,WAAW,CAAoC;IACvD,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,sBAAsB,CAAoC;gBAE9C,MAAM,EAAE,cAAc;IAWpC,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAyQnE,OAAO,CAAC,WAAW;CA0BpB"}
|
|
@@ -175,7 +175,14 @@ export class OpenAiCompatibleProvider {
|
|
|
175
175
|
: undefined;
|
|
176
176
|
const messages = request.messages.map((message) => ({
|
|
177
177
|
role: message.role,
|
|
178
|
-
content:
|
|
178
|
+
content: message.images?.length ? [
|
|
179
|
+
{ type: "text", text: modelContextText(message.content) },
|
|
180
|
+
...message.images.map(image => {
|
|
181
|
+
if (message.role !== "user" || !/^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(image.dataUrl) || image.dataUrl.length > 3000000)
|
|
182
|
+
throw new Error("Only bounded user PNG images are supported");
|
|
183
|
+
return { type: "image_url", image_url: { url: image.dataUrl } };
|
|
184
|
+
}),
|
|
185
|
+
] : modelContextText(message.content),
|
|
179
186
|
name: message.name,
|
|
180
187
|
tool_call_id: message.toolCallId,
|
|
181
188
|
tool_calls: message.toolCalls?.map((call) => ({
|
|
@@ -332,8 +339,12 @@ export class OpenAiCompatibleProvider {
|
|
|
332
339
|
await reader.cancel().catch(() => undefined);
|
|
333
340
|
reader.releaseLock();
|
|
334
341
|
}
|
|
335
|
-
if ((!ended && !finishReason) || finishReason === "length")
|
|
336
|
-
|
|
342
|
+
if ((!ended && !finishReason) || finishReason === "length") {
|
|
343
|
+
const error = new ModelServiceError("invalid_response", 200, undefined, false, finishReason === "length" ? "output_limit" : "incomplete_stream");
|
|
344
|
+
error.responseUsage = usage ? { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens, totalTokens: usage.total_tokens } : undefined;
|
|
345
|
+
error.partialText = content || undefined;
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
337
348
|
if (!content && !toolCallMap.size)
|
|
338
349
|
throw new Error("Model stream returned no content or tool calls");
|
|
339
350
|
for (const call of toolCallMap.values()) {
|
|
@@ -380,8 +391,12 @@ export class OpenAiCompatibleProvider {
|
|
|
380
391
|
? message.split(this.config.apiKey).join("[redacted]") : message;
|
|
381
392
|
throw new Error(redacted.slice(0, 600));
|
|
382
393
|
}
|
|
383
|
-
if (raw?.choices?.[0]?.finish_reason === "length")
|
|
384
|
-
|
|
394
|
+
if (raw?.choices?.[0]?.finish_reason === "length") {
|
|
395
|
+
const error = new ModelServiceError("invalid_response", 200, undefined, false, "output_limit");
|
|
396
|
+
error.responseUsage = raw.usage ? { inputTokens: raw.usage.prompt_tokens, outputTokens: raw.usage.completion_tokens, totalTokens: raw.usage.total_tokens } : undefined;
|
|
397
|
+
error.partialText = raw.choices[0].message?.content || undefined;
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
385
400
|
const choice = raw?.choices?.[0]?.message;
|
|
386
401
|
if (!choice) {
|
|
387
402
|
throw new Error("OpenAI-compatible response missing choices");
|
|
@@ -41,6 +41,10 @@ export interface ProviderResponseFormat {
|
|
|
41
41
|
export interface ProviderMessage {
|
|
42
42
|
role: ProviderRole;
|
|
43
43
|
content: string;
|
|
44
|
+
/** Host-read bounded PNG screenshots; never arbitrary URLs fetched by the model service. */
|
|
45
|
+
images?: Array<{
|
|
46
|
+
dataUrl: string;
|
|
47
|
+
}>;
|
|
44
48
|
name?: string;
|
|
45
49
|
toolCallId?: string;
|
|
46
50
|
/** Assistant calls retained alongside the matching tool result messages. */
|
|
@@ -1 +1 @@
|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AC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,sBAAsB,CAAC,EAAE,iCAAiC,CAAC;IAC3D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC/D;AAED,eAAO,MAAM,yBAAyB,GAAI,UAAU,QAAQ,KAAG,OAC1B,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ProviderRequest } from "./ProviderTypes.js";
|
|
2
|
+
/** Image bytes are not text tokens. Reserve conservatively for bounded screenshots;
|
|
3
|
+
* actual server tokenization and receipts remain authoritative. */
|
|
4
|
+
export declare function estimateProviderInputTokens(request: Pick<ProviderRequest, "messages" | "tools" | "responseFormat">): number;
|
|
5
|
+
//# sourceMappingURL=RequestSize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RequestSize.d.ts","sourceRoot":"","sources":["../../src/providers/RequestSize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAE1D;mEACmE;AACnE,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,GAAG,OAAO,GAAG,gBAAgB,CAAC,GAAG,MAAM,CAO3H"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Image bytes are not text tokens. Reserve conservatively for bounded screenshots;
|
|
2
|
+
* actual server tokenization and receipts remain authoritative. */
|
|
3
|
+
export function estimateProviderInputTokens(request) {
|
|
4
|
+
let imageTokens = 0;
|
|
5
|
+
const messages = request.messages.map(({ images, ...message }) => {
|
|
6
|
+
imageTokens += (images?.length ?? 0) * 8192;
|
|
7
|
+
return message;
|
|
8
|
+
});
|
|
9
|
+
return Math.ceil(JSON.stringify({ messages, tools: request.tools, responseFormat: request.responseFormat }).length / 3) + imageTokens;
|
|
10
|
+
}
|