@thanh01.pmt/domain-kit 0.6.0 → 0.6.2
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/LICENSE +21 -0
- package/README.md +10 -10
- package/dist/assembly/index.d.cts +3 -2
- package/dist/assembly/index.d.ts +3 -2
- package/dist/chunk-7A2SG466.mjs +325 -0
- package/dist/chunk-7A2SG466.mjs.map +1 -0
- package/dist/{chunk-DRVOV5ZD.mjs → chunk-DSEJLTUO.mjs} +2 -2
- package/dist/chunk-DSEJLTUO.mjs.map +1 -0
- package/dist/{chunk-2OGNQUXC.mjs → chunk-GVBDM746.mjs} +152 -303
- package/dist/chunk-GVBDM746.mjs.map +1 -0
- package/dist/{chunk-ERDTHXQA.mjs → chunk-H4W3YJLK.mjs} +10 -3
- package/dist/chunk-H4W3YJLK.mjs.map +1 -0
- package/dist/chunk-HRSBIVAW.mjs +3 -0
- package/dist/{chunk-ZKLT27T4.mjs.map → chunk-HRSBIVAW.mjs.map} +1 -1
- package/dist/chunk-IBVXXVGE.mjs +14 -0
- package/dist/chunk-IBVXXVGE.mjs.map +1 -0
- package/dist/{chunk-67GXK3ZE.mjs → chunk-WD3P5V3B.mjs} +3 -2
- package/dist/chunk-WD3P5V3B.mjs.map +1 -0
- package/dist/{chunk-5OMSYKQP.mjs → chunk-ZHMIJEMA.mjs} +33 -18
- package/dist/chunk-ZHMIJEMA.mjs.map +1 -0
- package/dist/{conceptEscalator-DPrs4PwC.d.cts → conceptEscalator-BmMJD8C5.d.cts} +1 -1
- package/dist/{conceptEscalator-BCsw0ys_.d.ts → conceptEscalator-DMsehscs.d.ts} +1 -1
- package/dist/concepts/index.d.cts +4 -3
- package/dist/concepts/index.d.ts +4 -3
- package/dist/{cpp-CZUPqJt9.d.cts → cpp-vlDl6pCL.d.cts} +4 -4
- package/dist/{cpp-CZUPqJt9.d.ts → cpp-vlDl6pCL.d.ts} +4 -4
- package/dist/detector/index.cjs +1 -0
- package/dist/detector/index.cjs.map +1 -1
- package/dist/detector/index.d.cts +2 -2
- package/dist/detector/index.d.ts +2 -2
- package/dist/detector/index.mjs +1 -1
- package/dist/{domainProfileDetector-DHb1T0zB.d.ts → domainProfileDetector-6pjgL-6_.d.ts} +1 -1
- package/dist/{domainProfileDetector-bzugdQmS.d.cts → domainProfileDetector-BsADsuRV.d.cts} +1 -1
- package/dist/{domainProfileSchema-CwT3Ffsw.d.cts → domainProfileSchema-779FGk14.d.cts} +38 -1
- package/dist/{domainProfileSchema-CwT3Ffsw.d.ts → domainProfileSchema-779FGk14.d.ts} +38 -1
- package/dist/extractors/index.d.cts +3 -3
- package/dist/extractors/index.d.ts +3 -3
- package/dist/feed/index.d.cts +1 -1
- package/dist/feed/index.d.ts +1 -1
- package/dist/graph/index.cjs +236 -57
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +27 -7
- package/dist/graph/index.d.ts +27 -7
- package/dist/graph/index.mjs +4 -2
- package/dist/{hybridGraphPipeline-CocfYe4d.d.cts → hybridGraphPipeline-B4mamLim.d.cts} +1 -1
- package/dist/{hybridGraphPipeline-9dRKJj7r.d.ts → hybridGraphPipeline-D2_1GUva.d.ts} +1 -1
- package/dist/index.cjs +278 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -9
- package/dist/index.d.ts +10 -9
- package/dist/index.mjs +12 -10
- package/dist/{keywordExtractor-BxlGRMHC.d.cts → keywordExtractor-1YAFntsn.d.cts} +1 -1
- package/dist/{keywordExtractor-DU5XRN8-.d.ts → keywordExtractor-DWw8z_AF.d.ts} +1 -1
- package/dist/parsers/index.cjs.map +1 -1
- package/dist/parsers/index.d.cts +1 -1
- package/dist/parsers/index.d.ts +1 -1
- package/dist/parsers/index.mjs +1 -1
- package/dist/pipeline/index.cjs +261 -68
- package/dist/pipeline/index.cjs.map +1 -1
- package/dist/pipeline/index.d.cts +10 -9
- package/dist/pipeline/index.d.ts +10 -9
- package/dist/pipeline/index.mjs +8 -6
- package/dist/schemas/index.cjs +8 -0
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +2 -2
- package/dist/schemas/index.d.ts +2 -2
- package/dist/schemas/index.mjs +1 -1
- package/dist/utils/llmClient.cjs +344 -0
- package/dist/utils/llmClient.cjs.map +1 -0
- package/dist/utils/llmClient.d.cts +118 -0
- package/dist/utils/llmClient.d.ts +118 -0
- package/dist/utils/llmClient.mjs +4 -0
- package/dist/utils/llmClient.mjs.map +1 -0
- package/dist/utils/llmTransportResult.cjs +16 -0
- package/dist/utils/llmTransportResult.cjs.map +1 -0
- package/dist/utils/llmTransportResult.d.cts +36 -0
- package/dist/utils/llmTransportResult.d.ts +36 -0
- package/dist/utils/llmTransportResult.mjs +3 -0
- package/dist/utils/llmTransportResult.mjs.map +1 -0
- package/package.json +9 -10
- package/dist/chunk-2OGNQUXC.mjs.map +0 -1
- package/dist/chunk-5OMSYKQP.mjs.map +0 -1
- package/dist/chunk-67GXK3ZE.mjs.map +0 -1
- package/dist/chunk-DRVOV5ZD.mjs.map +0 -1
- package/dist/chunk-ERDTHXQA.mjs.map +0 -1
- package/dist/chunk-ZKLT27T4.mjs +0 -3
- package/dist/llmClient-CX5uUiQ1.d.cts +0 -60
- package/dist/llmClient-CX5uUiQ1.d.ts +0 -60
- package/dist/{curriculumFeedSchema-DYayelAA.d.ts → curriculumFeedSchema-DK-TUAJZ.d.cts} +8 -8
- package/dist/{curriculumFeedSchema-DYayelAA.d.cts → curriculumFeedSchema-DK-TUAJZ.d.ts} +8 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Tony Pham
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -112,7 +112,7 @@ them, instead of surfacing as a broken lesson three packages later.
|
|
|
112
112
|
runProjectGraph runKnowledgeGraph runProjectGraphPipeline + runKnowledgeGraphPipeline
|
|
113
113
|
Pipeline Pipeline (two full graph runs), then:
|
|
114
114
|
STEP_1 scan/ (parseSyllabus generateHybridGraph()
|
|
115
|
-
select/
|
|
115
|
+
select/regex first if raw STEP_1 feature-concept links
|
|
116
116
|
STEP_2 keyword syllabusText) STEP_2 decomposePhases
|
|
117
117
|
extract generateKnowledge (auditPhasePlan fail-closed)
|
|
118
118
|
STEP_3 SDK API Graph: STEP_3 totals
|
|
@@ -136,8 +136,8 @@ them, instead of surfacing as a broken lesson three packages later.
|
|
|
136
136
|
v
|
|
137
137
|
+------------------------------------------------------------------------------+
|
|
138
138
|
| LAYER 3 - emitCurriculumFeed(graph) - pure projection, no LLM |
|
|
139
|
-
|
|
|
140
|
-
| (
|
|
139
|
+
| Options built in ONE shared helper (pipeline/emitFeed.ts, R3 fixed): |
|
|
140
|
+
| router (project), knowledge orchestrator, hybrid orchestrator. |
|
|
141
141
|
| learning_nodes[] - dependency_edges[] - suggested_groupings[] - phases[] |
|
|
142
142
|
| (phases[] is filled ONLY by the hybrid emitter - R1) |
|
|
143
143
|
+------------------------------------+-----------------------------------------+
|
|
@@ -190,10 +190,10 @@ verified against. Full postmortems: deep review 2026-10-05 (app repo,
|
|
|
190
190
|
|---|---|---|---|
|
|
191
191
|
| R1 | **FIXED 2026-10-07.** Was: `hybrid` without `repoDir` silently degraded to a knowledge-graph feed (only a `warnings[]` entry). Now a FORCED hybrid throws (fail-closed); an auto-detected downgrade returns a structured `modeDowngrade { from, to, reason }`. | `src/pipeline/domainRouter.ts` | High |
|
|
192
192
|
| R2 | **FIXED 2026-10-07.** Was: the hybrid branch's knowledge legs dropped `knowledgeTreePath`/`proposalsPath`, so STEP_2_5 ran in concept mode but not hybrid mode for the same subject. Now both hybrid legs pass them through. | `src/pipeline/domainRouter.ts` | High |
|
|
193
|
-
| R3 |
|
|
194
|
-
| R4 | Cycle breaking
|
|
195
|
-
| R5 | STEP_2_5 only
|
|
196
|
-
| R6 |
|
|
193
|
+
| R3 | **FIXED 2026-10-07.** Was: feed emission invoked from three places with drifting options (`hallucinationCount` only from the router). Now ONE shared helper `emitNormalizedFeed()` in `src/pipeline/emitFeed.ts` builds options for all three call sites (lives in pipeline/ so feed/ keeps its no-llmClient invariant). | `src/pipeline/emitFeed.ts` | Medium |
|
|
194
|
+
| R4 | Cycle breaking removes the DFS back-edge positionally (mechanism verified 2026-10-07: NO "weakest edge"/link-counting weighting — that was the old misleading log text, now fixed) and only warns. Which edge is dropped decides teaching order. | `src/graph/knowledgeGraphVerifier.ts:69` | Medium |
|
|
195
|
+
| R5 | **FIXED 2026-10-07.** Was: STEP_2_5 only ran when `knowledgeTreePath` was provided and the absence of tree anchoring was silent. Now the pipeline pushes an explicit warning (all concepts then stay `proposed_new`). | `src/graph/knowledgeGraphPipeline.ts` | Medium |
|
|
196
|
+
| R6 | **FIXED 2026-10-07.** Was: tree prereq codes outside THIS analysis were dropped silently. Now one aggregated warning lists unmapped tree prereq codes (deduped, display capped at 10). | `src/graph/knowledgeGraphPipeline.ts` | Medium |
|
|
197
197
|
| R7 | `emitCurriculumFeed` dispatches by shape (key presence) and pass-through-validates anything that "looks like a feed" (CF-8 in the deep review). | `src/feed/curriculumFeedEmitter.ts:833-839` | Low |
|
|
198
198
|
| R8 | Non-fatal pedagogy issues funnel into a single lossy `warnings[]` string channel; some drops only hit `console.warn` (e.g. a concept falling out of `learning_path`, KG-3). Structured diagnostics per ADR-0002 should replace string warnings. | deep review KG-3 | Medium |
|
|
199
199
|
| R9 | **FIXED 2026-10-07.** Was: ASCII-only regex assumptions broke on Vietnamese text (KG-1) - empty derived keywords threw, registries filled with fragments. Now a shared `stripDiacritics()` (NFD + combining-mark strip + `đ`→`d`, incl. the precomposed-base-letter case NFD cannot decompose) backs every tokenizer; regression tests in `src/__tests__/vietnamese-tokenization.test.ts`. | `src/utils/diacritics.ts` | Critical |
|
|
@@ -255,7 +255,7 @@ recomputed at the branch.
|
|
|
255
255
|
STEP_1 parseSyllabus(syllabusText) → structured units/topics
|
|
256
256
|
LLM decomposes the subject → concepts + prerequisites + problem_types
|
|
257
257
|
+ categories + techniques. The syllabus is truncated at
|
|
258
|
-
KG_MAX_SYLLABUS_CHARS (default
|
|
258
|
+
KG_MAX_SYLLABUS_CHARS (default 32000) with a warning.
|
|
259
259
|
|
|
260
260
|
STEP_2 validate & clean
|
|
261
261
|
· description shorter than 50 chars → warning
|
|
@@ -527,7 +527,7 @@ LLM_MAX_TOKENS=65536 # Max output tokens (default)
|
|
|
527
527
|
LLM_MIN_REQUEST_INTERVAL_MS=2500 # process-wide pacing; 0 disables
|
|
528
528
|
|
|
529
529
|
# Extra knobs the pipelines read directly:
|
|
530
|
-
KG_MAX_SYLLABUS_CHARS=
|
|
530
|
+
KG_MAX_SYLLABUS_CHARS=32000 # syllabus truncation before decomposition
|
|
531
531
|
KG_MAX_TOKENS=65536 # knowledge-graph generation budget
|
|
532
532
|
LLM_REQUEST_TIMEOUT_MS=300000 # per-request cap
|
|
533
533
|
```
|
|
@@ -1278,7 +1278,7 @@ orchestrators call it for theirs.
|
|
|
1278
1278
|
|
|
1279
1279
|
| Step | What happens | Fail mode |
|
|
1280
1280
|
|---|---|---|
|
|
1281
|
-
| `STEP_1` | parse the syllabus into structured units/topics, then LLM-decompose the subject into concepts, prerequisites, `problem_types`, categories | syllabus truncated at `KG_MAX_SYLLABUS_CHARS` (default
|
|
1281
|
+
| `STEP_1` | parse the syllabus into structured units/topics, then LLM-decompose the subject into concepts, prerequisites, `problem_types`, categories | syllabus truncated at `KG_MAX_SYLLABUS_CHARS` (default 32000) + warning |
|
|
1282
1282
|
| `STEP_2` | validate & clean — description ≥ 50 chars; **keyword registry fail-closed** (empty keywords are derived from name/description; nothing derivable → `throw`); dangling prerequisite edges removed | `throw` when keywords cannot be derived |
|
|
1283
1283
|
| `STEP_2_5` | *only when `knowledgeTreePath` is supplied* — standardize every concept against `mlo-knowlege-tree.tsv` into `standardized` or `proposed_new`; adopted tech-stack keywords merge into the registry; tree prerequisite codes seed internal edges | missing decision for a concept → `throw` |
|
|
1284
1284
|
| `STEP_3` | `detectPrerequisiteCycles()` → `breakPrerequisiteCycles()` at the weakest edge | warnings; edges are removed |
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { u as ProjectGraph, c as Step } from '../projectGraphSchema-DnD7orZV.cjs';
|
|
2
|
-
import { C as ConceptMapping } from '../conceptEscalator-
|
|
2
|
+
import { C as ConceptMapping } from '../conceptEscalator-BmMJD8C5.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../llmClient
|
|
4
|
+
import '../utils/llmClient.cjs';
|
|
5
|
+
import '../utils/llmTransportResult.cjs';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Roadmap assembly — assembles final roadmap with keyword tracking and time awareness.
|
package/dist/assembly/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { u as ProjectGraph, c as Step } from '../projectGraphSchema-DnD7orZV.js';
|
|
2
|
-
import { C as ConceptMapping } from '../conceptEscalator-
|
|
2
|
+
import { C as ConceptMapping } from '../conceptEscalator-DMsehscs.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../llmClient
|
|
4
|
+
import '../utils/llmClient.js';
|
|
5
|
+
import '../utils/llmTransportResult.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Roadmap assembly — assembles final roadmap with keyword tracking and time awareness.
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { transportResultFrom } from './chunk-IBVXXVGE.mjs';
|
|
2
|
+
|
|
3
|
+
// src/utils/llmClient.ts
|
|
4
|
+
function summarizeProvenance(callLog) {
|
|
5
|
+
const providers = [];
|
|
6
|
+
const models = [];
|
|
7
|
+
let failed = 0;
|
|
8
|
+
for (const r of callLog) {
|
|
9
|
+
if (!providers.includes(r.provider)) providers.push(r.provider);
|
|
10
|
+
if (!models.includes(r.model)) models.push(r.model);
|
|
11
|
+
if (!r.ok) failed++;
|
|
12
|
+
}
|
|
13
|
+
return { providers, models, calls: callLog.length, failed_calls: failed, degraded: failed > 0 };
|
|
14
|
+
}
|
|
15
|
+
async function responseJsonCompat(response) {
|
|
16
|
+
const text = await response.text();
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(text);
|
|
19
|
+
} catch {
|
|
20
|
+
const start = text.indexOf("{");
|
|
21
|
+
if (start < 0) {
|
|
22
|
+
throw new LlmClientError(`LLM API returned a non-JSON body: ${text.slice(0, 200)}`);
|
|
23
|
+
}
|
|
24
|
+
let depth = 0;
|
|
25
|
+
let inString = false;
|
|
26
|
+
let escape = false;
|
|
27
|
+
for (let i = start; i < text.length; i++) {
|
|
28
|
+
const ch = text[i];
|
|
29
|
+
if (escape) {
|
|
30
|
+
escape = false;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (ch === "\\") {
|
|
34
|
+
escape = true;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (ch === '"') {
|
|
38
|
+
inString = !inString;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (inString) continue;
|
|
42
|
+
if (ch === "{") depth++;
|
|
43
|
+
if (ch === "}") {
|
|
44
|
+
depth--;
|
|
45
|
+
if (depth === 0) {
|
|
46
|
+
return JSON.parse(text.slice(start, i + 1));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw new LlmClientError(`LLM API returned an unterminated JSON body: ${text.slice(0, 200)}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
var LlmClientError = class extends Error {
|
|
54
|
+
constructor(message, status, cause) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.cause = cause;
|
|
58
|
+
this.name = "LlmClientError";
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
function build9routerProvider(model) {
|
|
62
|
+
const apiKey = process.env.NINEROUTER_API_KEY;
|
|
63
|
+
if (!apiKey) return null;
|
|
64
|
+
const baseUrl = (process.env.NINEROUTER_BASE_URL || "https://ai-router.orchable.app/v1").replace(/^["']|["']$/g, "").trim();
|
|
65
|
+
const label = "9router";
|
|
66
|
+
const modelName = (model || process.env.NINEROUTER_MODEL || "laguna-s-2.1").trim();
|
|
67
|
+
return { label, baseUrl, apiKey, model: modelName };
|
|
68
|
+
}
|
|
69
|
+
function resolve9routerChain(configModel) {
|
|
70
|
+
const primary = build9routerProvider(configModel);
|
|
71
|
+
if (!primary) return [];
|
|
72
|
+
const alt = process.env.NINEROUTER_MODEL_ALT && process.env.NINEROUTER_MODEL_ALT.trim();
|
|
73
|
+
if (!alt) return [primary];
|
|
74
|
+
const secondary = build9routerProvider(alt);
|
|
75
|
+
if (!secondary) return [primary];
|
|
76
|
+
return primary.model === secondary.model ? [primary] : [primary, secondary];
|
|
77
|
+
}
|
|
78
|
+
var MIN_REQUEST_INTERVAL_MS = 2500;
|
|
79
|
+
var requestIntervalMs = Number(process.env.LLM_MIN_REQUEST_INTERVAL_MS || MIN_REQUEST_INTERVAL_MS);
|
|
80
|
+
var lastRequestAt = 0;
|
|
81
|
+
async function pacedDelay() {
|
|
82
|
+
const wait = lastRequestAt + requestIntervalMs - Date.now();
|
|
83
|
+
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
84
|
+
lastRequestAt = Date.now();
|
|
85
|
+
}
|
|
86
|
+
function createLlmClient(config) {
|
|
87
|
+
const chain = resolve9routerChain(config?.model);
|
|
88
|
+
const primary = chain[0];
|
|
89
|
+
if (!primary) {
|
|
90
|
+
throw new LlmClientError(
|
|
91
|
+
"No 9router provider configured. Set NINEROUTER_API_KEY and NINEROUTER_MODEL (or the NINEROUTER_* env defaults expected by the kit)."
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
primary.apiKey;
|
|
95
|
+
primary.baseUrl;
|
|
96
|
+
const model = primary.model;
|
|
97
|
+
if (config?.minRequestIntervalMs !== void 0) {
|
|
98
|
+
requestIntervalMs = Math.max(0, config.minRequestIntervalMs);
|
|
99
|
+
}
|
|
100
|
+
const callLog = [];
|
|
101
|
+
async function chat(messages, options) {
|
|
102
|
+
const temperature = options?.temperature ?? config?.temperature ?? 0.1;
|
|
103
|
+
const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || "65536", 10);
|
|
104
|
+
const attempts = [];
|
|
105
|
+
let lastError = null;
|
|
106
|
+
const TRANSIENT = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
107
|
+
const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 3e5);
|
|
108
|
+
const MAX_CHAIN_ROUNDS = 3;
|
|
109
|
+
for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {
|
|
110
|
+
if (round > 1) {
|
|
111
|
+
attempts.push("round " + (round - 1) + " failed \u2014 backing off 20s before rewalking the chain");
|
|
112
|
+
await new Promise((resolve) => setTimeout(resolve, 2e4));
|
|
113
|
+
}
|
|
114
|
+
for (const provider of chain) {
|
|
115
|
+
const recIdx = callLog.push({ provider: provider.label, model: provider.model, ok: false }) - 1;
|
|
116
|
+
try {
|
|
117
|
+
const headers = {
|
|
118
|
+
"Content-Type": "application/json",
|
|
119
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
120
|
+
};
|
|
121
|
+
const payload = {
|
|
122
|
+
model: provider.model,
|
|
123
|
+
messages,
|
|
124
|
+
temperature,
|
|
125
|
+
max_tokens: maxTokens
|
|
126
|
+
};
|
|
127
|
+
await pacedDelay();
|
|
128
|
+
const doFetch = () => fetch(`${provider.baseUrl}/chat/completions`, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: {
|
|
131
|
+
"Content-Type": "application/json",
|
|
132
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
133
|
+
},
|
|
134
|
+
body: JSON.stringify({
|
|
135
|
+
model: provider.model,
|
|
136
|
+
messages,
|
|
137
|
+
temperature,
|
|
138
|
+
max_tokens: maxTokens
|
|
139
|
+
}),
|
|
140
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
141
|
+
});
|
|
142
|
+
let response;
|
|
143
|
+
try {
|
|
144
|
+
response = await doFetch();
|
|
145
|
+
} catch (netErr) {
|
|
146
|
+
attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) \u2014 retrying once`);
|
|
147
|
+
await new Promise((r) => setTimeout(r, 5e3));
|
|
148
|
+
lastRequestAt = Date.now();
|
|
149
|
+
response = await doFetch();
|
|
150
|
+
}
|
|
151
|
+
if (!response.ok) {
|
|
152
|
+
const body = await response.text().catch(() => "");
|
|
153
|
+
const err = new LlmClientError(
|
|
154
|
+
`[${provider.label}] LLM API error: ${response.status} ${response.statusText} \u2014 ${body.slice(0, 200)}`,
|
|
155
|
+
response.status
|
|
156
|
+
);
|
|
157
|
+
if (response.status === 429) {
|
|
158
|
+
const retryAfterRaw = response.headers.get("retry-after");
|
|
159
|
+
const retryAfterMs = Math.min(
|
|
160
|
+
6e4,
|
|
161
|
+
Math.max(15e3, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1e3)
|
|
162
|
+
);
|
|
163
|
+
attempts.push(`${provider.label}: 429 rate-limited \u2014 backing off ${Math.round(retryAfterMs / 1e3)}s`);
|
|
164
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
|
|
165
|
+
lastRequestAt = Date.now();
|
|
166
|
+
const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
|
|
167
|
+
method: "POST",
|
|
168
|
+
headers,
|
|
169
|
+
body: JSON.stringify(payload),
|
|
170
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
171
|
+
});
|
|
172
|
+
if (!retry.ok) throw err;
|
|
173
|
+
const retryData = await responseJsonCompat(retry);
|
|
174
|
+
const retryContent2 = retryData.choices?.[0]?.message?.content || "";
|
|
175
|
+
if (!retryContent2.trim()) throw err;
|
|
176
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: true };
|
|
177
|
+
const transport2 = transportResultFrom(provider.label, retryData.model || provider.model, {
|
|
178
|
+
usage: retryData.usage,
|
|
179
|
+
framingStripped: true
|
|
180
|
+
});
|
|
181
|
+
return {
|
|
182
|
+
content: retryContent2,
|
|
183
|
+
model: retryData.model || provider.model,
|
|
184
|
+
provider: provider.label,
|
|
185
|
+
attempts: attempts.slice(),
|
|
186
|
+
usage: retryData.usage,
|
|
187
|
+
finishReason: retryData.choices?.[0]?.finish_reason,
|
|
188
|
+
_transport: transport2
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
if (TRANSIENT.has(response.status)) {
|
|
192
|
+
await new Promise((r) => setTimeout(r, 3e3));
|
|
193
|
+
const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
|
|
194
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
195
|
+
method: "POST",
|
|
196
|
+
headers: {
|
|
197
|
+
"Content-Type": "application/json",
|
|
198
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
199
|
+
},
|
|
200
|
+
body: JSON.stringify({
|
|
201
|
+
model: provider.model,
|
|
202
|
+
messages,
|
|
203
|
+
temperature,
|
|
204
|
+
max_tokens: maxTokens
|
|
205
|
+
})
|
|
206
|
+
});
|
|
207
|
+
if (!retry.ok) throw err;
|
|
208
|
+
const retryData = await responseJsonCompat(retry);
|
|
209
|
+
const retryContent = retryData.choices?.[0]?.message?.content || "";
|
|
210
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: true };
|
|
211
|
+
const transport2 = transportResultFrom(provider.label, retryData.model || provider.model, {
|
|
212
|
+
usage: retryData.usage,
|
|
213
|
+
framingStripped: true
|
|
214
|
+
});
|
|
215
|
+
return {
|
|
216
|
+
content: retryContent,
|
|
217
|
+
model: retryData.model || provider.model,
|
|
218
|
+
provider: provider.label,
|
|
219
|
+
attempts: attempts.slice(),
|
|
220
|
+
usage: retryData.usage,
|
|
221
|
+
finishReason: retryData.choices?.[0]?.finish_reason,
|
|
222
|
+
_transport: transport2
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
throw err;
|
|
226
|
+
}
|
|
227
|
+
const data = await responseJsonCompat(response);
|
|
228
|
+
const wrappedError = data.error;
|
|
229
|
+
if (wrappedError) {
|
|
230
|
+
throw new LlmClientError("[" + provider.label + "] upstream error " + (wrappedError.code ?? "") + ": " + (wrappedError.message ?? "unknown"));
|
|
231
|
+
}
|
|
232
|
+
const content = data.choices?.[0]?.message?.content || "";
|
|
233
|
+
if (!content.trim()) {
|
|
234
|
+
throw new LlmClientError("[" + provider.label + "] empty completion returned");
|
|
235
|
+
}
|
|
236
|
+
const transport = transportResultFrom(provider.label, data.model || provider.model, {
|
|
237
|
+
usage: data.usage,
|
|
238
|
+
framingStripped: true
|
|
239
|
+
});
|
|
240
|
+
return {
|
|
241
|
+
content,
|
|
242
|
+
model: data.model || provider.model,
|
|
243
|
+
provider: provider.label,
|
|
244
|
+
attempts: attempts.slice(),
|
|
245
|
+
usage: data.usage,
|
|
246
|
+
finishReason: data.choices?.[0]?.finish_reason,
|
|
247
|
+
_transport: transport
|
|
248
|
+
};
|
|
249
|
+
} catch (err) {
|
|
250
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
251
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: false, error: msg.slice(0, 200) };
|
|
252
|
+
attempts.push(`${provider.label}: ${msg}`);
|
|
253
|
+
lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (round < MAX_CHAIN_ROUNDS) continue;
|
|
257
|
+
throw lastError ?? new LlmClientError("All LLM providers failed (empty chain).");
|
|
258
|
+
}
|
|
259
|
+
throw lastError ?? new LlmClientError("All LLM providers failed after " + MAX_CHAIN_ROUNDS + " rounds.");
|
|
260
|
+
}
|
|
261
|
+
return { chat, model, callLog };
|
|
262
|
+
}
|
|
263
|
+
function parseJsonFromLlm(text) {
|
|
264
|
+
let cleaned = text.trim();
|
|
265
|
+
if (cleaned.startsWith("```json")) {
|
|
266
|
+
cleaned = cleaned.slice(7);
|
|
267
|
+
} else if (cleaned.startsWith("```")) {
|
|
268
|
+
cleaned = cleaned.slice(3);
|
|
269
|
+
}
|
|
270
|
+
if (cleaned.endsWith("```")) {
|
|
271
|
+
cleaned = cleaned.slice(0, -3);
|
|
272
|
+
}
|
|
273
|
+
cleaned = cleaned.trim();
|
|
274
|
+
try {
|
|
275
|
+
return JSON.parse(cleaned);
|
|
276
|
+
} catch {
|
|
277
|
+
const start = cleaned.indexOf("{");
|
|
278
|
+
if (start >= 0) {
|
|
279
|
+
let depth = 0;
|
|
280
|
+
let inString = false;
|
|
281
|
+
let escape = false;
|
|
282
|
+
for (let i = start; i < cleaned.length; i++) {
|
|
283
|
+
const ch = cleaned[i];
|
|
284
|
+
if (escape) {
|
|
285
|
+
escape = false;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (ch === "\\") {
|
|
289
|
+
escape = true;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (ch === '"') {
|
|
293
|
+
inString = !inString;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (inString) continue;
|
|
297
|
+
if (ch === "{") depth++;
|
|
298
|
+
if (ch === "}") {
|
|
299
|
+
depth--;
|
|
300
|
+
if (depth === 0) {
|
|
301
|
+
try {
|
|
302
|
+
return JSON.parse(cleaned.slice(start, i + 1));
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async function llmChatJson(client, systemPrompt, userPrompt, options) {
|
|
313
|
+
const result = await client.chat(
|
|
314
|
+
[
|
|
315
|
+
{ role: "system", content: systemPrompt },
|
|
316
|
+
{ role: "user", content: userPrompt }
|
|
317
|
+
],
|
|
318
|
+
options
|
|
319
|
+
);
|
|
320
|
+
return parseJsonFromLlm(result.content);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export { LlmClientError, build9routerProvider, createLlmClient, llmChatJson, parseJsonFromLlm, resolve9routerChain, responseJsonCompat, summarizeProvenance };
|
|
324
|
+
//# sourceMappingURL=chunk-7A2SG466.mjs.map
|
|
325
|
+
//# sourceMappingURL=chunk-7A2SG466.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/llmClient.ts"],"names":["transport"],"mappings":";;;AA4CO,SAAS,oBAAoB,OAAA,EAAyC;AAC3E,EAAA,MAAM,YAAsB,EAA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AAC5C,QAAA,IAAI,OAAO,GAAA,EAAK;AAAE,UAAA,QAAA,GAAW,CAAC,QAAA;AAAU,UAAA;AAAA,QAAU;AAClD,QAAA,IAAI,QAAA,EAAU;AACd,QAAA,IAAI,OAAO,GAAA,EAAK,KAAA,EAAA;AAChB,QAAA,IAAI,OAAO,GAAA,EAAK;AACd,UAAA,KAAA,EAAA;AACA,UAAA,IAAI,UAAU,CAAA,EAAG;AACf,YAAA,IAAI;AACF,cAAA,OAAO,KAAK,KAAA,CAAM,OAAA,CAAQ,MAAM,KAAA,EAAO,CAAA,GAAI,CAAC,CAAC,CAAA;AAAA,YAC/C,CAAA,CAAA,MAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,IAAA,MAAM,IAAI,eAAe,CAAA,wCAAA,EAA2C,OAAA,CAAQ,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,EAC7F;AACF;AAKA,eAAsB,WAAA,CACpB,MAAA,EACA,YAAA,EACA,UAAA,EACA,OAAA,EACkC;AAClC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,IAAA;AAAA,IAC1B;AAAA,MACE,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,MACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,KACtC;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,gBAAA,CAAiB,OAAO,OAAO,CAAA;AACxC","file":"chunk-7A2SG466.mjs","sourcesContent":["/**\n * LLM client wrapper — provides a unified interface for LLM calls\n * used by the graph generation pipeline.\n *\n * Supports OpenAI-compatible APIs via environment variables:\n * LLM_API_KEY, LLM_BASE_URL, LLM_MODEL (or LLM_TIER_FAST / LLM_TIER_STRONG)\n */\n\nimport { transportResultFrom, type LlmTransportResult } from './llmTransportResult';\nexport { transportResultFrom, type LlmTransportResult } from './llmTransportResult';\n\nexport interface LlmClientConfig {\n apiKey?: string;\n baseUrl?: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n /**\n * Minimum ms between requests, enforced process-wide so free tiers are not\n * rate-limited by a burst. Defaults to LLM_MIN_REQUEST_INTERVAL_MS (2500).\n * Set 0 to disable — correct when several pipelines run concurrently in one\n * process and per-pipeline pacing is enough, or when the caller owns the\n * rate limit itself (serverless).\n */\n minRequestIntervalMs?: number;\n}\n\n/** One provider attempt. Kept per client instance so provenance never leaks across requests. */\nexport interface LlmCallRecord {\n provider: string;\n model: string;\n ok: boolean;\n error?: string;\n}\n\nexport interface LlmProvenance {\n providers: string[];\n models: string[];\n calls: number;\n failed_calls: number;\n /** true when at least one provider fell through to the next in the chain. */\n degraded: boolean;\n}\n\nexport function summarizeProvenance(callLog: LlmCallRecord[]): LlmProvenance {\n const providers: string[] = [];\n const models: string[] = [];\n let failed = 0;\n for (const r of callLog) {\n if (!providers.includes(r.provider)) providers.push(r.provider);\n if (!models.includes(r.model)) models.push(r.model);\n if (!r.ok) failed++;\n }\n return { providers, models, calls: callLog.length, failed_calls: failed, degraded: failed > 0 };\n}\n\n/**\n * Some OpenAI-compatible gateways (observed: 9router / ai-router.orchable.app)\n * paste SSE stream framing onto NON-stream responses: a leading blank line,\n * then the chat.completion JSON object, wrapped with a trailing `data: [DONE]`.\n * response.json() throws \"Unexpected non-whitespace character after JSON\", so\n * read the text and cut the body back to the first balanced JSON object.\n */\nexport async function responseJsonCompat(response: Response): Promise<Record<string, any>> {\n const text = await response.text();\n try {\n return JSON.parse(text);\n } catch {\n const start = text.indexOf('{');\n if (start < 0) {\n throw new LlmClientError(`LLM API returned a non-JSON body: ${text.slice(0, 200)}`);\n }\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\') { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n return JSON.parse(text.slice(start, i + 1));\n }\n }\n }\n throw new LlmClientError(`LLM API returned an unterminated JSON body: ${text.slice(0, 200)}`);\n }\n}\n\n/** One callable provider endpoint in the fallback chain. */\nexport interface ProviderSpec {\n label: string;\n baseUrl: string;\n apiKey: string;\n model: string;\n}\n\nexport interface LlmClient {\n chat(messages: LlmChatMessage[], options?: { temperature?: number; maxTokens?: number }): Promise<LlmChatResult>;\n model: string;\n /** Every provider attempt made through this client — the provenance of the graph it produced. */\n callLog: LlmCallRecord[];\n}\n\nexport interface LlmChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface LlmChatResult {\n content: string;\n model: string;\n /** Provider label that ultimately served the request. */\n provider?: string;\n /** What happened per provider when fallback occurred (empty when first try succeeded). */\n attempts?: string[];\n /** 'stop' when complete; 'length' means the response was TRUNCATED by max_tokens. */\n finishReason?: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n finishReason?: string;\n };\n _transport?: LlmTransportResult;\n}\n\nexport class LlmClientError extends Error {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly cause?: Error,\n ) {\n super(message);\n this.name = 'LlmClientError';\n }\n}\n\n/**\n * Create an LLM client from environment variables.\n */\nexport function build9routerProvider(model?: string): ProviderSpec | null {\n const apiKey = process.env.NINEROUTER_API_KEY;\n if (!apiKey) return null;\n const baseUrl = (process.env.NINEROUTER_BASE_URL || 'https://ai-router.orchable.app/v1').replace(/^[\"']|[\"']$/g, '').trim();\n const label = '9router';\n const modelName = (model || process.env.NINEROUTER_MODEL || 'laguna-s-2.1').trim();\n return { label, baseUrl, apiKey, model: modelName };\n}\n\n/**\n * Synthesize a 9router-only chain from the configured primary model.\n * POLICY (user directive 2026-10-07): 9router free-tier ONLY — laguna-s-2.1\n * and nemotron-ultra ride the same pool from different upstream providers.\n * The returned chain is PRIMARY then SAME-POOL SECONDARY; the caller owns any\n * fallback semantics and MUST NOT silently branch to another gateway.\n */\nexport function resolve9routerChain(configModel?: string): ProviderSpec[] {\n const primary = build9routerProvider(configModel);\n if (!primary) return [];\n const alt = process.env.NINEROUTER_MODEL_ALT && process.env.NINEROUTER_MODEL_ALT.trim();\n if (!alt) return [primary];\n const secondary = build9routerProvider(alt);\n if (!secondary) return [primary];\n return primary.model === secondary.model ? [primary] : [primary, secondary];\n}\n\n// Free-tier rate limits (NVIDIA NIM, OpenRouter) trip when a pipeline fires\n// many requests in a burst. Global pacing keeps us under the limit; a single\n// isolated call still goes through immediately.\nconst MIN_REQUEST_INTERVAL_MS = 2_500;\nlet requestIntervalMs = Number(process.env.LLM_MIN_REQUEST_INTERVAL_MS || MIN_REQUEST_INTERVAL_MS);\nlet lastRequestAt = 0;\n\nasync function pacedDelay(): Promise<void> {\n const wait = lastRequestAt + requestIntervalMs - Date.now();\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n lastRequestAt = Date.now();\n}\n\nexport function createLlmClient(config?: LlmClientConfig): LlmClient {\n const chain = resolve9routerChain(config?.model);\n const primary = chain[0];\n if (!primary) {\n throw new LlmClientError(\n 'No 9router provider configured. Set NINEROUTER_API_KEY and NINEROUTER_MODEL (or the NINEROUTER_* env defaults expected by the kit).',\n );\n }\n const apiKey = primary.apiKey;\n const baseUrl = primary.baseUrl;\n const model = primary.model;\n if (config?.minRequestIntervalMs !== undefined) {\n requestIntervalMs = Math.max(0, config.minRequestIntervalMs);\n }\n // Per-client, so concurrent pipelines never inherit each other's provenance.\n const callLog: LlmCallRecord[] = [];\n\n async function chat(\n messages: LlmChatMessage[],\n options?: { temperature?: number; maxTokens?: number },\n ): Promise<LlmChatResult> {\n const temperature = options?.temperature ?? config?.temperature ?? 0.1;\n const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || '65536', 10);\n\n const attempts: string[] = [];\n let lastError: LlmClientError | null = null;\n const TRANSIENT = new Set([408, 429, 500, 502, 503, 504]);\n // Hard per-request cap so a hanging provider degrades to a transient error\n // and the chain falls through instead of blocking the pipeline forever.\n // Reasoning presets (e.g. deepseek-v4-flash) can legitimately think for\n // minutes on large structured outputs — 5 minutes default, env-overridable.\n const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 300_000);\n const MAX_CHAIN_ROUNDS = 3;\n for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {\n if (round > 1) {\n // Whole chain failed transiently (rate limits / upstream 5xx) — back\n // off and rewalk the chain from the primary instead of dying.\n attempts.push('round ' + (round - 1) + ' failed — backing off 20s before rewalking the chain');\n await new Promise((resolve) => setTimeout(resolve, 20_000));\n }\n for (const provider of chain) {\n // Provenance: opened as failed, flipped to ok on the paths that return.\n const recIdx = callLog.push({ provider: provider.label, model: provider.model, ok: false }) - 1;\n try {\n const headers = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n };\n const payload = {\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n };\n await pacedDelay();\n const doFetch = (): Promise<Response> => fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n // Transient network failures (DNS blip, TLS reset, \"fetch failed\") get\n // one same-provider retry before falling through the chain.\n let response: Response;\n try {\n response = await doFetch();\n } catch (netErr) {\n attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) — retrying once`);\n await new Promise((r) => setTimeout(r, 5_000));\n lastRequestAt = Date.now();\n response = await doFetch();\n }\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const err = new LlmClientError(\n `[${provider.label}] LLM API error: ${response.status} ${response.statusText} — ${body.slice(0, 200)}`,\n response.status,\n );\n if (response.status === 429) {\n // Rate-limited: honor Retry-After (bounded) and retry once on the\n // same provider before falling through to the next one.\n const retryAfterRaw = response.headers.get('retry-after');\n const retryAfterMs = Math.min(\n 60_000,\n Math.max(15_000, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1_000),\n );\n attempts.push(`${provider.label}: 429 rate-limited — backing off ${Math.round(retryAfterMs / 1000)}s`);\n await new Promise((resolve) => setTimeout(resolve, retryAfterMs));\n lastRequestAt = Date.now();\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n if (!retry.ok) throw err;\n const retryData = await responseJsonCompat(retry) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent2 = retryData.choices?.[0]?.message?.content || '';\n if (!retryContent2.trim()) throw err;\n callLog[recIdx] = { ...callLog[recIdx], ok: true };\n const transport = transportResultFrom(provider.label, retryData.model || provider.model, {\n usage: retryData.usage,\n framingStripped: true,\n });\n return {\n content: retryContent2,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n }\n if (TRANSIENT.has(response.status)) {\n await new Promise((r) => setTimeout(r, 3000));\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n });\n if (!retry.ok) throw err; // still transient-failing — fall through to next provider\n const retryData = await responseJsonCompat(retry) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent = retryData.choices?.[0]?.message?.content || '';\n callLog[recIdx] = { ...callLog[recIdx], ok: true };\n const transport = transportResultFrom(provider.label, retryData.model || provider.model, {\n usage: retryData.usage,\n framingStripped: true,\n });\n return {\n content: retryContent,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n }\n throw err;\n }\n const data = await responseJsonCompat(response) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const wrappedError = (data as { error?: { message?: string; code?: number } }).error;\n if (wrappedError) {\n // OpenRouter proxies some upstream failures as HTTP 200 with an\n // {\"error\": {...}} body — treat as transient and fall through.\n throw new LlmClientError('[' + provider.label + '] upstream error ' + (wrappedError.code ?? '') + ': ' + (wrappedError.message ?? 'unknown'));\n }\n const content = data.choices?.[0]?.message?.content || '';\n if (!content.trim()) {\n // Empty completion (provider outage / content filter) is transient —\n // fall through to the next provider instead of returning unusable ''.\n throw new LlmClientError('[' + provider.label + '] empty completion returned');\n }\n const transport = transportResultFrom(provider.label, data.model || provider.model, {\n usage: data.usage,\n framingStripped: true,\n });\n return {\n content,\n model: data.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: data.usage,\n finishReason: data.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n callLog[recIdx] = { ...callLog[recIdx], ok: false, error: msg.slice(0, 200) };\n attempts.push(`${provider.label}: ${msg}`);\n lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);\n // try next provider\n }\n }\n if (round < MAX_CHAIN_ROUNDS) continue; // rewalk the chain\n throw lastError ?? new LlmClientError('All LLM providers failed (empty chain).');\n }\n throw lastError ?? new LlmClientError('All LLM providers failed after ' + MAX_CHAIN_ROUNDS + ' rounds.');\n }\n\n return { chat, model, callLog };\n}\n\n/**\n * Parse JSON from LLM response, handling markdown code fences.\n */\nexport function parseJsonFromLlm(text: string): Record<string, unknown> {\n // Strip markdown code fences if present\n let cleaned = text.trim();\n if (cleaned.startsWith('```json')) {\n cleaned = cleaned.slice(7);\n } else if (cleaned.startsWith('```')) {\n cleaned = cleaned.slice(3);\n }\n if (cleaned.endsWith('```')) {\n cleaned = cleaned.slice(0, -3);\n }\n cleaned = cleaned.trim();\n\n try {\n return JSON.parse(cleaned) as Record<string, unknown>;\n } catch {\n // Try to find first complete JSON object using brace-depth tracking\n const start = cleaned.indexOf('{');\n if (start >= 0) {\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = start; i < cleaned.length; i++) {\n const ch = cleaned[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\') { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n try {\n return JSON.parse(cleaned.slice(start, i + 1)) as Record<string, unknown>;\n } catch {\n // keep looking\n }\n }\n }\n }\n }\n throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);\n }\n}\n\n/**\n * Call LLM and parse JSON response.\n */\nexport async function llmChatJson(\n client: ReturnType<typeof createLlmClient>,\n systemPrompt: string,\n userPrompt: string,\n options?: { temperature?: number; maxTokens?: number },\n): Promise<Record<string, unknown>> {\n const result = await client.chat(\n [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ],\n options,\n );\n\n return parseJsonFromLlm(result.content);\n}\n"]}
|
|
@@ -310,5 +310,5 @@ function mergeCppResults(results) {
|
|
|
310
310
|
}
|
|
311
311
|
|
|
312
312
|
export { mergeCppResults, mergePythonResults, mergeSwiftResults, mergeTsResults, parseCppFile, parsePythonFile, parseSwiftFile, parseTsFile };
|
|
313
|
-
//# sourceMappingURL=chunk-
|
|
314
|
-
//# sourceMappingURL=chunk-
|
|
313
|
+
//# sourceMappingURL=chunk-DSEJLTUO.mjs.map
|
|
314
|
+
//# sourceMappingURL=chunk-DSEJLTUO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/parsers/swift.ts","../src/parsers/typescript.ts","../src/parsers/python.ts","../src/parsers/cpp.ts"],"names":["IMPORT_RE","TYPE_RE","FUNC_RE"],"mappings":";AA0BA,IAAM,SAAA,GAAY,mBAAA;AAClB,IAAM,OAAA,GAAU,4DAAA;AAChB,IAAM,OAAA,GAAU,mDAAA;AAChB,IAAM,UAAA,GAAa,sIAAA;AACnB,IAAM,kBAAA,GAAqB,oJAAA;AAEpB,SAAS,cAAA,CAAe,UAAkB,OAAA,EAAmC;AAClF,EAAA,MAAM,MAAA,GAA2B;AAAA,IAC/B,SAAS,EAAC;AAAA,IACV,OAAO,EAAC;AAAA,IACR,WAAW,EAAC;AAAA,IACZ,mBAAmB,EAAC;AAAA,IACpB,gBAAgB,EAAC;AAAA,IACjB,iBAAiB;AAAC,GACpB;AAGA,EAAA,IAAI,KAAA;AACJ,EAAA,OAAA,CAAQ,KAAA,GAAQ,SAAA,CAAU,IAAA,CAAK,OAAO,OAAO,IAAA,EAAM;AACjD,IAAA,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EAC9B;AAGA,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAC/B,EAAA,OAAA,CAAQ,KAAA,GAAQ,kBAAA,CAAmB,IAAA,CAAK,OAAO,OAAO,IAAA,EAAM;AAC1D,IAAA,IAAI,CAAC,MAAA,CAAO,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG;AACzB,MAAA,MAAA,CAAO,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA;AACnB,MAAA,MAAA,CAAO,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,IAC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OAAA,EAAS,CAAA,CAC/C,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,CAAC,CAAA,GAAI,CAAA,CAAE,CAAC,CAAC,CAAA,CAC1B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,GAAA,CAAI,CAAC,CAAC,GAAG,CAAA,KAAM,GAAG,CAAA;AAGrB,EAAA,MAAA,CAAO,iBAAiB,CAAC,GAAG,IAAI,GAAA,CAAI,MAAA,CAAO,cAAc,CAAC,CAAA;AAE1D,EAAA,OAAO,MAAA;AACT","file":"chunk-DSEJLTUO.mjs","sourcesContent":["/**\n * Swift regex-based parser (heuristic) — extracts imports, types, functions, property wrappers,\n * error handling patterns, and framework usage from Swift source files.\n *\n * Ported from knowledge-tree/extract_project_keywords.py parse_swift_file()\n */\n\nexport interface SwiftParseResult {\n imports: string[];\n types: Array<{\n kind: string;\n name: string;\n conforms_to: string[];\n file: string;\n }>;\n functions: Array<{\n name: string;\n params: string;\n returns: string;\n file: string;\n }>;\n property_wrappers: string[];\n error_handling: string[];\n frameworks_used: string[];\n}\n\nconst IMPORT_RE = /^import\\s+(\\w+)/gm;\nconst TYPE_RE = /\\b(class|struct|enum|protocol)\\s+(\\w+)(?:\\s*:\\s*([^{]+))?/g;\nconst FUNC_RE = /\\bfunc\\s+(\\w+)\\s*\\(([^)]*)\\)(?:\\s*->\\s*([^{]+))?/g;\nconst WRAPPER_RE = /@(State|Binding|ObservedObject|StateObject|Published|Environment|EnvironmentObject|AppStorage|SceneStorage|FocusState|Observable)\\b/g;\nconst FRAMEWORK_USAGE_RE = /\\b(URLSession|URLRequest|JSONSerialization|JSONDecoder|JSONEncoder|Task|DispatchQueue|Timer|NotificationCenter|UserDefaults|FileManager|Bundle)\\b/g;\n\nexport function parseSwiftFile(filepath: string, content: string): SwiftParseResult {\n const result: SwiftParseResult = {\n imports: [],\n types: [],\n functions: [],\n property_wrappers: [],\n error_handling: [],\n frameworks_used: [],\n };\n\n // Extract imports\n let match: RegExpExecArray | null;\n while ((match = IMPORT_RE.exec(content)) !== null) {\n result.imports.push(match[1]);\n }\n\n // Extract framework usage (types used in body, not declarations)\n const fwSeen = new Set<string>();\n while ((match = FRAMEWORK_USAGE_RE.exec(content)) !== null) {\n if (!fwSeen.has(match[1])) {\n fwSeen.add(match[1]);\n result.frameworks_used.push(match[1]);\n }\n }\n\n // Extract type declarations\n while ((match = TYPE_RE.exec(content)) !== null) {\n const conforms = (match[3] || '')\n .split(',')\n .map(p => p.trim())\n .filter(Boolean);\n result.types.push({\n kind: match[1],\n name: match[2],\n conforms_to: conforms,\n file: filepath,\n });\n }\n\n // Extract function signatures\n while ((match = FUNC_RE.exec(content)) !== null) {\n const name = match[1];\n if (name.startsWith('_')) continue;\n result.functions.push({\n name,\n params: (match[2] || '').trim(),\n returns: (match[3] || '').trim(),\n file: filepath,\n });\n }\n\n // Extract property wrappers\n const wrapperSet = new Set<string>();\n while ((match = WRAPPER_RE.exec(content)) !== null) {\n wrapperSet.add(match[1]);\n }\n result.property_wrappers = Array.from(wrapperSet);\n\n // Extract error handling patterns\n if (content.includes('do {') || content.includes('do{')) {\n result.error_handling.push('do-catch');\n }\n if (content.includes('throws')) {\n result.error_handling.push('throws');\n }\n if (content.includes('Result<')) {\n result.error_handling.push('Result type');\n }\n if (content.includes('try?')) {\n result.error_handling.push('try?');\n }\n if (content.includes('try!')) {\n result.error_handling.push('try!');\n }\n\n return result;\n}\n\nexport function mergeSwiftResults(results: SwiftParseResult[]): SwiftParseResult {\n const merged: SwiftParseResult = {\n imports: [],\n types: [],\n functions: [],\n property_wrappers: [],\n error_handling: [],\n frameworks_used: [],\n };\n\n const importCounts = new Map<string, number>();\n const wrapperCounts = new Map<string, number>();\n const errorCounts = new Map<string, number>();\n const frameworkSet = new Set<string>();\n\n for (const r of results) {\n for (const imp of r.imports) {\n importCounts.set(imp, (importCounts.get(imp) || 0) + 1);\n }\n merged.types.push(...r.types);\n merged.functions.push(...r.functions);\n for (const w of r.property_wrappers) {\n wrapperCounts.set(w, (wrapperCounts.get(w) || 0) + 1);\n }\n for (const e of r.error_handling) {\n errorCounts.set(e, (errorCounts.get(e) || 0) + 1);\n }\n for (const fw of r.frameworks_used) {\n frameworkSet.add(fw);\n }\n }\n\n // Sort imports by count descending, top 20\n merged.imports = Array.from(importCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([mod, count]) => mod);\n\n // Sort wrappers by count, top 10\n merged.property_wrappers = Array.from(wrapperCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([w]) => w);\n\n // Sort errors by count, top 10\n merged.error_handling = Array.from(errorCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([p]) => p);\n\n merged.frameworks_used = Array.from(frameworkSet).sort();\n\n // Limit types and functions\n merged.types = merged.types.slice(0, 100);\n merged.functions = merged.functions.slice(0, 100);\n\n return merged;\n}\n","/**\n * TypeScript/JavaScript regex-based parser (heuristic) — extracts imports, types, functions,\n * and error handling patterns.\n *\n * Ported from knowledge-tree/extract_project_keywords.py parse_ts_file()\n */\n\nexport interface TsParseResult {\n imports: string[];\n types: Array<{\n kind: string;\n name: string;\n file: string;\n }>;\n functions: Array<{\n name: string;\n params: string;\n file: string;\n }>;\n error_handling: string[];\n}\n\nconst IMPORT_RE = /import\\s+.*?from\\s+['\"]([^'\"]+)['\"]/g;\nconst TYPE_RE = /\\b(interface|type|class|enum)\\s+(\\w+)/g;\nconst FUNC_RE = /\\bfunction\\s+(\\w+)\\s*\\(([^)]*)\\)/g;\nconst ARROW_RE = /\\bconst\\s+(\\w+)\\s*=\\s*\\([^)]*\\)\\s*(?::\\s*\\w+)?\\s*=>/g;\n\nexport function parseTsFile(filepath: string, content: string): TsParseResult {\n const result: TsParseResult = {\n imports: [],\n types: [],\n functions: [],\n error_handling: [],\n };\n\n let match: RegExpExecArray | null;\n\n // Extract imports\n while ((match = IMPORT_RE.exec(content)) !== null) {\n result.imports.push(match[1]);\n }\n\n // Extract type/interface/class/enum declarations\n while ((match = TYPE_RE.exec(content)) !== null) {\n result.types.push({\n kind: match[1],\n name: match[2],\n file: filepath,\n });\n }\n\n // Extract function declarations\n while ((match = FUNC_RE.exec(content)) !== null) {\n result.functions.push({\n name: match[1],\n params: (match[2] || '').trim(),\n file: filepath,\n });\n }\n\n // Extract arrow functions\n while ((match = ARROW_RE.exec(content)) !== null) {\n result.functions.push({\n name: match[1],\n params: '',\n file: filepath,\n });\n }\n\n // Extract error handling patterns\n if (content.includes('try {') || content.includes('try{')) {\n result.error_handling.push('try-catch');\n }\n if (content.includes('Promise')) {\n result.error_handling.push('Promise');\n }\n if (content.includes('.catch(')) {\n result.error_handling.push('.catch()');\n }\n\n return result;\n}\n\nexport function mergeTsResults(results: TsParseResult[]): TsParseResult {\n const merged: TsParseResult = {\n imports: [],\n types: [],\n functions: [],\n error_handling: [],\n };\n\n const importCounts = new Map<string, number>();\n const errorCounts = new Map<string, number>();\n\n for (const r of results) {\n for (const imp of r.imports) {\n importCounts.set(imp, (importCounts.get(imp) || 0) + 1);\n }\n merged.types.push(...r.types);\n merged.functions.push(...r.functions);\n for (const e of r.error_handling) {\n errorCounts.set(e, (errorCounts.get(e) || 0) + 1);\n }\n }\n\n merged.imports = Array.from(importCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([mod]) => mod);\n\n merged.error_handling = Array.from(errorCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([p]) => p);\n\n merged.types = merged.types.slice(0, 100);\n merged.functions = merged.functions.slice(0, 100);\n\n return merged;\n}\n","/**\n * Python regex-based parser (heuristic) — extracts imports, classes, functions, docstrings,\n * and error handling patterns.\n *\n * Ported from knowledge-tree/extract_project_keywords.py parse_python_file()\n */\n\nexport interface PythonParseResult {\n imports: string[];\n types: Array<{\n kind: string;\n name: string;\n bases: string[];\n file: string;\n }>;\n functions: Array<{\n name: string;\n params: string;\n file: string;\n }>;\n docstrings: string[];\n error_handling: string[];\n}\n\nconst IMPORT_RE = /^(?:import|from)\\s+(\\w+)/gm;\nconst CLASS_RE = /\\bclass\\s+(\\w+)(?:\\s*\\(([^)]+)\\))?/g;\nconst FUNC_RE = /\\bdef\\s+(\\w+)\\s*\\(([^)]*)\\)/g;\nconst DOCSTRING_RE = /\"\"\"([^\"]{20,300})\"\"\"/g;\n\nexport function parsePythonFile(filepath: string, content: string): PythonParseResult {\n const result: PythonParseResult = {\n imports: [],\n types: [],\n functions: [],\n docstrings: [],\n error_handling: [],\n };\n\n let match: RegExpExecArray | null;\n\n // Extract imports\n while ((match = IMPORT_RE.exec(content)) !== null) {\n result.imports.push(match[1]);\n }\n\n // Extract docstrings (module, class, function level) — high-signal domain intent\n while ((match = DOCSTRING_RE.exec(content)) !== null) {\n const firstSentence = match[1].trim().split('\\n')[0].slice(0, 120);\n if (firstSentence.length > 15) {\n result.docstrings.push(firstSentence);\n }\n }\n\n // Extract class declarations\n while ((match = CLASS_RE.exec(content)) !== null) {\n const bases = (match[2] || '')\n .split(',')\n .map(b => b.trim())\n .filter(Boolean);\n result.types.push({\n kind: 'class',\n name: match[1],\n bases,\n file: filepath,\n });\n }\n\n // Extract function declarations\n while ((match = FUNC_RE.exec(content)) !== null) {\n const name = match[1];\n // Skip dunder methods (__init__, __str__)\n if (name.startsWith('__') && name.endsWith('__')) continue;\n result.functions.push({\n name,\n params: (match[2] || '').trim(),\n file: filepath,\n });\n }\n\n // Extract error handling patterns\n if (content.includes('try:')) {\n result.error_handling.push('try-except');\n }\n if (content.includes('raise')) {\n result.error_handling.push('raise');\n }\n\n return result;\n}\n\nexport function mergePythonResults(results: PythonParseResult[]): PythonParseResult {\n const merged: PythonParseResult = {\n imports: [],\n types: [],\n functions: [],\n docstrings: [],\n error_handling: [],\n };\n\n const importCounts = new Map<string, number>();\n const errorCounts = new Map<string, number>();\n\n for (const r of results) {\n for (const imp of r.imports) {\n importCounts.set(imp, (importCounts.get(imp) || 0) + 1);\n }\n merged.types.push(...r.types);\n merged.functions.push(...r.functions);\n merged.docstrings.push(...r.docstrings);\n for (const e of r.error_handling) {\n errorCounts.set(e, (errorCounts.get(e) || 0) + 1);\n }\n }\n\n merged.imports = Array.from(importCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([mod]) => mod);\n\n merged.error_handling = Array.from(errorCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([p]) => p);\n\n merged.types = merged.types.slice(0, 100);\n merged.functions = merged.functions.slice(0, 100);\n merged.docstrings = merged.docstrings.slice(0, 20);\n\n return merged;\n}\n","/**\n * C++/Arduino regex-based parser (heuristic) — extracts #include, types, functions,\n * and error handling patterns.\n *\n * Ported from knowledge-tree/extract_project_keywords.py parse_cpp_file()\n */\n\nexport interface CppParseResult {\n imports: string[];\n types: Array<{\n kind: string;\n name: string;\n file: string;\n }>;\n functions: Array<{\n name: string;\n file: string;\n }>;\n error_handling: string[];\n}\n\nconst INCLUDE_RE = /#include\\s*[<\"]([^>\"]+)[>\"]/g;\nconst TYPE_RE = /\\b(?:class|struct|enum)\\s+(\\w+)/g;\nconst FUNC_RE = /\\b(?:void|int|float|double|char|bool|String|uint8_t|uint16_t|uint32_t)\\s+(\\w+)\\s*\\(/g;\n\nexport function parseCppFile(filepath: string, content: string): CppParseResult {\n const result: CppParseResult = {\n imports: [],\n types: [],\n functions: [],\n error_handling: [],\n };\n\n let match: RegExpExecArray | null;\n\n // Extract #include\n while ((match = INCLUDE_RE.exec(content)) !== null) {\n result.imports.push(match[1]);\n }\n\n // Extract type declarations\n while ((match = TYPE_RE.exec(content)) !== null) {\n result.types.push({\n kind: 'cpp',\n name: match[1],\n file: filepath,\n });\n }\n\n // Extract function declarations\n while ((match = FUNC_RE.exec(content)) !== null) {\n result.functions.push({\n name: match[1],\n file: filepath,\n });\n }\n\n // Extract error handling patterns\n if (/\\btry\\b|\\bthrow\\b|\\bcatch\\b/.test(content)) {\n result.error_handling.push('try/throw/catch');\n }\n\n return result;\n}\n\nexport function mergeCppResults(results: CppParseResult[]): CppParseResult {\n const merged: CppParseResult = {\n imports: [],\n types: [],\n functions: [],\n error_handling: [],\n };\n\n const importCounts = new Map<string, number>();\n\n for (const r of results) {\n for (const imp of r.imports) {\n importCounts.set(imp, (importCounts.get(imp) || 0) + 1);\n }\n merged.types.push(...r.types);\n merged.functions.push(...r.functions);\n merged.error_handling.push(...r.error_handling);\n }\n\n merged.imports = Array.from(importCounts.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([mod]) => mod);\n\n // Deduplicate error handling\n merged.error_handling = [...new Set(merged.error_handling)];\n\n return merged;\n}\n"]}
|