gitnexus 1.6.6 → 1.6.7-rc.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/dist/_shared/graph/types.d.ts +18 -2
- package/dist/_shared/graph/types.d.ts.map +1 -1
- package/dist/_shared/lbug/schema-constants.d.ts +2 -2
- package/dist/_shared/lbug/schema-constants.d.ts.map +1 -1
- package/dist/_shared/lbug/schema-constants.js +10 -0
- package/dist/_shared/lbug/schema-constants.js.map +1 -1
- package/dist/core/ingestion/model/registration-table.js +3 -0
- package/dist/core/ingestion/pipeline-phases/index.d.ts +1 -0
- package/dist/core/ingestion/pipeline-phases/index.js +1 -0
- package/dist/core/ingestion/pipeline-phases/registry.d.ts +56 -0
- package/dist/core/ingestion/pipeline-phases/registry.js +48 -0
- package/dist/core/ingestion/pipeline.d.ts +21 -0
- package/dist/core/ingestion/pipeline.js +28 -20
- package/dist/core/ingestion/taint/source-sink-config.d.ts +36 -0
- package/dist/core/ingestion/taint/source-sink-config.js +16 -0
- package/dist/core/ingestion/taint/source-sink-registry.d.ts +27 -0
- package/dist/core/ingestion/taint/source-sink-registry.js +35 -0
- package/dist/core/lbug/csv-generator.js +14 -0
- package/dist/core/lbug/lbug-adapter.js +12 -0
- package/dist/core/lbug/schema.d.ts +2 -1
- package/dist/core/lbug/schema.js +22 -0
- package/dist/server/api.d.ts +1 -0
- package/dist/server/api.js +17 -2
- package/package.json +1 -1
- package/scripts/spikes/s1-reaching-def-index-bench.ts +151 -0
- package/scripts/spikes/s2-postdom-prototype.ts +162 -0
- package/web/assets/{agent-EkX7webX.js → agent-CKPMqImC.js} +1 -1
- package/web/assets/{architectureDiagram-UL44E2DR-BoczH8cv.js → architectureDiagram-UL44E2DR-D1EXI0zA.js} +1 -1
- package/web/assets/{chunk-LCXTWHL2-By5HB3b-.js → chunk-LCXTWHL2-Dfmux4m1.js} +1 -1
- package/web/assets/{chunk-RG4AUYOV-BQE_DkpL.js → chunk-RG4AUYOV-CAkzcoRj.js} +1 -1
- package/web/assets/{classDiagram-KGZ6W3CR-Dj_02GUH.js → classDiagram-KGZ6W3CR-Bv93af_b.js} +1 -1
- package/web/assets/{classDiagram-v2-72OJOZXJ-D-NArMpf.js → classDiagram-v2-72OJOZXJ-CLfEqHUa.js} +1 -1
- package/web/assets/{diagram-3NCE3AQN-VXtXDO95.js → diagram-3NCE3AQN-BqAtKUpW.js} +1 -1
- package/web/assets/{diagram-GF46GFSD-B1qab2Ah.js → diagram-GF46GFSD-CaBG6n6o.js} +1 -1
- package/web/assets/{diagram-QXG6HAR7-BSCHGzzT.js → diagram-QXG6HAR7-CZ-O3rcV.js} +1 -1
- package/web/assets/{diagram-WEQXMOUZ-DHtknmNT.js → diagram-WEQXMOUZ-P4lSL4GH.js} +1 -1
- package/web/assets/{erDiagram-L5TCEMPS-Db-IYTmm.js → erDiagram-L5TCEMPS-QN2eEP1e.js} +1 -1
- package/web/assets/{flowDiagram-H6V6AXG4-BHDoyVoW.js → flowDiagram-H6V6AXG4-CXbXImlN.js} +1 -1
- package/web/assets/{index-BR0IhgbR.js → index-CG6q8eTs.js} +6 -6
- package/web/assets/{infoDiagram-3YFTVSEB-6h8wbWEe.js → infoDiagram-3YFTVSEB-DmLICZx1.js} +1 -1
- package/web/assets/{ishikawaDiagram-BNXS4ZKH-Dx2OkPk1.js → ishikawaDiagram-BNXS4ZKH-6LKOvBfp.js} +1 -1
- package/web/assets/{kanban-definition-75IXJCU3-CIIEZfqV.js → kanban-definition-75IXJCU3-DgDi9oJT.js} +1 -1
- package/web/assets/{mindmap-definition-2TDM6QVE-DUAqydRq.js → mindmap-definition-2TDM6QVE-CwR5sBB-.js} +1 -1
- package/web/assets/{pieDiagram-CU6KROY3-BntYuYZa.js → pieDiagram-CU6KROY3-By8g6f6B.js} +1 -1
- package/web/assets/{requirementDiagram-JXO7QTGE-QCD6I29n.js → requirementDiagram-JXO7QTGE-7oDcJ1_J.js} +1 -1
- package/web/assets/{sequenceDiagram-VS2MUI6T-DScFwLz2.js → sequenceDiagram-VS2MUI6T-FySeKCUy.js} +1 -1
- package/web/assets/{stateDiagram-7D4R322I-AkRAm6Hl.js → stateDiagram-7D4R322I-CB2nABwH.js} +1 -1
- package/web/assets/{stateDiagram-v2-36443NZ5-BCK1vigR.js → stateDiagram-v2-36443NZ5-COBGd2RL.js} +1 -1
- package/web/assets/{timeline-definition-O6YCAMPW-BvpIVXjX.js → timeline-definition-O6YCAMPW-Ds2CnVZK.js} +1 -1
- package/web/assets/{vennDiagram-MWXL3ELB-BYGWk6dK.js → vennDiagram-MWXL3ELB-DUIEwXWp.js} +1 -1
- package/web/assets/{wardleyDiagram-CUQ6CDDI-Dk1z7H2T.js → wardleyDiagram-CUQ6CDDI-DEiFPQih.js} +1 -1
- package/web/assets/{xychartDiagram-N2JHSOCM-2N6NCSWN.js → xychartDiagram-N2JHSOCM-BUbayhST.js} +1 -1
- package/web/index.html +1 -1
package/dist/server/api.js
CHANGED
|
@@ -290,8 +290,16 @@ const buildGraph = async (includeContent = false) => {
|
|
|
290
290
|
const GRAPH_RELATIONSHIP_QUERY = `MATCH (a)-[r:CodeRelation]->(b) RETURN a.id AS sourceId, b.id AS targetId, ` +
|
|
291
291
|
`r.type AS type, r.confidence AS confidence, r.reason AS reason, r.step AS step`;
|
|
292
292
|
const quoteNodeTable = (table) => `\`${table.replace(/`/g, '``')}\``;
|
|
293
|
-
const getNodeQuery = (table, includeContent) => {
|
|
293
|
+
export const getNodeQuery = (table, includeContent) => {
|
|
294
294
|
const tableLabel = quoteNodeTable(table);
|
|
295
|
+
if (table === 'BasicBlock') {
|
|
296
|
+
// Taint/PDG substrate (issue #2080) — BasicBlock has no name/content
|
|
297
|
+
// columns. Project only its declared columns: a default `n.name`
|
|
298
|
+
// projection raises a Ladybug "Cannot find property name" binder error
|
|
299
|
+
// (not matched by isIgnorableGraphQueryError), which would 500 the graph
|
|
300
|
+
// endpoint the moment BasicBlock joins NODE_TABLES, even on an empty table.
|
|
301
|
+
return `MATCH (n:${tableLabel}) RETURN n.id AS id, n.filePath AS filePath, n.startLine AS startLine, n.endLine AS endLine, n.text AS text`;
|
|
302
|
+
}
|
|
295
303
|
if (table === 'File') {
|
|
296
304
|
return includeContent
|
|
297
305
|
? `MATCH (n:${tableLabel}) RETURN n.id AS id, n.name AS name, n.filePath AS filePath, n.content AS content`
|
|
@@ -320,10 +328,17 @@ const mapGraphNodeRow = (table, row, includeContent) => ({
|
|
|
320
328
|
id: row.id ?? row[0],
|
|
321
329
|
label: table,
|
|
322
330
|
properties: {
|
|
323
|
-
|
|
331
|
+
// `?? ''` keeps NodeProperties.name a `string` even for label rows that
|
|
332
|
+
// project no name/label column (BasicBlock — taint/PDG substrate #2080).
|
|
333
|
+
// Without it, BasicBlock rows carry name:undefined (masked by the cast
|
|
334
|
+
// below) and the web layer (Header search, circles/tree layout) derefs
|
|
335
|
+
// `.name` unguarded → TypeError once M1 emits blocks. `row.text` gives a
|
|
336
|
+
// BasicBlock a sensible fallback name before the empty-string floor.
|
|
337
|
+
name: row.name ?? row.label ?? row.text ?? row[1] ?? '',
|
|
324
338
|
filePath: row.filePath ?? row[2],
|
|
325
339
|
startLine: row.startLine,
|
|
326
340
|
endLine: row.endLine,
|
|
341
|
+
text: row.text,
|
|
327
342
|
content: includeContent ? row.content : undefined,
|
|
328
343
|
responseKeys: row.responseKeys,
|
|
329
344
|
errorKeys: row.errorKeys,
|
package/package.json
CHANGED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spike S1 (issue #2080, M0) — THROWAWAY benchmark. Not part of the build
|
|
3
|
+
* (scripts/ is excluded from tsconfig) or the test suite.
|
|
4
|
+
*
|
|
5
|
+
* Question: can LadybugDB serve the headline REACHING_DEF query
|
|
6
|
+
* [:REACHING_DEF*1..5 {variable}]
|
|
7
|
+
* fast enough, and what is the right storage shape for the `variable`?
|
|
8
|
+
*
|
|
9
|
+
* What it does:
|
|
10
|
+
* 1. Builds a synthetic ~100K-edge graph of BasicBlock nodes + REACHING_DEF
|
|
11
|
+
* edges (variable carried in the CodeRelation `reason` column) with a
|
|
12
|
+
* realistic per-variable fan-out distribution, and loads it through the
|
|
13
|
+
* real bulk-COPY path (loadGraphToLbug).
|
|
14
|
+
* 2. Probes whether LadybugDB supports a secondary index on a relationship
|
|
15
|
+
* property (the crux of the "edge property vs side table" decision).
|
|
16
|
+
* 3. Times the variable-filtered bounded var-length path query.
|
|
17
|
+
*
|
|
18
|
+
* Run: npx tsx scripts/spikes/s1-reaching-def-index-bench.ts [edgeCount]
|
|
19
|
+
*/
|
|
20
|
+
import fs from 'fs/promises';
|
|
21
|
+
import path from 'path';
|
|
22
|
+
import os from 'os';
|
|
23
|
+
import { performance } from 'node:perf_hooks';
|
|
24
|
+
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
|
|
25
|
+
import type { KnowledgeGraph } from '../../src/core/graph/types.js';
|
|
26
|
+
|
|
27
|
+
const EDGE_COUNT = Number(process.argv[2] ?? 30_000);
|
|
28
|
+
// Realistic-ish def-use shape: many short chains, variables reused across them.
|
|
29
|
+
const CHAIN_LEN = 6; // blocks per function-ish chain
|
|
30
|
+
const DISTINCT_VARS = Math.max(1, Math.floor(EDGE_COUNT / 20)); // ~20 edges/variable fan-out
|
|
31
|
+
|
|
32
|
+
const log = (m: string) => process.stdout.write(m + '\n');
|
|
33
|
+
|
|
34
|
+
function buildSynthGraph(edgeCount: number): KnowledgeGraph {
|
|
35
|
+
const g = createKnowledgeGraph();
|
|
36
|
+
let edges = 0;
|
|
37
|
+
let chain = 0;
|
|
38
|
+
while (edges < edgeCount) {
|
|
39
|
+
const base = `BasicBlock:synth/f${chain}.ts`;
|
|
40
|
+
for (let i = 0; i <= CHAIN_LEN; i++) {
|
|
41
|
+
g.addNode({
|
|
42
|
+
id: `${base}:${i}`,
|
|
43
|
+
label: 'BasicBlock',
|
|
44
|
+
properties: {
|
|
45
|
+
name: '',
|
|
46
|
+
filePath: `synth/f${chain}.ts`,
|
|
47
|
+
startLine: i,
|
|
48
|
+
endLine: i,
|
|
49
|
+
text: '',
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
for (let i = 0; i < CHAIN_LEN && edges < edgeCount; i++) {
|
|
54
|
+
const variable = `v${edges % DISTINCT_VARS}`;
|
|
55
|
+
g.addRelationship({
|
|
56
|
+
id: `${base}:${i}->${i + 1}:${variable}`,
|
|
57
|
+
sourceId: `${base}:${i}`,
|
|
58
|
+
targetId: `${base}:${i + 1}`,
|
|
59
|
+
type: 'REACHING_DEF',
|
|
60
|
+
confidence: 1.0,
|
|
61
|
+
reason: variable, // M0 storage: variable rides `reason`
|
|
62
|
+
});
|
|
63
|
+
edges++;
|
|
64
|
+
}
|
|
65
|
+
chain++;
|
|
66
|
+
}
|
|
67
|
+
return g;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function main() {
|
|
71
|
+
const tmp = path.join(os.tmpdir(), `s1-spike-${Date.now()}`);
|
|
72
|
+
const storagePath = path.join(tmp, '.gitnexus');
|
|
73
|
+
const dbPath = path.join(storagePath, 'lbug');
|
|
74
|
+
await fs.mkdir(dbPath, { recursive: true });
|
|
75
|
+
|
|
76
|
+
const adapter = await import('../../src/core/lbug/lbug-adapter.js');
|
|
77
|
+
await adapter.initLbug(dbPath);
|
|
78
|
+
|
|
79
|
+
log(
|
|
80
|
+
`[S1] building synthetic graph: ~${EDGE_COUNT} REACHING_DEF edges, ` +
|
|
81
|
+
`${DISTINCT_VARS} distinct variables (~20 edges/var fan-out), chains of ${CHAIN_LEN}`,
|
|
82
|
+
);
|
|
83
|
+
const g = buildSynthGraph(EDGE_COUNT);
|
|
84
|
+
|
|
85
|
+
let t = performance.now();
|
|
86
|
+
await adapter.loadGraphToLbug(g, tmp, storagePath);
|
|
87
|
+
const loadMs = performance.now() - t;
|
|
88
|
+
const stats = await adapter.getLbugStats();
|
|
89
|
+
log(`[S1] bulk-COPY load: ${loadMs.toFixed(0)}ms (nodes=${stats.nodes}, edges=${stats.edges})`);
|
|
90
|
+
|
|
91
|
+
// (2) Probe: does LadybugDB support a secondary index on a REL property?
|
|
92
|
+
let relIndexSupported = false;
|
|
93
|
+
let relIndexErr = '';
|
|
94
|
+
for (const stmt of [
|
|
95
|
+
"CALL CREATE_REL_INDEX('CodeRelation', 'cr_reason_idx', 'reason')",
|
|
96
|
+
'CREATE INDEX cr_reason_idx ON CodeRelation(reason)',
|
|
97
|
+
]) {
|
|
98
|
+
try {
|
|
99
|
+
await adapter.executeQuery(stmt);
|
|
100
|
+
relIndexSupported = true;
|
|
101
|
+
break;
|
|
102
|
+
} catch (e: any) {
|
|
103
|
+
relIndexErr = String(e?.message ?? e).split('\n')[0];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
log(
|
|
107
|
+
`[S1] rel-property secondary index supported? ${relIndexSupported} ` +
|
|
108
|
+
`(last error: ${relIndexErr})`,
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
// (3a) Single-hop variable filter — the common case M3 runs most.
|
|
112
|
+
const probeVar = 'v0';
|
|
113
|
+
t = performance.now();
|
|
114
|
+
const single = await adapter.executeQuery(
|
|
115
|
+
`MATCH (a:BasicBlock)-[r:CodeRelation {type: 'REACHING_DEF', reason: '${probeVar}'}]->(b:BasicBlock)
|
|
116
|
+
RETURN count(r) AS c`,
|
|
117
|
+
);
|
|
118
|
+
const singleMs = performance.now() - t;
|
|
119
|
+
log(`[S1] single-hop variable filter → ${single[0]?.c} edges in ${singleMs.toFixed(0)}ms`);
|
|
120
|
+
|
|
121
|
+
// (3b) SOURCE-ANCHORED bounded var-length path — the realistic taint query
|
|
122
|
+
// (anchor the source block, then walk REACHING_DEF up to 5 hops). The
|
|
123
|
+
// UNANCHORED global form ([:REACHING_DEF*1..5] from every block) is
|
|
124
|
+
// impractical at scale (path explosion) — that is itself an S1 finding:
|
|
125
|
+
// taint queries MUST be scoped to a source block, not run graph-wide.
|
|
126
|
+
const srcId = 'BasicBlock:synth/f0.ts:0';
|
|
127
|
+
t = performance.now();
|
|
128
|
+
const anchored = await adapter.executeQuery(
|
|
129
|
+
`MATCH p = (a:BasicBlock)-[:CodeRelation*1..5 {type: 'REACHING_DEF'}]->(b:BasicBlock)
|
|
130
|
+
WHERE a.id = '${srcId}' AND all(rel IN relationships(p) WHERE rel.reason = '${probeVar}')
|
|
131
|
+
RETURN count(p) AS paths`,
|
|
132
|
+
);
|
|
133
|
+
const pathMs = performance.now() - t;
|
|
134
|
+
log(
|
|
135
|
+
`[S1] source-anchored [:REACHING_DEF*1..5 {reason='${probeVar}'}] from one block → ` +
|
|
136
|
+
`${anchored[0]?.paths} paths in ${pathMs.toFixed(0)}ms`,
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
await adapter.closeLbug();
|
|
140
|
+
await fs.rm(tmp, { recursive: true, force: true });
|
|
141
|
+
|
|
142
|
+
log('\n[S1] VERDICT INPUTS:');
|
|
143
|
+
log(
|
|
144
|
+
` load_ms=${loadMs.toFixed(0)} single_hop_ms=${singleMs.toFixed(0)} anchored_path_ms=${pathMs.toFixed(0)} rel_index=${relIndexSupported}`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
main().catch((e) => {
|
|
149
|
+
console.error('[S1] FAILED:', e);
|
|
150
|
+
process.exit(1);
|
|
151
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spike S2 (issue #2080, M0) — THROWAWAY post-dominator feasibility prototype.
|
|
3
|
+
* Not part of the build (scripts/ excluded from tsconfig) or the test suite.
|
|
4
|
+
*
|
|
5
|
+
* Question (per maintainer review): does the post-dominator algorithm Epic B
|
|
6
|
+
* (#2085, CDG) depends on hold up on real TS/JS control-flow shapes — the
|
|
7
|
+
* classic CFG hazards — before Epic B commits to it?
|
|
8
|
+
*
|
|
9
|
+
* Scope boundary: post-dominators operate on a CFG, not on the AST directly.
|
|
10
|
+
* This prototype validates the ALGORITHM (iterative dataflow on the reverse
|
|
11
|
+
* CFG, EXIT-rooted, → immediate-post-dominator tree) against CFGs that model
|
|
12
|
+
* each hazard's real TS control flow (the TS source each CFG represents is
|
|
13
|
+
* shown inline). Building the CFG from a tree-sitter AST is M1's job (#2081);
|
|
14
|
+
* this spike deliberately does not reimplement it.
|
|
15
|
+
*
|
|
16
|
+
* Run: npx tsx scripts/spikes/s2-postdom-prototype.ts
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
type CFG = {
|
|
20
|
+
name: string;
|
|
21
|
+
tsSource: string;
|
|
22
|
+
entry: string;
|
|
23
|
+
exit: string;
|
|
24
|
+
// adjacency: block -> successors
|
|
25
|
+
succ: Record<string, string[]>;
|
|
26
|
+
hazard: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// Iterative post-dominator dataflow on the reverse CFG.
|
|
30
|
+
// PostDom(EXIT) = {EXIT}; PostDom(n) = {n} ∪ (⋂ PostDom(s) for s ∈ succ(n)).
|
|
31
|
+
// Monotone over a finite lattice (powerset of blocks) ⇒ guaranteed to converge.
|
|
32
|
+
function postDominators(cfg: CFG): { pdom: Record<string, Set<string>>; iterations: number } {
|
|
33
|
+
const blocks = Object.keys(cfg.succ);
|
|
34
|
+
const all = new Set(blocks);
|
|
35
|
+
const pdom: Record<string, Set<string>> = {};
|
|
36
|
+
for (const b of blocks) pdom[b] = b === cfg.exit ? new Set([cfg.exit]) : new Set(all);
|
|
37
|
+
|
|
38
|
+
let changed = true;
|
|
39
|
+
let iterations = 0;
|
|
40
|
+
while (changed) {
|
|
41
|
+
changed = false;
|
|
42
|
+
iterations++;
|
|
43
|
+
for (const b of blocks) {
|
|
44
|
+
if (b === cfg.exit) continue;
|
|
45
|
+
const succs = cfg.succ[b] ?? [];
|
|
46
|
+
let inter: Set<string> | null = null;
|
|
47
|
+
for (const s of succs) {
|
|
48
|
+
if (inter === null) inter = new Set(pdom[s]);
|
|
49
|
+
else inter = new Set([...inter].filter((x) => pdom[s].has(x)));
|
|
50
|
+
}
|
|
51
|
+
const next = new Set<string>(inter ?? []);
|
|
52
|
+
next.add(b);
|
|
53
|
+
if (next.size !== pdom[b].size || [...next].some((x) => !pdom[b].has(x))) {
|
|
54
|
+
pdom[b] = next;
|
|
55
|
+
changed = true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (iterations > blocks.length + 5)
|
|
59
|
+
throw new Error('post-dom did not converge (suspected bug)');
|
|
60
|
+
}
|
|
61
|
+
return { pdom, iterations };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Immediate post-dominator: the closest strict post-dominator.
|
|
65
|
+
function ipdom(cfg: CFG, pdom: Record<string, Set<string>>): Record<string, string | null> {
|
|
66
|
+
const res: Record<string, string | null> = {};
|
|
67
|
+
for (const b of Object.keys(cfg.succ)) {
|
|
68
|
+
if (b === cfg.exit) {
|
|
69
|
+
res[b] = null;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const strict = [...pdom[b]].filter((x) => x !== b);
|
|
73
|
+
// ipdom = the strict post-dom that does not post-dominate any other strict post-dom.
|
|
74
|
+
res[b] =
|
|
75
|
+
strict.find((cand) => strict.every((other) => other === cand || !pdom[other].has(cand))) ??
|
|
76
|
+
null;
|
|
77
|
+
}
|
|
78
|
+
return res;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const CFGS: CFG[] = [
|
|
82
|
+
{
|
|
83
|
+
name: 'early-return',
|
|
84
|
+
hazard: 'early return / multiple paths to EXIT',
|
|
85
|
+
tsSource: `function f(x){ if (x) { return 1; } g(); return 2; }`,
|
|
86
|
+
entry: 'ENTRY',
|
|
87
|
+
exit: 'EXIT',
|
|
88
|
+
succ: { ENTRY: ['ret1', 'g'], ret1: ['EXIT'], g: ['ret2'], ret2: ['EXIT'], EXIT: [] },
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: 'try-throw-finally',
|
|
92
|
+
hazard: 'try/throw/finally with multiple exits through finally',
|
|
93
|
+
tsSource: `function f(){ try { risky(); } catch(e){ handle(e); } finally { cleanup(); } done(); }`,
|
|
94
|
+
entry: 'ENTRY',
|
|
95
|
+
exit: 'EXIT',
|
|
96
|
+
// try → (normal | throw→catch) → finally → done → EXIT; finally also reached on rethrow
|
|
97
|
+
succ: {
|
|
98
|
+
ENTRY: ['try'],
|
|
99
|
+
try: ['finally', 'catch'],
|
|
100
|
+
catch: ['finally'],
|
|
101
|
+
finally: ['done', 'EXIT'],
|
|
102
|
+
done: ['EXIT'],
|
|
103
|
+
EXIT: [],
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
name: 'labeled-break',
|
|
108
|
+
hazard: 'labeled break/continue across nested loops',
|
|
109
|
+
tsSource: `outer: for(;;){ for(;;){ if (a) break outer; if (b) continue outer; work(); } }`,
|
|
110
|
+
entry: 'ENTRY',
|
|
111
|
+
exit: 'EXIT',
|
|
112
|
+
succ: {
|
|
113
|
+
ENTRY: ['outerHead'],
|
|
114
|
+
outerHead: ['innerHead', 'EXIT'],
|
|
115
|
+
innerHead: ['breakOuter', 'afterIf1'],
|
|
116
|
+
breakOuter: ['EXIT'],
|
|
117
|
+
afterIf1: ['contOuter', 'work'],
|
|
118
|
+
contOuter: ['outerHead'],
|
|
119
|
+
work: ['innerHead'],
|
|
120
|
+
EXIT: [],
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
name: 'if-else-diamond',
|
|
125
|
+
hazard: 'baseline reducible diamond (sanity)',
|
|
126
|
+
tsSource: `function f(x){ if (x) { a(); } else { b(); } c(); }`,
|
|
127
|
+
entry: 'ENTRY',
|
|
128
|
+
exit: 'EXIT',
|
|
129
|
+
succ: { ENTRY: ['a', 'b'], a: ['c'], b: ['c'], c: ['EXIT'], EXIT: [] },
|
|
130
|
+
},
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
function main() {
|
|
134
|
+
let allOk = true;
|
|
135
|
+
for (const cfg of CFGS) {
|
|
136
|
+
try {
|
|
137
|
+
const { pdom, iterations } = postDominators(cfg);
|
|
138
|
+
const idom = ipdom(cfg, pdom);
|
|
139
|
+
// Sanity invariants: EXIT post-dominates every block; ipdom tree reaches EXIT.
|
|
140
|
+
const exitPostDomsAll = Object.keys(cfg.succ).every((b) => pdom[b].has(cfg.exit));
|
|
141
|
+
console.log(`\n[S2] ${cfg.name} — ${cfg.hazard}`);
|
|
142
|
+
console.log(` TS: ${cfg.tsSource}`);
|
|
143
|
+
console.log(
|
|
144
|
+
` converged in ${iterations} iters; EXIT post-dominates all blocks: ${exitPostDomsAll}`,
|
|
145
|
+
);
|
|
146
|
+
console.log(
|
|
147
|
+
` ipdom tree: ${Object.entries(idom)
|
|
148
|
+
.map(([b, p]) => `${b}->${p ?? '∅'}`)
|
|
149
|
+
.join(' ')}`,
|
|
150
|
+
);
|
|
151
|
+
if (!exitPostDomsAll) allOk = false;
|
|
152
|
+
} catch (e) {
|
|
153
|
+
allOk = false;
|
|
154
|
+
console.log(`\n[S2] ${cfg.name} FAILED: ${(e as Error).message}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
console.log(
|
|
158
|
+
`\n[S2] VERDICT INPUT: all hazard CFGs converged + EXIT post-dominates all = ${allOk}`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
main();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-
|
|
1
|
+
import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-CG6q8eTs.js";import{buildDynamicSystemPrompt as i}from"./context-builder-_HS0v2ma.js";var a=Object.defineProperty,o=(e,t)=>{let n={};for(var r in e)a(n,r,{get:e[r],enumerable:!0});return t||a(n,Symbol.toStringTag,{value:`Module`}),n};function s(e){let t=Symbol.for(e);return{brand(n,r){let i=r?Symbol.for(`${e}.${r}`):t;class a extends n{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return typeof e==`object`&&!!e&&i in e&&e[i]===!0}}return Object.defineProperty(a,`name`,{value:n.name}),a},sub(t){return s(`${e}.${t}`)},isInstance(e){return typeof e==`object`&&!!e&&t in e&&e[t]===!0}}}var c=s(`langchain`),l=o({ContextOverflowError:()=>m,LangChainError:()=>f,ModelAbortError:()=>p,addLangChainErrorFields:()=>u,ns:()=>d});function u(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}var d=c.sub(`error`),f=class extends d.brand(Error){name=`LangChainError`;constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},p=class extends d.brand(f,`model-abort`){name=`ModelAbortError`;partialOutput;constructor(e,t){super(e),this.partialOutput=t}},m=class e extends d.brand(f,`context-overflow`){name=`ContextOverflowError`;cause;constructor(e){super(e??`Input exceeded the model's context window.`)}static fromError(t){let n=new e(t.message);return n.cause=t,n}};function h(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`tool_call`)}function g(e){return!!(e&&typeof e==`object`&&`toolCall`in e&&e.toolCall!=null&&typeof e.toolCall==`object`&&`id`in e.toolCall&&typeof e.toolCall.id==`string`)}var _=class extends Error{output;constructor(e,t){super(e),this.output=t}};function v(e,t=b){e=e.trim();let n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
|
|
2
2
|
`)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
|
|
3
3
|
`)&&(r=r.substring(1));let i=r.indexOf("```"),a=r;return i!==-1&&(a=r.substring(0,i)),t(a.trim())}function y(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw Error(`Unexpected end of JSON input`);let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function i(){if(t[n]!==`"`)throw Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e=``,r=!1;for(;n<t.length;){let i=t[n];if(r){if(i===`n`)e+=`
|
|
4
4
|
`;else if(i===`t`)e+=` `;else if(i===`r`)e+=`\r`;else if(i===`\\`)e+=`\\`;else if(i===`"`)e+=`"`;else if(i===`b`)e+=`\b`;else if(i===`f`)e+=`\f`;else if(i===`/`)e+=`/`;else if(i===`u`){let r=t.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(r))r.length===4?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length;else throw Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${n}`);r=!1}else if(i===`\\`)r=!0;else if(i===`"`)return n+=1,e;else e+=i;n+=1}return r&&(e+=`\\`),e}function a(){let e=n,r=``;if(t[n]===`-`&&(r+=`-`,n+=1),n<t.length&&t[n]===`0`&&(r+=`0`,n+=1,t[n]>=`0`&&t[n]<=`9`))throw Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>=`1`&&t[n]<=`9`)for(;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&t[n]===`.`)for(r+=`.`,n+=1;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&(t[n]===`e`||t[n]===`E`))for(r+=t[n],n+=1,n<t.length&&(t[n]===`+`||t[n]===`-`)&&(r+=t[n],n+=1);n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(r===`-`)return-0;let i=Number.parseFloat(r);if(Number.isNaN(i))throw n=e,Error(`Invalid number '${r}' at position ${e}`);return i}function o(){if(r(),n>=t.length)throw Error(`Unexpected end of input at position ${n}`);let e=t[n];if(e===`{`)return c();if(e===`[`)return s();if(e===`"`)return i();if(`null`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if(`true`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if(`false`.startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if(e===`-`||e>=`0`&&e<=`9`)return a();throw Error(`Unexpected character '${e}' at position ${n}`)}function s(){if(t[n]!==`[`)throw Error(`Expected '[' at position ${n}, got '${t[n]}'`);let e=[];if(n+=1,r(),n>=t.length)return e;if(t[n]===`]`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length||(e.push(o()),r(),n>=t.length))return e;if(t[n]===`]`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`)}return e}function c(){if(t[n]!==`{`)throw Error(`Expected '{' at position ${n}, got '${t[n]}'`);let e={};if(n+=1,r(),n>=t.length)return e;if(t[n]===`}`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length)return e;let a=i();if(r(),n>=t.length)return e;if(t[n]!==`:`)throw Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length||(e[a]=o(),r(),n>=t.length))return e;if(t[n]===`}`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`)}return e}let l=o();if(r(),n<t.length)throw Error(`Unexpected character '${t[n]}' at position ${n}`);return l}function b(e){try{return e===void 0?null:y(e)}catch{return null}}var ee=/([A-Z]+)([A-Z][a-z0-9]+)/g,te=/([a-z0-9])([A-Z])/g,ne=/[-_\s]+/g;function x(e){return e.replace(ee,`$1_$2`).replace(te,`$1_$2`).replace(ne,`_`).toLowerCase()}function re(e){let t=e.trim();return/[-_\s]/.test(t)?t.replace(ne,`_`).toLowerCase().replace(/_+([a-z0-9])/g,(e,t)=>t.toUpperCase()):t}function ie(e,t){return t?.[e]||x(e)}function ae(e,t){return t?.[e]||re(e)}function oe(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var se=`__lc_escaped__`;function ce(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function le(e){return{[se]:e}}function S(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function ue(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function de(e){let t;return t=typeof e==`object`&&e?`lc_id`in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??`Object`]:[typeof e],{lc:1,type:`not_implemented`,id:t}}function fe(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return de(e);if(ue(e))return e;t.add(e);let n=e;if(ce(n))return t.delete(e),le(n);let r={};for(let[e,i]of Object.entries(n))r[e]=fe(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>fe(e,t)):e}function pe(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(S(t))return t[se];let n={};for(let[e,r]of Object.entries(t))n[e]=pe(r);return n}return Array.isArray(e)?e.map(e=>pe(e)):e}var me=o({Serializable:()=>ve,get_lc_unique_name:()=>_e});function he(e){return Array.isArray(e)?[...e]:{...e}}function ge(e,t){let n=he(e);for(let[e,r]of Object.entries(t)){let[t,...i]=e.split(`.`).reverse(),a=n;for(let e of i.reverse()){if(a[e]===void 0)break;a[e]=he(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function _e(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name==`function`&&(typeof t.lc_name!=`function`||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var ve=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,_e(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){this.lc_serializable_keys===void 0?this.lc_kwargs=e??{}:this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e)))}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||typeof this.lc_kwargs!=`object`||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},n={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,`lc_aliases`,this)),Object.assign(n,Reflect.get(e,`lc_secrets`,this)),Object.assign(r,Reflect.get(e,`lc_attributes`,this));Object.keys(n).forEach(e=>{let t=this,n=r,[i,...a]=e.split(`.`).reverse();for(let e of a.reverse()){if(!(e in t)||t[e]===void 0)return;(!(e in n)||n[e]===void 0)&&(typeof t[e]==`object`&&t[e]!=null?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&t[i]!==void 0&&(n[i]=n[i]||t[i])});let i={},a=new WeakSet;a.add(this);for(let[e,t]of Object.entries(r))i[e]=fe(t,a);let o=oe(Object.keys(n).length?ge(i,n):i,ie,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function ye(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&`source_type`in e&&(e.source_type===`url`||e.source_type===`base64`||e.source_type===`text`||e.source_type===`id`)}function be(e){return ye(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function xe(e){return ye(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function Se(e){return ye(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function Ce(e){return ye(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function we(e){if(ye(e)){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url}};if(e.source_type===`base64`){if(!e.mime_type)throw Error(`mime_type key is required for base64 data.`);return{type:`image_url`,image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error(`Unsupported source type. Only 'url' and 'base64' are supported.`)}function Te(e){let t=e.split(`;`)[0].split(`/`);if(t.length!==2)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let n=t[0].trim(),r=t[1].trim();if(n===``||r===``)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let t of e.split(`;`).slice(1)){let n=t.split(`=`);if(n.length!==2)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let r=n[0].trim(),a=n[1].trim();if(r===``)throw Error(`Invalid parameter syntax in mime type: "${e}".`);i[r]=a}return{type:n,subtype:r,parameters:i}}function Ee({dataUrl:e,asTypedArray:t=!1}){let n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function De(e,t){if(e.type===`text`){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type===`image`){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type===`audio`){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type===`file`){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function C(e,t){return w(e)&&e.type===t}function w(e){return typeof e==`object`&&!!e}function Oe(e){return Array.isArray(e)}function T(e){return typeof e==`string`}function ke(e){return typeof e==`number`}function E(e){return e instanceof Uint8Array}function Ae(e){try{return JSON.parse(e)}catch{return}}var je=e=>e();function Me(e){if(e.type===`char_location`&&T(e.document_title)&&ke(e.start_char_index)&&ke(e.end_char_index)&&T(e.cited_text)){let{document_title:t,start_char_index:n,end_char_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`char`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`page_location`&&T(e.document_title)&&ke(e.start_page_number)&&ke(e.end_page_number)&&T(e.cited_text)){let{document_title:t,start_page_number:n,end_page_number:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`page`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`content_block_location`&&T(e.document_title)&&ke(e.start_block_index)&&ke(e.end_block_index)&&T(e.cited_text)){let{document_title:t,start_block_index:n,end_block_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`block`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`web_search_result_location`&&T(e.url)&&T(e.title)&&T(e.encrypted_index)&&T(e.cited_text)){let{url:t,title:n,encrypted_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`url`,url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(e.type===`search_result_location`&&T(e.source)&&T(e.title)&&ke(e.start_block_index)&&ke(e.end_block_index)&&T(e.cited_text)){let{source:t,title:n,start_block_index:r,end_block_index:i,cited_text:a,...o}=e;return{...o,type:`citation`,source:`search`,url:t,title:n??void 0,startIndex:r,endIndex:i,citedText:a}}}function Ne(e){if(C(e,`document`)&&w(e.source)&&`type`in e.source){if(e.source.type===`base64`&&T(e.source.media_type)&&T(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&T(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&T(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&T(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(C(e,`image`)&&w(e.source)&&`type`in e.source){if(e.source.type===`base64`&&T(e.source.media_type)&&T(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&T(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&T(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Pe(e){function*t(){for(let t of e){let e=Ne(t);e?yield e:yield t}}return Array.from(t())}function Fe(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(C(n,`text`)&&T(n.text)){let{text:e,citations:t,...r}=n;if(Oe(t)&&t.length){let n=t.reduce((e,t)=>{let n=Me(t);return n?[...e,n]:e},[]);yield{...r,type:`text`,text:e,annotations:n};continue}else{yield{...r,type:`text`,text:e};continue}}else if(C(n,`thinking`)&&T(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(C(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(C(n,`tool_use`)&&T(n.name)&&T(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(C(n,`input_json_delta`)){if(Le(e)&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(C(n,`server_tool_use`)&&T(n.name)&&T(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:je(()=>{if(typeof n.input==`string`)return n.input;if(w(n.input)&&T(n.input.query))return n.input.query;if(T(n.partial_json)){let e=Ae(n.partial_json);if(e?.query)return e.query}return``})}};continue}else if(n.name===`code_execution`){yield{id:t,type:`server_tool_call`,name:`code_execution`,args:{code:je(()=>{if(typeof n.input==`string`)return n.input;if(w(n.input)&&T(n.input.code))return n.input.code;if(T(n.partial_json)){let e=Ae(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(C(n,`web_search_tool_result`)&&T(n.tool_use_id)&&Oe(n.content)){let{content:e,tool_use_id:t}=n;yield{type:`server_tool_call_result`,name:`web_search`,toolCallId:t,status:`success`,output:{urls:e.reduce((e,t)=>C(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(C(n,`code_execution_tool_result`)&&T(n.tool_use_id)&&w(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(C(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(C(n,`mcp_tool_result`)&&T(n.tool_use_id)&&w(n.content)){yield{type:`server_tool_call_result`,name:`mcp_tool_use`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(C(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(C(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(C(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=Ne(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Ie={translateContent:Fe,translateContentChunk:Fe};function Le(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Re(e){return be(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:xe(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:Ce(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function ze(e){return e.map(Re)}function Be(e){return!!(C(e,`image_url`)&&w(e.image_url)||C(e,`input_audio`)&&w(e.input_audio)||C(e,`file`)&&w(e.file))}function Ve(e){if(C(e,`image_url`)&&w(e.image_url)&&T(e.image_url.url)){let t=Ee({dataUrl:e.image_url.url});return t?{type:`image`,mimeType:t.mime_type,data:t.data}:{type:`image`,url:e.image_url.url}}else if(C(e,`input_audio`)&&w(e.input_audio)&&T(e.input_audio.data)&&T(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(C(e,`file`)&&w(e.file)&&T(e.file.data)){let t=Ee({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(T(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function He(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...We(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function Ue(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...We(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function We(e){let t=[];for(let n of e)Be(n)?t.push(Ve(n)):t.push(n);return t}function Ge(e){if(e.type===`url_citation`){let{url:t,title:n,start_index:r,end_index:i}=e;return{type:`citation`,url:t,title:n,startIndex:r,endIndex:i}}if(e.type===`file_citation`){let{file_id:t,filename:n,index:r}=e;return{type:`citation`,title:n,startIndex:r,endIndex:r,fileId:t}}return e}function Ke(e){function*t(){w(e.additional_kwargs?.reasoning)&&Oe(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>w(t)&&T(t.text)?`${e}${t.text}`:e,``)});let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)if(C(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=w(i)?{...i}:{};T(r)&&(o.phase=r);let s=Object.keys(o).length>0?{extras:o}:{};Array.isArray(n)?yield{...a,...s,type:`text`,text:String(t),annotations:n.map(Ge)}:yield{...a,...s,type:`text`,text:String(t)}}for(let t of e.tool_calls??[])yield{type:`tool_call`,id:t.id,name:t.name,args:t.args};if(w(e.additional_kwargs)&&Oe(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(C(t,`web_search_call`)){let e={};if(w(t.action)&&T(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:`server_tool_call`,name:`web_search`,args:e},t.status===`completed`||t.status===`failed`){let e={};w(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(C(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:Oe(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:Oe(t.results)?{results:t.results}:{}});continue}else if(C(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(C(t,`code_interpreter_call`)){if(T(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),Oe(t.outputs)){let e=je(()=>{if(t.status!==`in_progress`){if(t.status===`completed`)return 0;if(t.status===`incomplete`)return 127;if(t.status!==`interpreting`&&t.status===`failed`)return 1}});for(let n of t.outputs)if(C(n,`logs`)){yield{type:`server_tool_call_result`,toolCallId:t.id??``,status:`success`,output:{type:`code_interpreter_output`,returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}continue}else if(C(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(C(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(C(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(C(t,`tool_search_call`)){let e={};w(t.arguments)&&Object.assign(e,t.arguments);let n={};T(t.execution)&&(n.execution=t.execution),T(t.status)&&(n.status=t.status),T(t.call_id)&&(n.call_id=t.call_id),yield{id:T(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(C(t,`tool_search_output`)){let e={name:`tool_search`};T(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:T(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:Oe(t.tools)?t.tools:[]},extras:e};continue}else if(C(t,`image_generation_call`)){T(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:T(t.id)?t.id:void 0,metadata:{status:T(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}w(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function qe(e){function*t(){yield*Ke(e);for(let t of e.tool_call_chunks??[])yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args}}return Array.from(t())}var Je={translateContent:e=>typeof e.content==`string`?He(e):Ke(e),translateContentChunk:e=>typeof e.content==`string`?Ue(e):qe(e)};function Ye(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Xe(e,t=`pretty`){return t===`pretty`?Ze(e):JSON.stringify(e)}function Ze(e){let t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i=`=`.repeat(r),a=n.length%2==0?i:`${i}=`;if(t.push(`${i}${n}${a}`),e.type===`ai`){let n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push(`Tool Calls:`);for(let e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(` Args:`);for(let[n,r]of Object.entries(e.args))t.push(` ${n}: ${typeof r==`object`?JSON.stringify(r):r}`)}}}if(e.type===`tool`){let n=e;n.name&&t.push(`Name: ${n.name}`)}return typeof e.content==`string`&&e.content.trim()&&(t.length>1&&t.push(``),t.push(e.content)),t.join(`
|