gitnexus 1.6.5-rc.26 → 1.6.5-rc.28
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/cli/index.js +2 -0
- package/dist/cli/wiki.d.ts +2 -0
- package/dist/cli/wiki.js +11 -0
- package/dist/core/wiki/llm-client.d.ts +4 -0
- package/dist/core/wiki/llm-client.js +3 -3
- package/package.json +1 -1
- package/web/assets/{agent-BG6RCOzz.js → agent-BDDjazGf.js} +12 -12
- package/web/assets/architecture-7EHR7CIX-6QZW5X65-BETj2x4g.js +1 -0
- package/web/assets/architectureDiagram-UL44E2DR-0TKVszPW.js +36 -0
- package/web/assets/blockDiagram-7IZFK4PR-B4niSLvR.js +132 -0
- package/web/assets/{c4Diagram-Y2BXMSZH-hLOeq7xC.js → c4Diagram-Y2BXMSZH-DIzEXalR.js} +6 -6
- package/web/assets/chunk-2T2R6R2M-n6s9JZqv.js +4 -0
- package/web/assets/{chunk-2UTLFMKG-CpoohCFN.js → chunk-2UTLFMKG-CMBB1TMN.js} +1 -1
- package/web/assets/{chunk-3SSMPTDK-CfqpR3Nr.js → chunk-3SSMPTDK-BzGeeheI.js} +1 -1
- package/web/assets/{chunk-4R4BOZG6-D3gm7tYj.js → chunk-4R4BOZG6-mKhL59ul.js} +1 -1
- package/web/assets/chunk-5IMINLNL-CnTLsXIV.js +1 -0
- package/web/assets/chunk-5VCL7Z4A-w1BCx98Z.js +1 -0
- package/web/assets/chunk-6764PJDD-ChwMM2z4.js +1 -0
- package/web/assets/chunk-67TQ5CYL-CChC2cAv.js +124 -0
- package/web/assets/chunk-7J6CGLKN-DT-b53FT.js +10 -0
- package/web/assets/chunk-7W6UQGC5-CgFyfZ6k.js +1 -0
- package/web/assets/{chunk-AZZRMDJM-DSoCJlUA.js → chunk-AZZRMDJM-5E9ARdDQ.js} +1 -1
- package/web/assets/{chunk-C62D2QBJ-CvFF2PnB.js → chunk-C62D2QBJ-CDAWj26E.js} +1 -1
- package/web/assets/{chunk-CEXFNPSA-DdNtJtrF.js → chunk-CEXFNPSA-D68Tk6ls.js} +1 -1
- package/web/assets/chunk-INKRHTLW-ELpfuk9h.js +70 -0
- package/web/assets/{chunk-J5EP6P6S-DtcVaAJI.js → chunk-J5EP6P6S-DxWW0yvu.js} +1 -1
- package/web/assets/{chunk-JQRUD6KW-DElaNjc0.js → chunk-JQRUD6KW-Dcq_Qnyy.js} +1 -1
- package/web/assets/chunk-KGFNY3KK-W-VR57xb.js +62 -0
- package/web/assets/{chunk-KGYTTC2M-D0K5or7e.js → chunk-KGYTTC2M-C6PHeuay.js} +1 -1
- package/web/assets/chunk-KNLZD3CH-BuZBOcso.js +1 -0
- package/web/assets/{chunk-KRXBNO2N-DpR8iDt8.js → chunk-KRXBNO2N-DH2NPM7I.js} +1 -1
- package/web/assets/{chunk-LCXTWHL2-DdMObOEk.js → chunk-LCXTWHL2-DavkqCND.js} +5 -5
- package/web/assets/chunk-LII3EMHJ-3X33tCpU.js +1 -0
- package/web/assets/chunk-QA3QBVWF-D5Ha3GgB.js +2 -0
- package/web/assets/{chunk-RERM46MO-Betu1cSy.js → chunk-RERM46MO-DQNbXtfw.js} +1 -1
- package/web/assets/{chunk-RG4AUYOV-BUCJ2JP5.js → chunk-RG4AUYOV-D_ubpjIs.js} +6 -6
- package/web/assets/{chunk-RKZBBQEN-Cutpza0t.js → chunk-RKZBBQEN-BmTPLSyv.js} +1 -1
- package/web/assets/{chunk-RLI5ZMPA-BFUxCvX2.js → chunk-RLI5ZMPA-DExu2DOK.js} +1 -1
- package/web/assets/chunk-T2UQINTJ-kGYG7ppP.js +1 -0
- package/web/assets/chunk-T5OCTHI4--9wWpVws.js +1 -0
- package/web/assets/{chunk-UP6H54XL-0YWa0NDg.js → chunk-UP6H54XL-DsKdC6jC.js} +1 -1
- package/web/assets/{chunk-UXSXWOXI-CSz0OXpz.js → chunk-UXSXWOXI-DR81EqLr.js} +1 -1
- package/web/assets/chunk-UY5QBCOK-Du-c56gs.js +1 -0
- package/web/assets/{chunk-W44A43WB-AOmgoT-X.js → chunk-W44A43WB-lrCpuupA.js} +1 -1
- package/web/assets/chunk-ZXARS5L4-CSZRiyOf.js +1 -0
- package/web/assets/classDiagram-KGZ6W3CR-CojpAtMx.js +1 -0
- package/web/assets/classDiagram-v2-72OJOZXJ-DGdoqp9r.js +1 -0
- package/web/assets/cose-bilkent-UX7MHV2Q-BHv2bbtl.js +1 -0
- package/web/assets/dagre-ND4H6XIP-DsIr9MOv.js +4 -0
- package/web/assets/diagram-3NCE3AQN-5odGXWhY.js +43 -0
- package/web/assets/diagram-GF46GFSD-Du26loU5.js +24 -0
- package/web/assets/diagram-HNR7UZ2L-fUWreZzx.js +3 -0
- package/web/assets/diagram-QXG6HAR7-Vi3k1Pck.js +24 -0
- package/web/assets/diagram-WEQXMOUZ-C646kJx-.js +10 -0
- package/web/assets/erDiagram-L5TCEMPS-B02mTKtG.js +85 -0
- package/web/assets/eventmodeling-FCH6USID-MREXMVOE-B3myHUst.js +1 -0
- package/web/assets/flowDiagram-H6V6AXG4-DYQh7Y0C.js +162 -0
- package/web/assets/ganttDiagram-JCBTUEKG-BHQssTz6.js +292 -0
- package/web/assets/gitGraph-WXDBUCRP-R675I2BI-DF3rtf4A.js +1 -0
- package/web/assets/gitGraphDiagram-S2ZK5IYY-CCwVLT__.js +106 -0
- package/web/assets/index-D6RE1OtS.js +623 -0
- package/web/assets/info-J43DQDTF-KCYPFFUO-R4XV_akJ.js +1 -0
- package/web/assets/infoDiagram-3YFTVSEB-Dz72SU_l.js +2 -0
- package/web/assets/{ishikawaDiagram-BNXS4ZKH-B3NgQ4lJ.js → ishikawaDiagram-BNXS4ZKH-O10m70dP.js} +6 -6
- package/web/assets/journeyDiagram-M6C3CM3L-DNPYCpvq.js +139 -0
- package/web/assets/kanban-definition-75IXJCU3-uUbWa1c6.js +89 -0
- package/web/assets/{katex-K3KEBU37-CqF6_ZN-.js → katex-K3KEBU37-CrVLz8l7.js} +1 -1
- package/web/assets/{mindmap-definition-2TDM6QVE-B5c9VOzs.js → mindmap-definition-2TDM6QVE-DpMxZSfi.js} +29 -29
- package/web/assets/packet-YPE3B663-LP52Z2RK-CgQPdNZa.js +1 -0
- package/web/assets/pie-LRSECV5Y-TCRJHUBD-BzWOwc_c.js +1 -0
- package/web/assets/pieDiagram-CU6KROY3-CMkeerkq.js +30 -0
- package/web/assets/{quadrantDiagram-VICAPDV7-C47UxSZD.js → quadrantDiagram-VICAPDV7-bAm6Hi_5.js} +6 -6
- package/web/assets/radar-GUYGQ44K-RDLRG3WG-B7KG0FN7.js +1 -0
- package/web/assets/requirementDiagram-JXO7QTGE-BTeZrcKz.js +84 -0
- package/web/assets/sankeyDiagram-URQDO5SZ-LFJz53u5.js +40 -0
- package/web/assets/sequenceDiagram-VS2MUI6T-Cb_0gO9y.js +162 -0
- package/web/assets/stateDiagram-7D4R322I-gzKZ2GGa.js +1 -0
- package/web/assets/stateDiagram-v2-36443NZ5-I1MiGU6x.js +1 -0
- package/web/assets/timeline-definition-O6YCAMPW-BVMAewfu.js +120 -0
- package/web/assets/treeView-BLDUP644-QA4HXRO3-CRSxEwLO.js +1 -0
- package/web/assets/treemap-LRROVOQU-LLAWBHMP-a0PfKoVn.js +1 -0
- package/web/assets/{vennDiagram-MWXL3ELB-W8Yoaayh.js → vennDiagram-MWXL3ELB-B1LIvNBr.js} +8 -8
- package/web/assets/wardley-L42UT6IY-5TKZOOLJ-BKQ6e5mC.js +1 -0
- package/web/assets/wardleyDiagram-CUQ6CDDI-DzzfaG4H.js +78 -0
- package/web/assets/{xychartDiagram-N2JHSOCM-DGRtrj4P.js → xychartDiagram-N2JHSOCM-BMw7CGC6.js} +6 -6
- package/web/index.html +13 -2
- package/web/assets/architecture-7EHR7CIX-6QZW5X65-F-tujre-.js +0 -1
- package/web/assets/architectureDiagram-UL44E2DR-2GL7nOvO.js +0 -36
- package/web/assets/blockDiagram-7IZFK4PR-5AjX0pPU.js +0 -132
- package/web/assets/chunk-2T2R6R2M-B_pq_2nf.js +0 -4
- package/web/assets/chunk-6764PJDD-WcI965eO.js +0 -1
- package/web/assets/chunk-LII3EMHJ-I78zXtzi.js +0 -1
- package/web/assets/chunk-T5OCTHI4-DKwlkuvB.js +0 -1
- package/web/assets/chunk-ZXARS5L4-DIzgxjMw.js +0 -1
- package/web/assets/classDiagram-KGZ6W3CR-BT-rn7LF.js +0 -1
- package/web/assets/classDiagram-v2-72OJOZXJ-uR3nDadY.js +0 -1
- package/web/assets/cose-bilkent-UX7MHV2Q-DCSCD1TK.js +0 -1
- package/web/assets/dagre-ND4H6XIP-CsciHSij.js +0 -4
- package/web/assets/diagram-3NCE3AQN-BKUT5Rpc.js +0 -43
- package/web/assets/diagram-GF46GFSD-Dxb4hZSo.js +0 -24
- package/web/assets/diagram-HNR7UZ2L-D3qus9Cn.js +0 -3
- package/web/assets/diagram-QXG6HAR7-r9BMLGGP.js +0 -24
- package/web/assets/diagram-WEQXMOUZ-BGXqs7-m.js +0 -10
- package/web/assets/erDiagram-L5TCEMPS-LgSWVrkZ.js +0 -85
- package/web/assets/eventmodeling-FCH6USID-MREXMVOE-By7r3bla.js +0 -1
- package/web/assets/flowDiagram-H6V6AXG4-Bj_vV5ky.js +0 -162
- package/web/assets/ganttDiagram-JCBTUEKG-B1eVITSh.js +0 -292
- package/web/assets/gitGraph-WXDBUCRP-R675I2BI-ClEP6RdE.js +0 -1
- package/web/assets/gitGraphDiagram-S2ZK5IYY-BP0R-_FD.js +0 -106
- package/web/assets/index-oL-ZNYwb.js +0 -885
- package/web/assets/info-J43DQDTF-KCYPFFUO-bBJRjmP5.js +0 -1
- package/web/assets/infoDiagram-3YFTVSEB-Dmj4OEO3.js +0 -2
- package/web/assets/journeyDiagram-M6C3CM3L-DALmL4_N.js +0 -139
- package/web/assets/kanban-definition-75IXJCU3-AvVbHpnN.js +0 -89
- package/web/assets/packet-YPE3B663-LP52Z2RK-1ZCldnu3.js +0 -1
- package/web/assets/pie-LRSECV5Y-TCRJHUBD-EhjHC5EE.js +0 -1
- package/web/assets/pieDiagram-CU6KROY3-Po2HSSR4.js +0 -30
- package/web/assets/radar-GUYGQ44K-RDLRG3WG-CvXjgxlW.js +0 -1
- package/web/assets/requirementDiagram-JXO7QTGE-CpECN_Hq.js +0 -84
- package/web/assets/sankeyDiagram-URQDO5SZ-B3b7cLrS.js +0 -40
- package/web/assets/sequenceDiagram-VS2MUI6T-CRJ95oVP.js +0 -162
- package/web/assets/stateDiagram-7D4R322I-C7U9b3ks.js +0 -1
- package/web/assets/stateDiagram-v2-36443NZ5-BQajbtov.js +0 -1
- package/web/assets/timeline-definition-O6YCAMPW-rtbk6BBo.js +0 -120
- package/web/assets/treeView-BLDUP644-QA4HXRO3-R2o5gwfP.js +0 -1
- package/web/assets/treemap-LRROVOQU-LLAWBHMP-Cesmac_u.js +0 -1
- package/web/assets/wardley-L42UT6IY-5TKZOOLJ-B9HYoRgA.js +0 -1
- package/web/assets/wardleyDiagram-CUQ6CDDI-DIZw5Abj.js +0 -78
- /package/web/assets/{chunk-AQ6EADP3-BpMj3rQl.js → chunk-AQ6EADP3-CCFje6lL.js} +0 -0
- /package/web/assets/{context-builder-CG-ydtp4.js → context-builder-_HS0v2ma.js} +0 -0
package/dist/cli/index.js
CHANGED
|
@@ -103,6 +103,8 @@ program
|
|
|
103
103
|
.option('--reasoning-model', 'Mark deployment as reasoning model (o1/o3/o4-mini) — strips temperature, uses max_completion_tokens')
|
|
104
104
|
.option('--no-reasoning-model', 'Disable reasoning model mode (overrides saved config)')
|
|
105
105
|
.option('--concurrency <n>', 'Parallel LLM calls (default: 3)', '3')
|
|
106
|
+
.option('--timeout <seconds>', 'Per-attempt LLM request timeout in seconds (default: 60)')
|
|
107
|
+
.option('--retries <n>', 'Max LLM retry attempts per request (default: 3)')
|
|
106
108
|
.option('--gist', 'Publish wiki as a public GitHub Gist after generation')
|
|
107
109
|
.option('-v, --verbose', 'Enable verbose output (show LLM commands and responses)')
|
|
108
110
|
.option('--review', 'Stop after grouping to review module structure before generating pages')
|
package/dist/cli/wiki.d.ts
CHANGED
package/dist/cli/wiki.js
CHANGED
|
@@ -304,6 +304,17 @@ export const wikiCommand = async (inputPath, options) => {
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
|
+
// ── Apply per-run overrides not saved to config ────────────────────
|
|
308
|
+
if (options?.timeout) {
|
|
309
|
+
const secs = parseInt(options.timeout, 10);
|
|
310
|
+
if (!isNaN(secs) && secs > 0)
|
|
311
|
+
llmConfig.requestTimeoutMs = secs * 1000;
|
|
312
|
+
}
|
|
313
|
+
if (options?.retries) {
|
|
314
|
+
const n = parseInt(options.retries, 10);
|
|
315
|
+
if (!isNaN(n) && n > 0)
|
|
316
|
+
llmConfig.maxAttempts = n;
|
|
317
|
+
}
|
|
307
318
|
// ── Setup progress bar with elapsed timer ──────────────────────────
|
|
308
319
|
const bar = new cliProgress.SingleBar({
|
|
309
320
|
format: ' {bar} {percentage}% | {phase}',
|
|
@@ -19,6 +19,10 @@ export interface LLMConfig {
|
|
|
19
19
|
apiVersion?: string;
|
|
20
20
|
/** When true, strips sampling params and uses max_completion_tokens instead of max_tokens */
|
|
21
21
|
isReasoningModel?: boolean;
|
|
22
|
+
/** Per-attempt fetch timeout in ms (default: 60_000). */
|
|
23
|
+
requestTimeoutMs?: number;
|
|
24
|
+
/** Max fetch attempts before giving up (default: 3). */
|
|
25
|
+
maxAttempts?: number;
|
|
22
26
|
}
|
|
23
27
|
export interface LLMResponse {
|
|
24
28
|
content: string;
|
|
@@ -170,11 +170,11 @@ export async function callLLM(prompt, config, systemPrompt, options) {
|
|
|
170
170
|
// indefinitely on a frozen TCP connection — the per-call
|
|
171
171
|
// signal is the only timeout `resilientFetch` honors;
|
|
172
172
|
// `capDelayMs` only bounds the *backoff* between attempts.
|
|
173
|
-
// 60s
|
|
174
|
-
signal: AbortSignal.timeout(60_000),
|
|
173
|
+
// Default 60s; raise via --timeout for slow models or large pages.
|
|
174
|
+
signal: AbortSignal.timeout(config.requestTimeoutMs ?? 60_000),
|
|
175
175
|
}, {
|
|
176
176
|
breakerKey: `wiki-llm-${new URL(url).host}`,
|
|
177
|
-
retry: { maxAttempts: 3, baseDelayMs: 2_000, capDelayMs: 30_000 },
|
|
177
|
+
retry: { maxAttempts: config.maxAttempts ?? 3, baseDelayMs: 2_000, capDelayMs: 30_000 },
|
|
178
178
|
});
|
|
179
179
|
}
|
|
180
180
|
catch (err) {
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as e,t}from"./chunk-CilyBKbf.js";import{
|
|
1
|
+
import{r as e,t}from"./chunk-CilyBKbf.js";import{o as n,s as r}from"./index-D6RE1OtS.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=t(((e,t)=>{t.exports=function(e,t){if(typeof e!=`string`)throw TypeError(`Expected a string`);return t=t===void 0?`_`:t,e.replace(/([a-z\d])([A-Z])/g,`$1`+t+`$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1`+t+`$2`).toLowerCase()}})),x=t(((e,t)=>{var n=/[\p{Lu}]/u,r=/[\p{Ll}]/u,i=/^[\p{Lu}](?![\p{Lu}])/gu,a=/([\p{Alpha}\p{N}_]|$)/u,o=/[_.\- ]+/,s=RegExp(`^`+o.source),c=new RegExp(o.source+a.source,`gu`),l=RegExp(`\\d+`+a.source,`gu`),u=(e,t,i)=>{let a=!1,o=!1,s=!1;for(let c=0;c<e.length;c++){let l=e[c];a&&n.test(l)?(e=e.slice(0,c)+`-`+e.slice(c),a=!1,s=o,o=!0,c++):o&&s&&r.test(l)?(e=e.slice(0,c-1)+`-`+e.slice(c-1),s=o,o=!1,a=!0):(a=t(l)===l&&i(l)!==l,s=o,o=i(l)===l&&t(l)!==l)}return e},d=(e,t)=>(i.lastIndex=0,e.replace(i,e=>t(e))),f=(e,t)=>(c.lastIndex=0,l.lastIndex=0,e.replace(c,(e,n)=>t(n)).replace(l,e=>t(e))),p=(e,t)=>{if(!(typeof e==`string`||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join(`-`):e.trim(),e.length===0)return``;let n=t.locale===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),r=t.locale===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?r(e):n(e):(e!==n(e)&&(e=u(e,n,r)),e=e.replace(s,``),e=t.preserveConsecutiveUppercase?d(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),f(e,r))};t.exports=p,t.exports.default=p})),te=e(ee(),1),S=e(x(),1);function ne(e,t){return t?.[e]||(0,te.default)(e)}function re(e,t){return t?.[e]||(0,S.default)(e)}function ie(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var ae=`__lc_escaped__`;function oe(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function se(e){return{[ae]:e}}function ce(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function C(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function le(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 ue(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return le(e);if(C(e))return e;t.add(e);let n=e;if(oe(n))return t.delete(e),se(n);let r={};for(let[e,i]of Object.entries(n))r[e]=ue(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>ue(e,t)):e}function de(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(ce(t))return t[ae];let n={};for(let[e,r]of Object.entries(t))n[e]=de(r);return n}return Array.isArray(e)?e.map(e=>de(e)):e}var fe=o({Serializable:()=>ge,get_lc_unique_name:()=>he});function pe(e){return Array.isArray(e)?[...e]:{...e}}function me(e,t){let n=pe(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]=pe(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function he(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 ge=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,he(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]=ue(t,a);let o=ie(Object.keys(n).length?me(i,n):i,ne,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function _e(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 ve(e){return _e(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function ye(e){return _e(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function be(e){return _e(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function xe(e){return _e(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function Se(e){if(_e(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 Ce(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 we({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 Te(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 w(e,t){return T(e)&&e.type===t}function T(e){return typeof e==`object`&&!!e}function Ee(e){return Array.isArray(e)}function E(e){return typeof e==`string`}function De(e){return typeof e==`number`}function Oe(e){return e instanceof Uint8Array}function D(e){try{return JSON.parse(e)}catch{return}}var ke=e=>e();function Ae(e){if(e.type===`char_location`&&E(e.document_title)&&De(e.start_char_index)&&De(e.end_char_index)&&E(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`&&E(e.document_title)&&De(e.start_page_number)&&De(e.end_page_number)&&E(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`&&E(e.document_title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(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`&&E(e.url)&&E(e.title)&&E(e.encrypted_index)&&E(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`&&E(e.source)&&E(e.title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(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 je(e){if(w(e,`document`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&E(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(w(e,`image`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Me(e){function*t(){for(let t of e){let e=je(t);e?yield e:yield t}}return Array.from(t())}function Ne(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){let{text:e,citations:t,...r}=n;if(Ee(t)&&t.length){let n=t.reduce((e,t)=>{let n=Ae(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(w(n,`thinking`)&&E(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(w(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`tool_use`)&&E(n.name)&&E(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(w(n,`input_json_delta`)){if(Fe(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(w(n,`server_tool_use`)&&E(n.name)&&E(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.query))return n.input.query;if(E(n.partial_json)){let e=D(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:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.code))return n.input.code;if(E(n.partial_json)){let e=D(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(w(n,`web_search_tool_result`)&&E(n.tool_use_id)&&Ee(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)=>w(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(w(n,`code_execution_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(w(n,`mcp_tool_result`)&&E(n.tool_use_id)&&T(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(w(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(w(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(w(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=je(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Pe={translateContent:Ne,translateContentChunk:Ne};function Fe(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Ie(e){return ve(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ye(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:xe(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Le(e){return e.map(Ie)}function Re(e){return!!(w(e,`image_url`)&&T(e.image_url)||w(e,`input_audio`)&&T(e.input_audio)||w(e,`file`)&&T(e.file))}function ze(e){if(w(e,`image_url`)&&T(e.image_url)&&E(e.image_url.url)){let t=we({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(w(e,`input_audio`)&&T(e.input_audio)&&E(e.input_audio.data)&&E(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(w(e,`file`)&&T(e.file)&&E(e.file.data)){let t=we({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(E(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function Be(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(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 Ve(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(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 He(e){let t=[];for(let n of e)Re(n)?t.push(ze(n)):t.push(n);return t}function Ue(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 We(e){function*t(){T(e.additional_kwargs?.reasoning)&&Ee(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>T(t)&&E(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(w(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=T(i)?{...i}:{};E(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(Ue)}: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(T(e.additional_kwargs)&&Ee(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(w(t,`web_search_call`)){let e={};if(T(t.action)&&E(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={};T(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(w(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:Ee(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:Ee(t.results)?{results:t.results}:{}});continue}else if(w(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`code_interpreter_call`)){if(E(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),Ee(t.outputs)){let e=ke(()=>{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(w(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(w(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(w(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(w(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`tool_search_call`)){let e={};T(t.arguments)&&Object.assign(e,t.arguments);let n={};E(t.execution)&&(n.execution=t.execution),E(t.status)&&(n.status=t.status),E(t.call_id)&&(n.call_id=t.call_id),yield{id:E(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(w(t,`tool_search_output`)){let e={name:`tool_search`};E(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:Ee(t.tools)?t.tools:[]},extras:e};continue}else if(w(t,`image_generation_call`)){E(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:E(t.id)?t.id:void 0,metadata:{status:E(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}T(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function Ge(e){function*t(){yield*We(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 Ke={translateContent:e=>typeof e.content==`string`?Be(e):We(e),translateContentChunk:e=>typeof e.content==`string`?Ve(e):Ge(e)};function qe(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Je(e,t=`pretty`){return t===`pretty`?Ye(e):JSON.stringify(e)}function Ye(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(`
|
|
@@ -213,11 +213,11 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
213
213
|
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var eX={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},tX=4096;function nX(e){return e?Object.entries(eX).find(([t])=>e.startsWith(t))?.[1]??tX:tX}function rX(e){return!!(e.tools&&e.tools.length>0)}function iX(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function aX(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function oX(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function sX(e){return`input_schema`in e}function cX(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.type==`string`&&[`text_editor_`,`computer_`,`bash_`,`web_search_`,`web_fetch_`,`str_replace_editor_`,`str_replace_based_edit_tool_`,`code_execution_`,`memory_`,`tool_search_`,`mcp_toolset`].some(t=>typeof e.type==`string`&&e.type.startsWith(t))}function lX(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function uX(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var dX=class extends Sw{static lc_name(){return`ChatAnthropic`}get lc_secrets(){return{anthropicApiKey:`ANTHROPIC_API_KEY`,apiKey:`ANTHROPIC_API_KEY`}}get lc_aliases(){return{modelName:`model`}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName=`claude-sonnet-4-5-20250929`;model=`claude-sonnet-4-5-20250929`;invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:`disabled`};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};if(super(n??{}),this._addVersion(`@langchain/anthropic`,`1.3.29`),this.anthropicApiKey=n?.apiKey??n?.anthropicApiKey??pr(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=n?.anthropicApiUrl,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??nX(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,this.thinking=n?.thinking??this.thinking,this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new YY(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(e=>{if(KE(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(cX(e)||sX(e))return e;if(sC(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(KE(e))return{name:e.name,description:e.description,input_schema:Nm(e.schema)?Vv(e.schema):e.schema,...e.extras?eG.parse(e.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=$W(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in tG){let n=tG[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=OG(this.model,r),o={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:lX(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return kG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,AG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=wG(e),a={...r,...i,stream:!0},o=!rX(a)&&!iX(a)&&!aX(a)&&!oX(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=jG(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=uX(a),l=new Zl({message:new Xt({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async*_streamChatModelEvents(e,t,n){let r=this.invocationParams(t),i=wG(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal}),s=this.streamUsage??t.streamUsage;yield*LG(async function*(e,t){for await(let n of e){if(t?.aborted){e.controller?.abort();return}yield n}}(o,t.signal),{streamUsage:s??!0})}async _generateNonStreaming(e,t,n){let r=wG(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=MG(i,a),{role:s,type:c,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.call(async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw FG(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw FG(e)}})}_llmType(){return`anthropic`}get profile(){return IG[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=WC(i);let e=QY(Vv(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,t;if(Nm(i)||ev(i)){let n=Vv(i);t=[{name:e,description:n.description??`A function available to call.`,input_schema:n}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(t=[i],e=i.name):t=[{name:e,description:i.description??``,input_schema:i}];if(r=GC(i,e,ZW),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:t,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:t,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},fX=class extends dX{};YD(`command`,[B({command:aO(`view`),path:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),insert_text:uD()}),B({command:aO(`delete`),path:uD()}),B({command:aO(`rename`),old_path:uD(),new_path:uD()})]),YD(`command`,[B({command:aO(`view`),path:uD(),view_range:$D([MD(),MD()]).optional()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),new_str:uD()})]);var pX=$D([MD(),MD()]),mX=B({action:aO(`screenshot`)}),hX=B({action:aO(`left_click`),coordinate:pX}),gX=B({action:aO(`right_click`),coordinate:pX}),_X=B({action:aO(`middle_click`),coordinate:pX}),vX=B({action:aO(`double_click`),coordinate:pX}),yX=B({action:aO(`triple_click`),coordinate:pX}),bX=B({action:aO(`left_click_drag`),start_coordinate:pX,end_coordinate:pX}),xX=B({action:aO(`left_mouse_down`),coordinate:pX}),SX=B({action:aO(`left_mouse_up`),coordinate:pX}),CX=B({action:aO(`scroll`),coordinate:pX,scroll_direction:rO([`up`,`down`,`left`,`right`]),scroll_amount:MD()}),wX=B({action:aO(`type`),text:uD()}),TX=B({action:aO(`key`),key:uD()}),EX=B({action:aO(`mouse_move`),coordinate:pX}),DX=B({action:aO(`hold_key`),key:uD()}),OX=B({action:aO(`wait`),duration:MD().optional()}),kX=B({action:aO(`zoom`),region:$D([MD(),MD(),MD(),MD()])});YD(`action`,[mX,hX,gX,_X,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX]),YD(`action`,[mX,hX,gX,_X,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX,kX]),qD([B({command:uD().describe(`The bash command to run`)}),B({restart:aO(!0).describe(`Set to true to restart the bash session`)})]);for(var AX=[],jX=0;jX<256;++jX)AX.push((jX+256).toString(16).slice(1));function MX(e,t=0){return(AX[e[t+0]]+AX[e[t+1]]+AX[e[t+2]]+AX[e[t+3]]+`-`+AX[e[t+4]]+AX[e[t+5]]+`-`+AX[e[t+6]]+AX[e[t+7]]+`-`+AX[e[t+8]]+AX[e[t+9]]+`-`+AX[e[t+10]]+AX[e[t+11]]+AX[e[t+12]]+AX[e[t+13]]+AX[e[t+14]]+AX[e[t+15]]).toLowerCase()}var NX,PX=new Uint8Array(16);function FX(){if(!NX&&(NX=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!NX))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return NX(PX)}var IX={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function LX(e,t,n){if(IX.randomUUID&&!t&&!e)return IX.randomUUID();e||={};var r=e.random||(e.rng||FX)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return MX(r)}function RX(e,t){return new Xt({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:LX()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function zX(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function BX(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function VX(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[zX(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[zX(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function HX(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function UX(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function WX(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return VX(e);if(e._getType()===`ai`)return BX(e);if(e._getType()===`system`)return HX(e);if(e._getType()===`tool`)return UX(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var GX=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},KX={searchParams:`URLSearchParams`in GX,iterable:`Symbol`in GX&&`iterator`in Symbol,blob:`FileReader`in GX&&`Blob`in GX&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in GX,arrayBuffer:`ArrayBuffer`in GX};function qX(e){return e&&DataView.prototype.isPrototypeOf(e)}if(KX.arrayBuffer)var JX=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],YX=ArrayBuffer.isView||function(e){return e&&JX.indexOf(Object.prototype.toString.call(e))>-1};function XX(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function ZX(e){return typeof e!=`string`&&(e=String(e)),e}function QX(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return KX.iterable&&(t[Symbol.iterator]=function(){return t}),t}function $X(e){this.map={},e instanceof $X?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}$X.prototype.append=function(e,t){e=XX(e),t=ZX(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},$X.prototype.delete=function(e){delete this.map[XX(e)]},$X.prototype.get=function(e){return e=XX(e),this.has(e)?this.map[e]:null},$X.prototype.has=function(e){return this.map.hasOwnProperty(XX(e))},$X.prototype.set=function(e,t){this.map[XX(e)]=ZX(t)},$X.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},$X.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),QX(e)},$X.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),QX(e)},$X.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),QX(e)},KX.iterable&&($X.prototype[Symbol.iterator]=$X.prototype.entries);function eZ(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function tZ(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function nZ(e){var t=new FileReader,n=tZ(t);return t.readAsArrayBuffer(e),n}function rZ(e){var t=new FileReader,n=tZ(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function iZ(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function aZ(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function oZ(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:KX.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:KX.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:KX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():KX.arrayBuffer&&KX.blob&&qX(e)?(this._bodyArrayBuffer=aZ(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):KX.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||YX(e))?this._bodyArrayBuffer=aZ(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):KX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},KX.blob&&(this.blob=function(){var e=eZ(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return eZ(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(KX.blob)return this.blob().then(nZ);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=eZ(this);if(e)return e;if(this._bodyBlob)return rZ(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(iZ(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},KX.formData&&(this.formData=function(){return this.text().then(uZ)}),this.json=function(){return this.text().then(JSON.parse)},this}var sZ=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function cZ(e){var t=e.toUpperCase();return sZ.indexOf(t)>-1?t:e}function lZ(e,t){if(!(this instanceof lZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof lZ){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new $X(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new $X(t.headers)),this.method=cZ(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in GX)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}lZ.prototype.clone=function(){return new lZ(this,{body:this._bodyInit})};function uZ(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function dZ(e){var t=new $X;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
214
214
|
`)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}oZ.call(lZ.prototype);function fZ(e,t){if(!(this instanceof fZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||={},this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw RangeError(`Failed to construct 'Response': The status provided (0) is outside the range [200, 599].`);this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?``:``+t.statusText,this.headers=new $X(t.headers),this.url=t.url||``,this._initBody(e)}oZ.call(fZ.prototype),fZ.prototype.clone=function(){return new fZ(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new $X(this.headers),url:this.url})},fZ.error=function(){var e=new fZ(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var pZ=[301,302,303,307,308];fZ.redirect=function(e,t){if(pZ.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new fZ(null,{status:t,headers:{location:e}})};var mZ=GX.DOMException;try{new mZ}catch{mZ=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},mZ.prototype=Object.create(Error.prototype),mZ.prototype.constructor=mZ}function hZ(e,t){return new Promise(function(n,r){var i=new lZ(e,t);if(i.signal&&i.signal.aborted)return r(new mZ(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:dZ(a.getAllResponseHeaders()||``)};i.url.indexOf(`file://`)===0&&(a.status<200||a.status>599)?e.status=200:e.status=a.status,e.url=`responseURL`in a?a.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in a?a.response:a.responseText;setTimeout(function(){n(new fZ(t,e))},0)},a.onerror=function(){setTimeout(function(){r(TypeError(`Network request failed`))},0)},a.ontimeout=function(){setTimeout(function(){r(TypeError(`Network request timed out`))},0)},a.onabort=function(){setTimeout(function(){r(new mZ(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&GX.location.href?GX.location.href:e}catch{return e}}if(a.open(i.method,s(i.url),!0),i.credentials===`include`?a.withCredentials=!0:i.credentials===`omit`&&(a.withCredentials=!1),`responseType`in a&&(KX.blob?a.responseType=`blob`:KX.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof $X||GX.Headers&&t.headers instanceof GX.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(XX(e)),a.setRequestHeader(e,ZX(t.headers[e]))}),i.headers.forEach(function(e,t){c.indexOf(t)===-1&&a.setRequestHeader(t,e)})}else i.headers.forEach(function(e,t){a.setRequestHeader(t,e)});i.signal&&(i.signal.addEventListener(`abort`,o),a.onreadystatechange=function(){a.readyState===4&&i.signal.removeEventListener(`abort`,o)}),a.send(i._bodyInit===void 0?null:i._bodyInit)})}hZ.polyfill=!0,GX.fetch||(GX.fetch=hZ,GX.Headers=$X,GX.Request=lZ,GX.Response=fZ);var gZ=`11434`,_Z=`http://127.0.0.1:${gZ}`,vZ=`0.6.3`,yZ=Object.defineProperty,bZ=(e,t,n)=>t in e?yZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xZ=(e,t,n)=>(bZ(e,typeof t==`symbol`?t:t+``,n),n),SZ=class e extends Error{constructor(t,n){super(t),this.error=t,this.status_code=n,this.name=`ResponseError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},CZ=class{constructor(e,t,n){xZ(this,`abortController`),xZ(this,`itr`),xZ(this,`doneCallback`),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if(`error`in e)throw Error(e.error);if(yield e,e.done||e.status===`success`){this.doneCallback();return}}throw Error(`Did not receive done or success response in stream.`)}},wZ=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get(`content-type`)?.includes(`application/json`))try{n=await e.json(),t=n.error||t}catch{console.log(`Failed to parse error response as JSON`)}else try{console.log(`Getting text from response`),t=await e.text()||t}catch{console.log(`Failed to get text from error response`)}throw new SZ(t,e.status)};function TZ(){if(typeof window<`u`&&window.navigator){let e=navigator;return`userAgentData`in e&&e.userAgentData?.platform?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<`u`)return`${process.arch} ${process.platform} Node.js/${process.version}`;return``}function EZ(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}else if(Array.isArray(e))return Object.fromEntries(e);else return e||{}}var DZ=(e,t)=>e[t],OZ=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${vZ} (${TZ()})`};n.headers=EZ(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?DZ({},`OLLAMA_API_KEY`):void 0;!(n.headers.authorization||n.headers.Authorization)&&e&&(n.headers.Authorization=`Bearer ${e}`)}}catch(e){console.error(`error parsing url`,e)}let i=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...i},e(t,n)},kZ=async(e,t,n)=>{let r=await OZ(e,t,{headers:n?.headers});return await wZ(r),r},AZ=async(e,t,n,r)=>{let i=await OZ(e,t,{method:`POST`,body:(e=>typeof e==`object`&&!!e&&!Array.isArray(e))(n)?JSON.stringify(n):n,signal:r?.signal,headers:r?.headers});return await wZ(i),i},jZ=async(e,t,n,r)=>{let i=await OZ(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await wZ(i),i},MZ=async function*(e){let t=new TextDecoder(`utf-8`),n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0});let a=n.split(`
|
|
215
215
|
`);n=a.pop()??``;for(let e of a)try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}}n+=t.decode();for(let e of n.split(`
|
|
216
|
-
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},NZ=e=>{if(!e)return _Z;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:gZ;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},PZ=Object.defineProperty,FZ=(e,t,n)=>t in e?PZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,IZ=(e,t,n)=>(FZ(e,typeof t==`symbol`?t:t+``,n),n),LZ=class{constructor(e){IZ(this,`config`),IZ(this,`fetch`),IZ(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=NZ(e?.host??_Z)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await AZ(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new CZ(e,MZ(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await AZ(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await jZ(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await AZ(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await kZ(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await AZ(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await AZ(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await AZ(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await kZ(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await kZ(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await AZ(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await AZ(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new LZ;var RZ=class extends Sw{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.6`),this.baseUrl=n.baseUrl??pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new LZ({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>ak(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>ak(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?pl(r,i.message):i.message;let i=new qt({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=WX(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Zl({text:o,message:RX(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Zl({text:``,message:new Xt({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Vv(i);Nm(i)||ev(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:Nm(i)||ev(i)?o:i}}),r=GC(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=WC(i);let e=Vv(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},zZ=e=>r.includes(e),BZ=e=>n.includes(e),VZ=e=>{let{executeQuery:t,search:r,grep:i,readFile:a}=e;return[FO(async({query:e,limit:t,groupByProcess:n})=>{let i=t??10,a=n??!0,o;try{o=await r(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
216
|
+
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},NZ=e=>{if(!e)return _Z;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:gZ;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},PZ=Object.defineProperty,FZ=(e,t,n)=>t in e?PZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,IZ=(e,t,n)=>(FZ(e,typeof t==`symbol`?t:t+``,n),n),LZ=class{constructor(e){IZ(this,`config`),IZ(this,`fetch`),IZ(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=NZ(e?.host??_Z)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await AZ(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new CZ(e,MZ(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await AZ(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await jZ(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await AZ(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await kZ(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await AZ(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await AZ(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await AZ(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await kZ(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await kZ(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await AZ(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await AZ(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new LZ;var RZ=class extends Sw{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.6`),this.baseUrl=n.baseUrl??pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new LZ({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>ak(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>ak(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?pl(r,i.message):i.message;let i=new qt({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=WX(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Zl({text:o,message:RX(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Zl({text:``,message:new Xt({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Vv(i);Nm(i)||ev(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:Nm(i)||ev(i)?o:i}}),r=GC(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=WC(i);let e=Vv(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},zZ=e=>n.includes(e),BZ=e=>r.includes(e),VZ=e=>{let{executeQuery:t,search:n,grep:i,readFile:a}=e;return[FO(async({query:e,limit:t,groupByProcess:r})=>{let i=t??10,a=r??!0,o;try{o=await n(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
217
217
|
|
|
218
218
|
`)}`;let l=new Map,u=`__no_process__`;for(let e of s){if(e.processes.length===0){l.has(u)||l.set(u,{label:`No process`,entries:[]}),l.get(u).entries.push({result:e});continue}for(let t of e.processes)l.has(t.id)||l.set(t.id,{label:t.label,stepCount:t.stepCount,entries:[]}),l.get(t.id).entries.push({result:e,step:t.step,stepCount:t.stepCount})}let d=Array.from(l.entries()).sort((e,t)=>{let n=e[1].entries.length;return t[1].entries.length-n}),f=[];f.push(`Found ${o.length} matches grouped by process:`),f.push(``);for(let[e,t]of d){let n=t.stepCount?`, ${t.stepCount} steps`:``,r=e===u?`NO PROCESS (${t.entries.length} matches)`:`PROCESS: ${t.label} (${t.entries.length} matches${n})`;f.push(r),t.entries.forEach(n=>{let r=n.step?{id:e,label:t.label,step:n.step,stepCount:n.stepCount}:void 0;f.push(c(n.result,r))}),f.push(``)}return f.join(`
|
|
219
|
-
`).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:t_({query:Xg().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:Qg().optional().nullable().describe(`Group results by process (default: true)`),limit:Zg().optional().nullable().describe(`Max results to return (default: 10)`)})}),FO(async({query:e,cypher:
|
|
220
|
-
`);return`Semantic search for "${e}" (${t.length} results):\n\n${
|
|
219
|
+
`).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:t_({query:Xg().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:Qg().optional().nullable().describe(`Group results by process (default: true)`),limit:Zg().optional().nullable().describe(`Max results to return (default: 10)`)})}),FO(async({query:e,cypher:r})=>{try{if(r.includes(`{{QUERY_VECTOR}}`)){if(!e)return`Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.`;try{let t=await n(e,{limit:10,mode:`semantic`});if(t.length===0)return`Semantic search returned no results. Embeddings may not be generated yet.`;let r=t.map((e,t)=>`[${t+1}] ${e.label||`File`}: ${e.name||e.filePath?.split(`/`).pop()||`?`} (score: ${(e.score??0).toFixed(3)})\n File: ${e.filePath||`n/a`}`).join(`
|
|
220
|
+
`);return`Semantic search for "${e}" (${t.length} results):\n\n${r}`}catch{return`Semantic search not available. Embeddings may not be generated. Use a non-vector Cypher query instead.`}}let i=await t(r);if(i.length===0)return`Query returned no results.`;let a=i[0],o=typeof a==`object`&&!Array.isArray(a)?Object.keys(a):[];if(o.length>0){let e=`| ${o.join(` | `)} |`,t=`|${o.map(()=>`---`).join(`|`)}|`,n=i.slice(0,50).map(e=>`| ${o.map(t=>{let n=e[t];if(n==null)return``;if(typeof n==`object`)return JSON.stringify(n);let r=String(n).replace(/\\/g,`\\\\`).replace(/\|/g,`\\|`);return r.length>60?r.slice(0,57)+`...`:r}).join(` | `)} |`).join(`
|
|
221
221
|
`),r=i.length>50?`\n\n_(${i.length-50} more rows)_`:``;return`**${i.length} results:**\n\n${e}\n${t}\n${n}${r}`}let s=i.slice(0,50).map((e,t)=>`[${t+1}] ${JSON.stringify(e)}`),c=i.length>50?`\n... (${i.length-50} more)`:``;return`${i.length} results:\n${s.join(`
|
|
222
222
|
`)}${c}`}catch(e){return`Cypher error: ${e instanceof Error?e.message:String(e)}\n\nCheck your query syntax. Node tables: File, Folder, Function, Class, Interface, Method, CodeElement. Relation: CodeRelation with type property (CONTAINS, DEFINES, IMPORTS, CALLS). Example: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f, g`}},{name:`cypher`,description:`Execute a Cypher query against the code graph. Use for structural queries like finding callers, tracing imports, class inheritance, or custom traversals.
|
|
223
223
|
|
|
@@ -318,7 +318,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
318
318
|
collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
|
|
319
319
|
LIMIT 1
|
|
320
320
|
`,[d,f,p]=await Promise.all([t(o),t(l),t(u)]),m=d.length>0?c(d[0],0,`label`):`Unclustered`,h=d.length>0?c(d[0],1,`description`):``,g=f.map(e=>`- ${c(e,0,`label`)} (step ${c(e,1,`step`)}/${c(e,2,`stepCount`)??`?`})`),_=`None`;if(p.length>0){let e=p[0],t=Array.isArray(e)?e[0]:e.outgoing||[],n=Array.isArray(e)?e[1]:e.incoming||[],r=(t||[]).filter(e=>e&&e.name).slice(0,5),i=(n||[]).filter(e=>e&&e.name).slice(0,5),a=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},o=r.map(e=>a(e,`out`)),s=i.map(e=>a(e,`in`));(o.length||s.length)&&(_=[...o,...s].join(`, `))}return[`SYMBOL: ${a} ${r}`,`ID: ${n}`,`File: ${i||`n/a`}`,`Cluster: ${m}${h?` — ${h}`:``}`,``,`PROCESSES:`,...g.length>0?g:[`- None found`],``,`CONNECTIONS:`,_].join(`
|
|
321
|
-
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:t_({target:Xg().describe(`Name or ID of a symbol, cluster, or process`),type:n_([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),FO(async({target:e,direction:
|
|
321
|
+
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:t_({target:Xg().describe(`Name or ID of a symbol, cluster, or process`),type:n_([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),FO(async({target:e,direction:n,maxDepth:o,relationTypes:s,includeTests:c,minConfidence:l})=>{let u=Math.min(o??3,10),d=c??!1,f=l??.7,p=e=>{if(!e)return!1;let t=e.toLowerCase();return t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__mocks__`)||t.endsWith(`.test.ts`)||t.endsWith(`.test.tsx`)||t.endsWith(`.spec.ts`)||t.endsWith(`.spec.tsx`)},m=s&&s.length>0?s.filter(e=>BZ(e)):[`CALLS`,`IMPORTS`,`EXTENDS`,`IMPLEMENTS`];if(m.length===0)return`No valid relation types provided. Valid types: ${r.join(`, `)}`;let h=m.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),g=e.includes(`/`),_=e.replace(/'/g,`''`),v=g?`
|
|
322
322
|
MATCH (n)
|
|
323
323
|
WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${_}'
|
|
324
324
|
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
@@ -330,7 +330,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
330
330
|
LIMIT 10
|
|
331
331
|
`,y;try{y=await t(v)}catch(t){return`Error finding target "${e}": ${t}`}if(!y||y.length===0)return`Could not find "${e}" in the codebase. Try using the search tool first to find the exact name.`;let b=y.map(e=>Array.isArray(e)?e[2]:e.filePath).filter(Boolean);if(y.length>1&&!e.includes(`/`))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${e}" found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
332
332
|
`)}\n\nPlease specify which file you mean by using a more specific path, e.g.:\n- impact("${b[0].split(`/`).slice(-3).join(`/`)}")\n- impact("${b[1]?.split(`/`).slice(-3).join(`/`)||b[0]}")`;let ee=y[0];if(e.includes(`/`)&&y.length>1){let t=y.find(t=>{let n=Array.isArray(t)?t[2]:t.filePath;return n&&n.toLowerCase().includes(e.toLowerCase())});if(t)ee=t;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${e}". Found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
333
|
-
`)}\n\nPlease use a more specific path.`}let x=Array.isArray(ee)?ee[0]:ee.id,te=Array.isArray(ee)?ee[1]:ee.nodeType,S=Array.isArray(ee)?ee[2]:ee.filePath,ne=te===`File`,re=[],ie=
|
|
333
|
+
`)}\n\nPlease use a more specific path.`}let x=Array.isArray(ee)?ee[0]:ee.id,te=Array.isArray(ee)?ee[1]:ee.nodeType,S=Array.isArray(ee)?ee[2]:ee.filePath,ne=te===`File`,re=[],ie=n===`upstream`?ne?`
|
|
334
334
|
MATCH (affected)-[r:CodeRelation]->(callee)
|
|
335
335
|
WHERE callee.filePath = '${(S||e).replace(/'/g,`''`)}'
|
|
336
336
|
AND r.type IN [${h}]
|
|
@@ -396,7 +396,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
396
396
|
r.confidence AS confidence,
|
|
397
397
|
r.reason AS reason
|
|
398
398
|
LIMIT 300
|
|
399
|
-
`;if(re.push(t(ie).then(e=>e).catch(e=>[])),u>=2){let e=
|
|
399
|
+
`;if(re.push(t(ie).then(e=>e).catch(e=>[])),u>=2){let e=n===`upstream`?`
|
|
400
400
|
MATCH (target {id: '${x.replace(/'/g,`''`)}'})
|
|
401
401
|
MATCH (a)-[r1:CodeRelation]->(target)
|
|
402
402
|
MATCH (affected)-[r2:CodeRelation]->(a)
|
|
@@ -434,7 +434,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
434
434
|
r2.confidence AS confidence,
|
|
435
435
|
r2.reason AS reason
|
|
436
436
|
LIMIT 200
|
|
437
|
-
`;re.push(t(e).catch(e=>[]))}if(u>=3){let e=
|
|
437
|
+
`;re.push(t(e).catch(e=>[]))}if(u>=3){let e=n===`upstream`?`
|
|
438
438
|
MATCH (target {id: '${x.replace(/'/g,`''`)}'})
|
|
439
439
|
MATCH (a)-[r1:CodeRelation]->(target)
|
|
440
440
|
MATCH (b)-[r2:CodeRelation]->(a)
|
|
@@ -476,8 +476,8 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
476
476
|
r3.confidence AS confidence,
|
|
477
477
|
r3.reason AS reason
|
|
478
478
|
LIMIT 100
|
|
479
|
-
`;re.push(t(e).catch(e=>[]))}let ae=await Promise.all(re),oe=new Map,se=[],ce=new Set;ae.forEach((e,t)=>{let n=t+1;e.forEach(e=>{let t=Array.isArray(e)?e[0]:e.id,r=Array.isArray(e)?e[3]:e.filePath;if(!(!d&&p(r))&&t&&!ce.has(t)){ce.add(t),oe.has(n)||oe.set(n,[]);let i={id:t,name:Array.isArray(e)?e[1]:e.name,nodeType:Array.isArray(e)?e[2]:e.nodeType,filePath:r,startLine:Array.isArray(e)?e[4]:e.startLine,edgeType:Array.isArray(e)?e[5]:e.edgeType||`CALLS`,confidence:Array.isArray(e)?e[6]:e.confidence??1,reason:Array.isArray(e)?e[7]:e.reason||``};oe.get(n).push(i),se.push(t)}})});let C=se.length;if(C===0){if(ne){let t=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),
|
|
480
|
-
`);return`No ${
|
|
479
|
+
`;re.push(t(e).catch(e=>[]))}let ae=await Promise.all(re),oe=new Map,se=[],ce=new Set;ae.forEach((e,t)=>{let n=t+1;e.forEach(e=>{let t=Array.isArray(e)?e[0]:e.id,r=Array.isArray(e)?e[3]:e.filePath;if(!(!d&&p(r))&&t&&!ce.has(t)){ce.add(t),oe.has(n)||oe.set(n,[]);let i={id:t,name:Array.isArray(e)?e[1]:e.name,nodeType:Array.isArray(e)?e[2]:e.nodeType,filePath:r,startLine:Array.isArray(e)?e[4]:e.startLine,edgeType:Array.isArray(e)?e[5]:e.edgeType||`CALLS`,confidence:Array.isArray(e)?e[6]:e.confidence??1,reason:Array.isArray(e)?e[7]:e.reason||``};oe.get(n).push(i),se.push(t)}})});let C=se.length;if(C===0){if(ne){let t=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=((S||e).split(`/`).pop()||e).replace(/\.[^/.]+$/,``);try{let a=(await i(`\\b${t(r)}\\b`,15)).filter(e=>e.filePath!==S);if(a.length>0){let t=a.map(e=>`${e.filePath}:${e.line}: ${e.text}`).join(`
|
|
480
|
+
`);return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}), but textual references were detected (graph may be incomplete):\n\n${t}`}}catch{}}return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}). This code appears to be ${n===`upstream`?`unused (not called by anything)`:`self-contained (no outgoing dependencies)`}.`}let le=oe.get(1)||[],ue=oe.get(2)||[],de=oe.get(3)||[],fe={high:0,medium:0,low:0};for(let e of oe.values())for(let t of e){let e=t.confidence??1;e>=.9?fe.high+=1:e>=.8?fe.medium+=1:fe.low+=1}let pe=se.slice(0,500),me=pe.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),he=[],ge=[];if(pe.length>0){let e=`
|
|
481
481
|
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
482
482
|
WHERE s.id IN [${me}]
|
|
483
483
|
RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
|
|
@@ -493,8 +493,8 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:t_({cypher:Xg().describe(`T
|
|
|
493
493
|
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
494
494
|
WHERE s.id IN [${r}]
|
|
495
495
|
RETURN DISTINCT c.label AS label
|
|
496
|
-
`:``,[a,o,s]=await Promise.all([t(e),t(n),i?t(i):Promise.resolve([])]),c=new Set;s.forEach(e=>{let t=Array.isArray(e)?e[0]:e.label;t&&c.add(t)}),he=a.map(e=>({label:Array.isArray(e)?e[0]:e.label,hits:Array.isArray(e)?e[1]:e.hits,minStep:Array.isArray(e)?e[2]:e.minStep,stepCount:Array.isArray(e)?e[3]:e.stepCount})),ge=o.map(e=>{let t=Array.isArray(e)?e[0]:e.label;return{label:t,hits:Array.isArray(e)?e[1]:e.hits,impact:c.has(t)?`direct`:`indirect`}})}let _e=le.length,ve=he.length,ye=ge.length,be=`LOW`;_e>=30||ve>=5||ye>=5||C>=200?be=`CRITICAL`:_e>=15||ve>=3||ye>=3||C>=100?be=`HIGH`:(_e>=5||C>=30)&&(be=`MEDIUM`);let xe=[`🔴 IMPACT: ${e} | ${
|
|
497
|
-
`),n=e.startLine-1;if(n<0||n>=t.length)return null;let r=t[n].trim();return r.length>80&&(r=r.slice(0,77)+`...`),r}catch{return null}};if(le.length>0){let t=
|
|
496
|
+
`:``,[a,o,s]=await Promise.all([t(e),t(n),i?t(i):Promise.resolve([])]),c=new Set;s.forEach(e=>{let t=Array.isArray(e)?e[0]:e.label;t&&c.add(t)}),he=a.map(e=>({label:Array.isArray(e)?e[0]:e.label,hits:Array.isArray(e)?e[1]:e.hits,minStep:Array.isArray(e)?e[2]:e.minStep,stepCount:Array.isArray(e)?e[3]:e.stepCount})),ge=o.map(e=>{let t=Array.isArray(e)?e[0]:e.label;return{label:t,hits:Array.isArray(e)?e[1]:e.hits,impact:c.has(t)?`direct`:`indirect`}})}let _e=le.length,ve=he.length,ye=ge.length,be=`LOW`;_e>=30||ve>=5||ye>=5||C>=200?be=`CRITICAL`:_e>=15||ve>=3||ye>=3||C>=100?be=`HIGH`:(_e>=5||C>=30)&&(be=`MEDIUM`);let xe=[`🔴 IMPACT: ${e} | ${n} | ${C} affected`,`Confidence: High ${fe.high} | Medium ${fe.medium} | Low ${fe.low}`,``,`AFFECTED PROCESSES:`,...he.length>0?he.map(e=>`- ${e.label} - BROKEN at step ${e.minStep??`?`} (${e.hits} symbols, ${e.stepCount??`?`} steps)`):[`- None found`],``,`AFFECTED CLUSTERS:`,...ge.length>0?ge.map(e=>`- ${e.label} (${e.impact}, ${e.hits} symbols)`):[`- None found`],``,`RISK: ${be}`,`- Direct callers: ${_e}`,`- Processes affected: ${ve}`,`- Clusters affected: ${ye}`,``],Se=e=>{let t=e.filePath?.split(`/`).pop()||``,n=e.startLine?`${t}:${e.startLine}`:t,r=Math.round((e.confidence??1)*100),i=r<80?`[fuzzy]`:``;return` ${e.nodeType}|${e.name}|${n}|${e.edgeType}|${r}%${i}`},Ce=async e=>{if(!e.filePath||!e.startLine)return null;try{let t=(await a(e.filePath)).split(`
|
|
497
|
+
`),n=e.startLine-1;if(n<0||n>=t.length)return null;let r=t[n].trim();return r.length>80&&(r=r.slice(0,77)+`...`),r}catch{return null}};if(le.length>0){let t=n===`upstream`?`d=1 (Directly DEPEND ON ${e}):`:`d=1 (${e} USES these):`;xe.push(t);for(let e of le.slice(0,15)){xe.push(Se(e));let t=await Ce(e);t&&xe.push(` ↳ "${t}"`)}le.length>15&&xe.push(` ... +${le.length-15} more`),xe.push(``)}if(ue.length>0){let t=n===`upstream`?`d=2 (Indirectly DEPEND ON ${e}):`:`d=2 (${e} USES these indirectly):`;xe.push(t),ue.slice(0,15).forEach(e=>xe.push(Se(e))),ue.length>15&&xe.push(` ... +${ue.length-15} more`),xe.push(``)}return de.length>0&&(xe.push(`d=3 (Deep impact/dependency):`),de.slice(0,5).forEach(e=>xe.push(Se(e))),de.length>5&&xe.push(` ... +${de.length-5} more`),xe.push(``)),xe.push(`✅ GRAPH ANALYSIS COMPLETE (trusted)`),xe.push(`⚠️ Optional: grep("${e}") for dynamic patterns`),xe.push(``),xe.join(`
|
|
498
498
|
`)},{name:`impact`,description:`Analyze the impact of changing a function, class, or file.
|
|
499
499
|
|
|
500
500
|
Use when users ask:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-4R4BOZG6-mKhL59ul.js";import{t as e}from"./chunk-RERM46MO-DQNbXtfw.js";export{e as createArchitectureServices};
|