@maincode-ai/matilda-code 0.20.9 → 0.21.1
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/chunks/agent-NKMZBTFX.js +3 -0
- package/chunks/agent-headless-QALB2VKF.js +3 -0
- package/chunks/{anthropicContentGenerator-I3ANKUSE.js → anthropicContentGenerator-GW3P6NLQ.js} +11 -11
- package/chunks/chunk-ASBKKKEC.js +107 -0
- package/chunks/{chunk-2JIJ6PFL.js → chunk-BZMRSSEE.js} +1 -1
- package/chunks/{chunk-JFICDNCB.js → chunk-G6ZP2JXV.js} +1 -1
- package/chunks/{chunk-FIUFMVRX.js → chunk-PPBGETQF.js} +16 -16
- package/chunks/chunk-QLEJOI4X.js +25 -0
- package/chunks/{chunk-NPLAJOCA.js → chunk-UBLZ73EY.js} +20 -20
- package/chunks/{chunk-2D5W3WW7.js → chunk-UUTPLLCJ.js} +423 -422
- package/chunks/{computer-use-5NE6OER4.js → computer-use-D5SWPUWU.js} +1 -1
- package/chunks/contextCommand-Z577LUBV.js +3 -0
- package/chunks/{edit-PMMM4Z57.js → edit-PSPQYZEV.js} +1 -1
- package/chunks/{enter-worktree-KOLSAE3N.js → enter-worktree-HOQPTB4F.js} +1 -1
- package/chunks/{enterPlanMode-WIEHROJ4.js → enterPlanMode-4KND327M.js} +1 -1
- package/chunks/{exit-worktree-5GFNCQCU.js → exit-worktree-2EUDTVQD.js} +1 -1
- package/chunks/{exitPlanMode-4SD3GHP7.js → exitPlanMode-I5NUEMM2.js} +1 -1
- package/chunks/{geminiContentGenerator-GSNXCP36.js → geminiContentGenerator-KE5W2HAZ.js} +1 -1
- package/chunks/{glob-6NLJB2GI.js → glob-6LD5EXSG.js} +1 -1
- package/chunks/{grep-7TT7XXG2.js → grep-D7F7VOBQ.js} +1 -1
- package/chunks/matildaAgentContentGenerator-53Y6ZKNX.js +32 -0
- package/chunks/matildaContentGenerator-XH7XBFUB.js +8 -0
- package/chunks/{monitor-7Z2SKQOD.js → monitor-GH5LJV3O.js} +1 -1
- package/chunks/notebook-edit-VYMSF622.js +17 -0
- package/chunks/openaiContentGenerator-W7WJAAQ3.js +3 -0
- package/chunks/ripGrep-AZQNLER7.js +3 -0
- package/chunks/scheduler-2XZK4D6E.js +8 -0
- package/chunks/{serve-HI33OSTP.js → serve-VB2EI7T2.js} +1 -1
- package/chunks/shell-QLCMTFUQ.js +3 -0
- package/chunks/{skill-HOXYLSX3.js → skill-EGDTMPHB.js} +1 -1
- package/chunks/src-O4M6KMI4.js +3 -0
- package/chunks/{team-create-PWPR4OKM.js → team-create-DAPGTPYR.js} +1 -1
- package/chunks/{workflow-UMB2MXXJ.js → workflow-PI6BBTXZ.js} +2 -2
- package/chunks/write-file-4K4VALFS.js +15 -0
- package/cli.js +231 -231
- package/package.json +2 -2
- package/chunks/agent-MR6HBCNC.js +0 -3
- package/chunks/agent-headless-Y5AQHZHB.js +0 -3
- package/chunks/chunk-7VBRP4XQ.js +0 -18
- package/chunks/chunk-7VE3KGS4.js +0 -8
- package/chunks/chunk-OVZKSZIR.js +0 -101
- package/chunks/chunk-XYA3SFGC.js +0 -25
- package/chunks/contextCommand-TQW3E3L6.js +0 -3
- package/chunks/matildaAgentContentGenerator-BZXWJKJ6.js +0 -32
- package/chunks/matildaContentGenerator-BBG5MEI5.js +0 -8
- package/chunks/notebook-edit-ZWC6PWD3.js +0 -17
- package/chunks/openaiContentGenerator-JACPHIUG.js +0 -3
- package/chunks/ripGrep-3EJOL3QF.js +0 -3
- package/chunks/scheduler-6GFBYAJV.js +0 -8
- package/chunks/shell-6VEGUV5J.js +0 -3
- package/chunks/src-3M4GZHJB.js +0 -3
- package/chunks/write-file-REUJ4LGI.js +0 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.1"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|
package/chunks/agent-MR6HBCNC.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Af as b,Bf as c,Cf as d,Df as e,Ef as f,zf as a}from"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{f as AgentTool,b as TOOL_REGISTRY_REBUILT,e as createApprovalModeOverride,c as hasRebuiltToolRegistry,d as rebuildToolRegistryOnOverride,a as resolveSubagentApprovalMode};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{$e as b,_e as a,af as c}from"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{c as AgentHeadless,a as ContextState,b as templateString};
|
package/chunks/chunk-7VBRP4XQ.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Bb as C,Pa as ge,Ra as fe,a as c,ab as L,na as k}from"./chunk-CFBZKYFB.js";import{P as B,R as M,j as D}from"./chunk-QWBNNEV2.js";import{b as O,c as d,f as I,g as y,h as f,i as _,k as U,l as m,n as A}from"./chunk-FWDMPRKU.js";import{b as u}from"./chunk-GZPNIYVZ.js";import{f as Ee}from"./chunk-OWGSC52X.js";u();function Se(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function x(e){let t=e.candidates||0,r=e.thoughts||0;return r>t?t+r:Math.max(t,r)}function ye(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+x(e)):(e.prompt||0)+x(e)}function Ae(e){let t=Math.max(0,e.thoughtsTokens||0),r=x({candidates:e.outputTokens||0,thoughts:t}),n=Math.max(e.totalTokens||0,(e.inputTokens||0)+r);return{...e,outputTokens:r,thoughtsTokens:t,totalTokens:n}}u();u();A();fe();u();A();var H=Ee(ge(),1);import{createHash as Ce}from"node:crypto";var S="matilda.telemetry.traceparent",v="matilda.telemetry.tracestate",Re="matilda-code.daemon.request",F="matilda-code.daemon.bridge",be="matilda-code.daemon.error";function _e(e){return e instanceof Error?e.message:String(e)}function xe(e){return e instanceof Error?e.name||"Error":typeof e}var ve="0".repeat(32),he="0".repeat(16);function De(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(!(S in t)&&!(v in t))return{...t};let r={...t};return delete r[S],delete r[v],r}function Oe(e){return Ce("sha256").update(e).digest("hex").slice(0,16)}async function P(e,t,r,n={}){if(!C())return await r(void 0);let o=n.autoOkOnSuccess??!0;return await m.getTracer(c).startActiveSpan(e,{kind:I.INTERNAL,attributes:t},async s=>{try{let a=await r(s);return o&&s.setStatus({code:y.OK}),a}catch(a){throw $(s,a),a}finally{s.end()}})}async function Ie(e,t){return await P(Re,{"http.request.method":e.method,"http.route":e.route,"matilda-code.daemon.operation":"http_request",...e.workspaceHash?{"matilda-code.workspace.hash":e.workspaceHash}:{},...e.sessionId?{"session.id":e.sessionId}:{},...e.clientId?{"matilda-code.client_id":e.clientId}:{},...e.permissionRequestId?{"matilda-code.daemon.permission.request_id":e.permissionRequestId}:{}},t,{autoOkOnSuccess:!1})}async function q(e,t,r){return await P(F,{"matilda-code.daemon.operation":e,...t},async()=>await r())}function Me(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function ke(e,t){try{m.getSpan(f.active())?.setAttribute(e,t)}catch{}}function $(e,t,r={}){let n=e??m.getSpan(f.active());if(n)try{let o=L(_e(t));n.recordException(t instanceof Error?t:new Error(o)),n.setAttributes({"error.type":xe(t),"error.message":o,...r}),n.setStatus({code:y.ERROR,message:o})}catch{}}function Le(e,t={},r){if(C())try{H.logs.getLogger(c).emit({body:e,timestamp:new Date,attributes:{"event.name":r?.eventName??be,...t},...r?.severityNumber!=null?{severityNumber:r.severityNumber}:{}})}catch{}}function j(){return{context:f.active()}}async function W(e,t){let r=e&&typeof e=="object"&&"context"in e&&e.context?e.context:void 0;return r?await f.with(r,t):await t()}function V(e){let t=e._meta,r=De(t);try{let n=B();n&&(r[S]=M(n))}catch{}return!t&&!r[S]?e:{...e,_meta:r}}function Pe(e){let t=e?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t,n=r[S];if(typeof n!="string"||n.length===0)return;let o={traceparent:n},i=r[v];typeof i=="string"&&i.length>0&&(o.tracestate=i);let s=U.extract(O,o);if(m.getSpanContext(s))return s;let a=n.split("-"),p=a[1],l=a[2],b=a[3];if(!(a[0]!=="00"||!p?.match(/^[0-9a-f]{32}$/)||!l?.match(/^[0-9a-f]{16}$/)||!b?.match(/^[0-9a-f]{2}$/)||p===ve||l===he))return m.setSpan(O,m.wrapSpanContext({traceId:p,spanId:l,traceFlags:Number.parseInt(b,16),isRemote:!0}))}function Ne(){return{captureContext:j,runWithContext:W,withSpan:q,event(e,t){if(C())try{let r=m.getSpan(f.active());if(r){r.addEvent(e,t);return}let n=m.getTracer(c).startSpan(F,{kind:I.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});n.addEvent(e,t),n.setStatus({code:y.OK}),n.end()}catch{}},injectPromptContext:V}}u();A();var we=`${c}.daemon.http.request.count`,Ue=`${c}.daemon.http.request.duration`,Be=`${c}.daemon.session.active`,He=`${c}.daemon.session.lifecycle`,Fe=`${c}.daemon.channel.lifecycle`,qe=`${c}.daemon.prompt.queue_wait`,$e=`${c}.daemon.prompt.duration`,je=`${c}.daemon.bridge.error.count`,We=`${c}.daemon.cancel.count`,Ve=`${c}.daemon.sse.active`,Ye=`${c}.daemon.process.heap_used`,Ge=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),T=!1,G,K,z,Q,X,J,Z,ee;function Ke(e){let t=e instanceof Error?e.name:typeof e;return Ge.has(t)?t:"unknown"}function ze(){if(T)return;let e=k();e&&(G=e.createCounter(we,{description:"Daemon HTTP request count by route and status class.",valueType:d.INT}),K=e.createHistogram(Ue,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:d.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),z=e.createCounter(He,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:d.INT}),Q=e.createCounter(Fe,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:d.INT}),X=e.createHistogram(qe,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:d.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),J=e.createHistogram($e,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:d.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),Z=e.createCounter(je,{description:"Daemon bridge error count by normalized error type.",valueType:d.INT}),ee=e.createCounter(We,{description:"Daemon cancel request count.",valueType:d.INT}),T=!0)}var Y=!1;function Qe(e){if(Y)return;let t=k();t&&(t.createObservableGauge(Be,{description:"Current number of active daemon sessions.",valueType:d.INT}).addCallback(r=>{try{r.observe(e.sessionCount())}catch{}}),t.createObservableGauge(Ve,{description:"Current number of active SSE connections.",valueType:d.INT}).addCallback(r=>{try{r.observe(e.sseCount())}catch{}}),t.createObservableGauge(Ye,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:d.INT}).addCallback(r=>{try{r.observe(e.heapUsed())}catch{}}),Y=!0)}function Xe(e,t,r){if(!T)return;let n=`${Math.floor(r/100)}xx`;G?.add(1,{route:t,status_class:n}),K?.record(e,{route:t})}function Je(e){T&&z?.add(1,{action:e})}function Ze(e,t){T&&Q?.add(1,{action:e,...t!=null?{expected:t}:{}})}function et(e){T&&X?.record(e)}function tt(e){T&&J?.record(e)}function rt(e){T&&Z?.add(1,{error_type:Ke(e)})}function nt(){T&&ee?.add(1)}u();A();var ot=3e3,it=64,st=64,at=100,ct=1e3;function ut(e){return`${new URL(e).origin}/api/client-events`}function dt(e){let t={eventType:e.eventType,platform:"cli",clientTimestamp:e.clientTimestamp??new Date().toISOString()};return e.traceId&&(t.traceId=e.traceId.slice(0,it)),e.supportRef&&(t.supportRef=e.supportRef.slice(0,st)),typeof e.status=="number"&&(t.status=e.status),e.errorClass&&(t.errorClass=e.errorClass.slice(0,at)),e.rawError&&(t.rawError=e.rawError.slice(0,ct)),e.appVersion&&(t.appVersion=e.appVersion),e.sessionId&&(t.sessionId=e.sessionId),t}async function pt(e,t){let{baseUrl:r,token:n}=t;if(!r||!n)return;let o=t.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),t.timeoutMs??ot);try{let a=await o(ut(r),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify(dt(e)),signal:i.signal});a.ok||_.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`)}catch{}finally{clearTimeout(s)}}var re=(r=>(r.GCP="gcp",r.LOCAL="local",r))(re||{}),Xn="local",Jn="http://localhost:4317";u();A();var mt=new Set(["service.version","service.instance.id","session.id"]);function E(e,t){_.warn(e),t?.push(e)}function ne(e,t){if(!e)return{};let r={};for(let n of e.split(",")){let o=n.trim();if(!o)continue;let i=o.indexOf("=");if(i<0){E(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${o}" (hint: percent-encode literal commas as %2C)`,t);continue}let s=o.slice(0,i).trim();if(!s)continue;let a=o.slice(i+1).trim(),p;try{p=decodeURIComponent(s)}catch{E(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),p=s}let l;try{l=decodeURIComponent(a)}catch{E(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${p}", using raw value`,t),l=a}r[p]=l}return r}function N(e,t,r){for(let n of mt)n in e&&(E(`${t} cannot override reserved key "${n}"; ignoring`,r),delete e[n]);return e}function oe(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))return E("settings.telemetry.resourceAttributes must be an object; ignoring",t),{};let r={};for(let[n,o]of Object.entries(e)){let i=n.trim();if(!i){E("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",t);continue}typeof o=="string"?r[i]=o:E(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof o}); ignoring`,t)}return r}function R(e){if(e!==void 0)return e==="true"||e==="1"}function te(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function lt(e){let t=e.argv??{},r=e.env??{},n=e.settings??{},o=t.telemetry??R(r.MATILDA_TELEMETRY_ENABLED)??n.enabled,i=t.telemetryTarget??r.MATILDA_TELEMETRY_TARGET??n.target,s=te(i);if(i!==void 0&&s===void 0)throw new D(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=t.telemetryOtlpEndpoint??r.MATILDA_TELEMETRY_OTLP_ENDPOINT??r.OTEL_EXPORTER_OTLP_ENDPOINT??n.otlpEndpoint,p=t.telemetryOtlpProtocol??r.MATILDA_TELEMETRY_OTLP_PROTOCOL??n.otlpProtocol,l=["grpc","http"].find(Te=>Te===p);if(p!==void 0&&l===void 0)throw new D(`Invalid telemetry OTLP protocol: ${String(p)}. Valid values are: grpc, http`);let b=t.telemetryLogPrompts??R(r.MATILDA_TELEMETRY_LOG_PROMPTS)??n.logPrompts,ie=R(r.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??n.includeSensitiveSpanAttributes??!1,se=t.telemetryOutfile??r.MATILDA_TELEMETRY_OUTFILE??n.outfile,ae=r.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??r.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??n.otlpTracesEndpoint,ce=r.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??r.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??n.otlpLogsEndpoint,ue=r.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??r.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??n.otlpMetricsEndpoint,g=[],de=N(ne(r.OTEL_RESOURCE_ATTRIBUTES,g),"OTEL_RESOURCE_ATTRIBUTES",g),pe=N(oe(n.resourceAttributes,g),"settings.telemetry.resourceAttributes",g),h={...de,...pe},w=r.OTEL_SERVICE_NAME?.trim();w&&(h["service.name"]=w);let le=Object.keys(h).length?h:void 0,me=R(r.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??n.metrics?.includeSessionId??!1;return{enabled:o,target:s,otlpEndpoint:a,otlpProtocol:l,otlpTracesEndpoint:ae,otlpLogsEndpoint:ce,otlpMetricsEndpoint:ue,logPrompts:b,includeSensitiveSpanAttributes:ie,outfile:se,resourceAttributes:le,metrics:{includeSessionId:me},resourceAttributeWarnings:g.length?g:void 0}}export{Se as a,x as b,ye as c,Ae as d,R as e,te as f,lt as g,S as h,v as i,Oe as j,P as k,Ie as l,q as m,Me as n,ke as o,$ as p,Le as q,j as r,W as s,V as t,Pe as u,Ne as v,ze as w,Qe as x,Xe as y,Je as z,Ze as A,et as B,tt as C,rt as D,nt as E,pt as F,re as G,Xn as H,Jn as I};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
|
9
|
-
/**
|
|
10
|
-
* @license
|
|
11
|
-
* Copyright 2026 Matilda
|
|
12
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
13
|
-
*/
|
|
14
|
-
/**
|
|
15
|
-
* @license
|
|
16
|
-
* Copyright 2025 Google LLC
|
|
17
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
18
|
-
*/
|
package/chunks/chunk-7VE3KGS4.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{s as a}from"./chunk-XYA3SFGC.js";import{d as s}from"./chunk-XJDC3ZQZ.js";import{b as d}from"./chunk-GZPNIYVZ.js";d();var E=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],f=new Set([...E,...s]),c=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",u="(?:0|[1-9]\\d{0,4})",l="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",m=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${u}$`),new RegExp(`^${o}-maincode\\.${l}(?:\\.${u})?$`)],R=41;function _(e){return e==="desktop"?"desktop":e===void 0||c.has(e)?"code_cli":"unknown"}function g(e){return e==="desktop"||e===void 0||c.has(e)||e==="VSCode"?"matilda-client":"unknown"}function S(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function T(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>R||!m.some(n=>n.test(t))))return t}function x(e,t=process.platform){let n=e.getChannel?.(),r=_(n),p=g(n),i=T(e.getCliVersion?.());return{"x-matilda-reported-surface":r,"x-matilda-reported-os":S(t),"x-matilda-reported-process":r==="desktop"?"matilda-desktop":n==="VSCode"?"matilda-vscode":r==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":p,...i?{"x-matilda-reported-version":i}:{}}}function N(e){return f.has(e.toLowerCase())}function A(e){let t=e??a;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function k(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&A(e.baseUrl)}export{x as a,N as b,k as c};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-OVZKSZIR.js
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as L,d as Ct}from"./chunk-4F4DA5UI.js";import{a as Tt,b as Fe,c as At,d as Mt}from"./chunk-DC7LAFZZ.js";import{a as Y}from"./chunk-7VBRP4XQ.js";import{a as ft,b as ht,e as Ke,n as yt,q as J,r as St}from"./chunk-XYA3SFGC.js";import{b as A,e as K}from"./chunk-4J6DC24J.js";import{a as mt}from"./chunk-XJDC3ZQZ.js";import{Jc as ut,Kc as pt,Mb as lt,Mc as gt,Pb as dt,Rb as ct,Sa as F,Wa as Ue,Xa as De,Ya as Ge,eb as Ne,f as P,fb as $,tb as de,ub as ce}from"./chunk-CFBZKYFB.js";import{b as vt}from"./chunk-3YLXGE6T.js";import{L as st,Y as b,c as at,d as B,e as W}from"./chunk-QWBNNEV2.js";import{h as x,l as Le,n as sn}from"./chunk-FWDMPRKU.js";import{b as h}from"./chunk-GZPNIYVZ.js";h();h();var j=b("TAGGED_THINKING_PARSER"),X=["<think>","<thinking>"],Z=["</think>","</thinking>"],ln=Math.max(...X.map(t=>t.length),...Z.map(t=>t.length));function q(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function ue(t,e,n){let o=t.length-e;return o<=0||o>ln?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function pe(t,e,n){return n.find(o=>t.startsWith(o,e))}function je(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e=e.replace(/[ \t]{2,}/g," "),e=e.replace(/^\s+/,""),e}function _t(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=je(n.text);o&&e.push({text:o})}return e}var $e=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){if(this.mode==="text"){let s=pe(o,a,X);if(s){j.debug(`taggedThinking: detected open tag "${s}" at offset ${a}`),q(i,r,this.mode),r="",this.mode="thought",a+=s.length;continue}let l=pe(o,a,Z);if(l){j.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${a}`),q(i,r,this.mode),r="",a+=l.length;continue}if(!n&&(ue(o,a,X)||ue(o,a,Z)))break}else{let s=pe(o,a,Z);if(s){j.debug(`taggedThinking: detected close tag "${s}" at offset ${a}`),q(i,r,this.mode),r="",this.mode="text",a+=s.length;continue}let l=pe(o,a,X);if(l){a+=l.length;continue}if(!n&&(ue(o,a,Z)||ue(o,a,X)))break}r+=this.buffer[a],a+=1}return a<this.buffer.length?(q(i,r,this.mode),this.buffer=this.buffer.slice(a),j.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),_t(i)):(this.buffer="",this.mode==="thought"&&r&&j.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),q(i,r,this.mode),j.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),_t(i))}};function It(t){return new $e().parse(t,!0)}var w=b("CONVERTER"),Et="(attached media from previous tool call)";function Ot(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,i=t.total_tokens||0,r=t.prompt_tokens_details,a=r?.cached_tokens??r?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,s=t.completion_tokens_details,l=s?.reasoning_tokens??s?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),i>n&&(n>0||o>0||p>0)&&(d=Math.max(d,i-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let m=t.usage_is_incomplete===!0||o>0&&n===0||i>0&&n===0&&o===0,f=n,g=i;return(g===0&&(f>0||d>0)||g>0&&f>0&&g<f+d)&&(g=f+d),{promptTokenCount:f,candidatesTokenCount:d,totalTokenCount:g,cachedContentTokenCount:a,thoughtsTokenCount:p,...m?{usageIsIncomplete:!0}:{}}}var dn=64,bt=1024;function kt(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,i=n>=bt&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=dn?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<bt&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function Lt(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function cn(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=Lt(r.parameters)),a&&(a=ht(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function un(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return gn(t,o),fn(t.contents,o,e),o=Pt(o),n.cleanOrphanToolCalls&&(o=vn(o),o=Pt(o)),o}function pn(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let g of o)typeof g=="string"?r.push(g):"text"in g&&g.text?"thought"in g&&g.thought?i.push(g.text):r.push(g.text):"functionCall"in g&&g.functionCall&&(a.push({id:g.functionCall.id||`call_${s}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},c=i.join("");c&&(l.reasoning_content=c),a.length>0&&(l.tool_calls=a);let u=Sn(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),f=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:f,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function gn(t,e){if(!t.config?.systemInstruction)return;let n=Dt(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function fn(t,e,n){if(Array.isArray(t))for(let o of t)xt(o,e,n);else t&&xt(t,e,n)}function xt(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!yn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){r.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&i==="assistant"&&d.text&&a.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&r.push({type:"text",text:d.text});let m=Ut(d,n);if(m&&i==="user"&&r.push(m),"functionCall"in d&&d.functionCall&&i==="assistant"){let f=d.functionCall.id;if(f){if(c.has(f)){w.debug(`Dropping duplicate functionCall id=${f} while converting content`);continue}c.add(f)}s.push({id:f||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&i==="user"){let f=d.functionResponse.id;if(f){if(u.has(f))continue;u.add(f)}let g=mn(d.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],y=[];for(let T of g.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
|
|
4
|
-
`);g.content=T||"[media attached in following user message]",p.push(...C)}}e.push(g)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:Et},...p]}),i==="assistant"){if(r.length===0&&s.length===0&&a.length===0)return;let m={role:"assistant",content:r.filter(g=>g.type==="text").map(g=>g.text).join("")||(a.length>0?"":null)};s.length>0&&(m.tool_calls=s);let f=a.join("");f&&(m.reasoning_content=f),e.push(m);return}r.length>0&&e.push({role:"user",content:r})}function hn(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function mn(t,e){let n=hn(t.response),o=[];n&&o.push({type:"text",text:n});for(let i of t.parts||[]){if("text"in i&&typeof i.text=="string"){i.text.length>0&&o.push({type:"text",text:i.text});continue}let r=Ut(i,e);r&&o.push(r)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function Ut(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,i=wt(o),r=t.inlineData.displayName||o;if(i==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("image",r,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:U("pdf",r,e);if(i==="audio"){if(!n.audio)return U("audio",r,e);let a=Cn(o);if(a)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:a}}}return i==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("video",r,e):{type:"text",text:`Unsupported inline media type: ${o} (${r}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",i=t.fileData.fileUri,r=t.fileData.mimeType,a=wt(r);if(a==="image")return n.image?{type:"image_url",image_url:{url:i}}:U("image",o,e);if(r==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:i}}:U("pdf",o,e);if(a==="video")return n.video?{type:"video_url",video_url:{url:i}}:U("video",o,e);let s=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${r}${s}.`}}return null}function U(t,e,n){w.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
|
|
5
|
-
/extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function wt(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Cn(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function yn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Dt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Dt(e)).filter(Boolean).join(`
|
|
6
|
-
`):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
7
|
-
`)||""}function He(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return It(t);if(!t)return[];let o=je(t);return o?[{text:o}]:[]}function Tn(t,e){let n=t.choices?.[0],o=new K;if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let r=n.message.reasoning_content??n.message.reasoning;r&&i.push({text:r,thought:!0})}if(n.message.content&&i.push(...He(n.message.content,e)),n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a={};r.function.arguments&&(a=ft(r.function.arguments,{})),i.push({functionCall:{id:r.id,name:r.function.name,args:a}})}}o.candidates=[{content:{parts:i,role:"model"},finishReason:Gt(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage){let i=t.choices?.[0]?.message,r=i?.reasoning_content??i?.reasoning??"",a=typeof i?.content=="string"?i.content:"";o.usageMetadata=Ot(t.usage,{estimatedReasoningTokens:Y(r.length),estimatedContentTokens:Y(a.length)})}return o}function An(t,e){let n=t.choices?.[0],o=new K,i=e.toolCallParser;if(!i)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let c=n.delta?.reasoning_content??n.delta?.reasoning;if(c){let u=kt(c,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});u&&r.push({text:u,thought:!0})}}if(typeof n.delta?.content=="string"){let c=kt(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&r.push(...He(c,e,!!n.finish_reason))}else n.finish_reason&&r.push(...He("",e,!0));if(n.delta?.tool_calls)for(let c of n.delta.tool_calls){let u=c.index??0;c.function?.arguments?i.addChunk(u,c.function.arguments,c.id,c.function.name):i.addChunk(u,"",c.id,c.function?.name)}let a=!1;if(n.finish_reason){a=i.hasIncompleteToolCalls();let c=i.getCompletedToolCalls();for(let u of c)u.name&&r.push({functionCall:{id:u.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:u.name,args:u.args}})}let s=a&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:r,role:"model"},index:0,safetyRatings:[]};s&&(l.finishReason=Gt(s)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=Ot(t.usage,Mn(e))),o}function Mn(t){return{estimatedReasoningTokens:Y(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Y(t.textDeltaState?.emittedLength??0)}}function Gt(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function Sn(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function ze(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function Rt(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===Et}function vn(t){let e=[],n=new Map,o=new Map,i=new Map,r=new Set,a=new Set;for(let s=0;s<t.length;s+=1){let l=t[s];if(ze(l)){let c=[],u=new Set;for(let C of l.tool_calls){let y=C.id;!y||a.has(y)||u.has(y)||(u.add(y),c.push(C))}let p=new Set,d=[],m=[],f=!1;for(let C=s+1;C<t.length;C+=1){let y=t[C];if(y.role==="tool"&&"tool_call_id"in y){if(!y.tool_call_id){f=!1;continue}u.has(y.tool_call_id)&&!p.has(y.tool_call_id)?(p.add(y.tool_call_id),d.push(C),f=!0):f=!1;continue}if(Rt(y)){f&&m.push(C);continue}if(!(y.role==="assistant"&&!ze(y)))break}let g=c.filter(C=>p.has(C.id));for(let C of g)a.add(C.id);n.set(s,g),o.set(s,d),i.set(s,m)}}for(let s=0;s<t.length;s+=1){if(r.has(s))continue;let l=t[s];if(ze(l)){let c=l.reasoning_content,u=n.get(s)??[];if(u.length>0){let p={...l};p.tool_calls=u,e.push(p);for(let d of o.get(s)??[]){let m=t[d];m&&(e.push(m),r.add(d))}for(let d of i.get(s)??[]){let m=t[d];m&&(e.push(m),r.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||c){let p={...l};delete p.tool_calls,e.push(p)}else w.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?w.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):Rt(l)?w.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function Pt(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let i="tool_calls"in o?o.tool_calls||[]:[],r="tool_calls"in n?n.tool_calls||[]:[],a=o.content,s=n.content,l=Array.isArray(a)||Array.isArray(s),c;if(l){let p=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[],d=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[];c=[...p,...d]}else c=[typeof a=="string"?a:"",typeof s=="string"?s:""].filter(Boolean).join("")||null;let u=[...i,...r];o.content=c||null,u.length>0&&(o.tool_calls=u);continue}}e.push(n)}return e}var ge={convertGeminiToolParametersToOpenAI:Lt,convertGeminiToolsToOpenAI:cn,convertGeminiRequestToOpenAI:un,convertGeminiResponseToOpenAI:pn,convertOpenAIResponseToGemini:Tn,convertOpenAIChunkToGemini:An};h();import*as _ from"node:path";import{promises as me}from"node:fs";h();h();import _n from"crypto";var he=new Uint8Array(256),fe=he.length;function Ve(){return fe>he.length-16&&(_n.randomFillSync(he),fe=0),he.slice(fe,fe+=16)}h();var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function Nt(t,e=0){return M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]}h();h();import In from"crypto";var Be={randomUUID:In.randomUUID};function bn(t,e,n){if(Be.randomUUID&&!e&&!t)return Be.randomUUID();t=t||{};let o=t.random||(t.rng||Ve)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return Nt(o)}var We=bn;import*as E from"os";var Ce=b("OPENAI_LOGGER"),kn="########",xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function wn(t,e){let n=e||process.cwd();if(!t)return _.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=_.join(E.homedir(),t.slice(1)):_.isAbsolute(t)||(o=_.resolve(n,t)),_.normalize(o)}function Kt(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function Rn(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function Pn(t){if(t)return F(t)?Kt(t):Kt(Rn(t))}function En(t){if(!t)return;let e=t.indexOf(kn);if(e>0)return t.slice(0,e);if(xn.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function On(t){let e=t?.trim(),n=En(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var Q=class{logDir;initialized=!1;constructor(e,n){this.logDir=wn(e,n)}async initialize(){if(!this.initialized)try{await me.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw Ce.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,i){this.initialized||await this.initialize();let r=new Date().toISOString().replace(/:/g,"-"),a=We().slice(0,8),s=Pn(i),l=s?`openai-${r}-${a}-${s}.json`:`openai-${r}-${a}.json`,c=_.join(this.logDir,l),u={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:On(i),system:{hostname:E.hostname(),platform:E.platform(),release:E.release(),nodeVersion:process.version}};try{return await me.writeFile(c,JSON.stringify(u,null,2),"utf-8"),c}catch(p){throw Ce.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await me.readdir(this.logDir)).filter(i=>i.startsWith("openai-")&&i.endsWith(".json")).map(i=>_.join(this.logDir,i)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(Ce.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await me.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw Ce.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},ni=new Q;h();var ye="$runtime|";function ri(t){let e=t;for(;e.startsWith(ye);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}h();var Te=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Ft=["model","apiKey","apiKeyEnvKey","baseUrl"],Ae=[...Ft,...Te],di={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},ci={openai:Ct,"matilda-oauth":L},Me=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],ui=Me.map(t=>t.id);h();h();h();h();sn();h();import{AsyncLocalStorage as Ln}from"node:async_hooks";var $t=new Ln;h();function jt(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Un)}function Un(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function zt(){let t=mt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var D=b("LOGGING_CONTENT_GENERATOR"),Dn=4096,Ht="...[truncated]",Gn=Dn-Ht.length,ee=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new Q(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let i=JSON.stringify(e);lt(this.config,new ut(n,o,i,P.getStore()))}_logApiResponse(e,n,o,i,r,a){ct(this.config,new gt(e,o,n,i,this.generatorAuthType,r,a,P.getStore()))}_logApiError(e,n,o,i,r){let a=at(o),s=W(o),l=o?.requestID||o?.request_id||e,c=B(o);dt(this.config,new pt({responseId:l,model:i,durationMs:n,promptId:r,authType:this.generatorAuthType,errorMessage:a,errorType:s,statusCode:c,subagentName:P.getStore()}))}safelyLogApiError(e,n,o,i,r){try{this._logApiError(e,n,o,i,r)}catch(a){D.warn("Failed to log API error:",a)}}safelyLogApiResponse(e,n,o,i,r,a){try{this._logApiResponse(e,n,o,i,r,a)}catch(s){D.warn("Failed to log API response:",s)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=zt(),i=Ne(e.model,n);try{i.setAttribute("llm_request.stream",!1)}catch{}let r=Le.setSpan(x.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession();try{Ke.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),s||(Ue(this.config,i,e.config?.systemInstruction),De(this.config,i,e.config?.tools));let c=await x.with(r,async()=>{s||this.logApiRequest(this.toContents(e.contents),e.model,n);let u=await l.wrap(()=>this.wrapped.generateContent(e,n)),p=Date.now()-a,d=s?void 0:this.extractResponseText(u);s||Ge(this.config,i,d),this.safelyLogApiResponse(u.responseId??"",p,this.getClientVisibleModelId(e.model,u.modelVersion),n,u.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),u,void 0,n)}catch(m){D.warn("Failed to log OpenAI interaction:",m)}return u});return $(i,{success:!0,inputTokens:c.usageMetadata?.promptTokenCount,outputTokens:c.usageMetadata?.candidatesTokenCount,cachedInputTokens:c.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-a,responseId:c.responseId||void 0,finishReason:c.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:c.usageMetadata?.thoughtsTokenCount,subagentName:P.getStore()||void 0,...o}),c}catch(c){let u=Date.now()-a,p=e.config?.abortSignal?.aborted??!1;throw $(i,{success:!1,durationMs:u,error:p?ce:de,errorType:W(c),errorStatusCode:B(c),subagentName:P.getStore()||void 0,...o}),await x.with(r,async()=>{this.safelyLogApiError("",u,c,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,c,n)}catch(d){D.warn("Failed to log OpenAI interaction:",d)}}),c}}async generateContentStream(e,n){let o=zt(),i=Ne(e.model,n);try{i.setAttribute("llm_request.stream",!0)}catch{}let r=Le.setSpan(x.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession(),c;try{Ke.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),s||(Ue(this.config,i,e.config?.systemInstruction),De(this.config,i,e.config?.tools)),c=await x.with(r,async()=>(s||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(p){let d=Date.now()-a;x.with(r,()=>this.safelyLogApiError("",d,p,e.model,n));let m=e.config?.abortSignal?.aborted??!1;$(i,{success:!1,durationMs:d,error:m?ce:de,errorType:W(p),errorStatusCode:B(p),subagentName:P.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,p,n)}catch(f){D.warn("Failed to log OpenAI interaction:",f)}throw p}let u;if(this.openaiLogger)try{u=await l.resolve(e)}catch(p){D.warn("Failed to resolve OpenAI request:",p)}return x.with(r,()=>this.loggingStreamWrapper(c,a,n,e.model,u,i,r,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():$t.run(i=>{e=i},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,i,r,a,s,l,c){let u=F(o),p=!u||!!this.openaiLogger,d=[],m="",f="",g,C=!1,y,T,S=P.getStore(),R,V=!1,se=v=>s?x.with(s,v):v(),an=5*6e4,k,ot=a?()=>{V||(k!==void 0&&clearTimeout(k),k=setTimeout(()=>{try{a.setAttribute("stream.timed_out",!0)}catch{}$(a,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:S||void 0,...c}),V=!0},an),k.unref())}:void 0;ot?.();try{for await(let I of e){!m&&I.responseId&&(m=I.responseId),!f&&I.modelVersion&&(f=I.modelVersion),p&&d.push(I),I.usageMetadata&&(g=I.usageMetadata);let rt=I.candidates?.[0];rt?.finishReason&&(y=rt.finishReason),R===void 0&&jt(I)&&(R=Date.now()-n),ot?.(),yield I}k!==void 0&&(clearTimeout(k),k=void 0);let v=Date.now()-n,le=p?this.consolidateGeminiResponsesForLogging(d):void 0,it=u?void 0:this.extractResponseText(le);V||(se(()=>this.safelyLogApiResponse(m,v,this.getClientVisibleModelId(i,f),o,g,it)),!u&&a&&Ge(this.config,a,it),await se(()=>this.safelyLogOpenAIInteraction(r,le,void 0,o)))}catch(v){if(C=!0,T=v,!V){let le=Date.now()-n;se(()=>this.safelyLogApiError(m,le,v,this.getClientVisibleModelId(i,f),o)),await se(()=>this.safelyLogOpenAIInteraction(r,void 0,v,o))}throw v}finally{if(k!==void 0&&clearTimeout(k),a&&!V){let v=l?.aborted??!1;$(a,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:R,durationMs:Date.now()-n,error:C?v?ce:de:void 0,responseId:m||void 0,finishReason:y,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:S||void 0,errorType:T?W(T):void 0,errorStatusCode:T?B(T):void 0,...c})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ge.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),i={model:e.model,messages:o};return e.config?.tools&&(i.tools=await ge.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(i.temperature=e.config.temperature),e.config?.topP!==void 0&&(i.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(i.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(i.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(i.frequency_penalty=e.config.frequencyPenalty),i}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,i){if(!this.openaiLogger||!e)return;let r=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,r,o instanceof Error?o:o?new Error(String(o)):void 0,i)}async safelyLogOpenAIInteraction(e,n,o,i){try{await this.logOpenAIInteraction(e,n,o,i)}catch(r){D.warn("Failed to log OpenAI interaction:",r)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new K;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),ge.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new K,o=[],i=new Map,r,a;for(let c of e){c.usageMetadata&&(a=c.usageMetadata);let u=c.candidates?.[0];u?.finishReason&&(r=u.finishReason);let p=u?.content?.parts??[];for(let d of p){if(typeof d=="string"){o.push({text:d});continue}if("text"in d){d.text&&o.push({text:d.text,...d.thought?{thought:!0}:{},...d.thoughtSignature?{thoughtSignature:d.thoughtSignature}:{}});continue}if("functionCall"in d&&d.functionCall){let m=d.functionCall.id||d.functionCall.name||"tool_call",f=i.get(m),g={functionCall:d.functionCall};f!==void 0?o[f]=g:(i.set(m,o.length),o.push(g));continue}if("functionResponse"in d&&d.functionResponse){o.push({functionResponse:d.functionResponse});continue}o.push(d)}}let s=e[e.length-1],l=s.candidates?.[0];return n.responseId=s.responseId,n.createTime=s.createTime,n.modelVersion=s.modelVersion,n.promptFeedback=s.promptFeedback,n.usageMetadata=a,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...r?{finishReason:r}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",i=!1,r=!1,a=s=>{if(i=!0,r)return;let l=Gn-o.length;if(s.length<=l){o+=s;return}o+=s.slice(0,Math.max(0,l)),r=!0};for(let s of n){if(typeof s=="string"){a(s);continue}"text"in s&&typeof s.text=="string"&&!("thought"in s&&s.thought)&&a(s.text)}if(i)return r?`${o}${Ht}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let r=o.text,a=r?String(r):"",s=a?`${a}
|
|
8
|
-
${n}`:n;return{...o,text:s}}return e}};h();function Vt(t){switch(t){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Bt(t){switch(t){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var O=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},Se=class extends O{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let i=e||"(unknown)",r=n||"(unknown)";super(`Missing credentials for modelProviders model '${r}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${i}[].envKey.`:`Configure modelProviders.${i}[].envKey and set that environment variable.`))}},ve=class extends O{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},_e=class extends O{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},Ie=class extends O{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},be=class extends O{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},ke=class extends O{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};h();import Kn from"node:process";h();var Wt={image:!0,pdf:!0,audio:!0,video:!0},Nn=[[/^gemini-3/,Wt],[/^gemini-/,Wt],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function te(t){let e=yt(t);for(let[n,o]of Nn)if(n.test(e))return{...o};return{}}h();var Yt=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new xe(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||L}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),o=new Set,i=[];for(let l of n)o.has(l)||(o.add(l),i.push(l));let r=[];i.includes("matilda-oauth")&&r.push("matilda-oauth");for(let l of i)l!=="matilda-oauth"&&r.push(l);let a=this.getRuntimeModelOption(),s=[];for(let l of r)a&&a.authType===l&&s.push(a),s.push(...this.modelRegistry.getModelsForAuthType(l));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===Fe&&e?.envKey===Tt&&e?.baseUrl===Mt&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?Fe:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?At:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===L){this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(i){throw this.rollbackToStateSnapshot(o),i}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=te(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=J(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let i=this.extractRuntimeModelSnapshotId(n);if(i){await this.switchToRuntimeModel(i);return}let r=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let a=e!==this.currentAuthType;this.currentAuthType=e;let s=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!s)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=r.generationConfig.model||"",c=!a&&l?this.modelRegistry.getModel(e,l,r.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,u=e!=="matilda-oauth"&&!a&&!!r.generationConfig.apiKey&&!!s.envKey&&c?.envKey===s.envKey&&c.baseUrl===s.baseUrl,p=u?r.generationConfig.apiKey:void 0,d=u?r.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0;let m=a?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,m)}catch(a){throw this.rollbackToStateSnapshot(r),a}}buildRuntimeModelSnapshotId(e,n){return`${ye}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(ye))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of Te)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:i}=this._generationConfig;if(!(!n||!e||!o||!i)&&!this.modelRegistry.hasModel(e,n,i))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let r=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);r.apiKey=o,r.baseUrl=i,r.modelId=n;let a=this.buildRuntimeModelSnapshotId(r.authType,r.modelId);a!==r.id&&(this.runtimeModelSnapshots.delete(r.id),r.id=a,this.runtimeModelSnapshots.set(a,r),this.activeRuntimeModelSnapshotId=a),r.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of Ae)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),e.envKey!==void 0){let o=Kn.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of Te)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=J(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=te(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),i=this.modelRegistry.getModel(n,e);return!i||!o||i.envKey!==o.envKey||i.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,r=n?this.modelRegistry.getModel(e,n,i)??this.modelRegistry.getModel(e,n):void 0;if(r){let m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==r.envKey||this._generationConfig.baseUrl!==r.baseUrl),f=o===e&&this._generationConfig.model===n&&!m,g=f?this._generationConfig.apiKey:void 0,C=f&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,y=this.generationConfigSources.baseUrl,T=f&&!!this._generationConfig.baseUrl&&(y?.kind==="cli"||y?.kind==="env"||y?.kind==="settings"),S=T?this._generationConfig.baseUrl:void 0,R=T&&y?{...y}:void 0;this.applyResolvedModelDefaults(r),f&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,s=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&s?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(e);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,...r}=this._generationConfig,a=this.currentAuthType;if(!e||!a)return;if(this.modelRegistry.hasModel(a,e,o)){this.clearRuntimeModelSnapshotForAuthType(a);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(a,e),c={id:l,authType:a,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,generationConfig:r,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,c),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let i=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let r=i;this.onModelChange&&await this.onModelChange(n.authType,r)}catch(i){throw this.rollbackToStateSnapshot(o),i}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};h();import{readFileSync as no}from"node:fs";import{join as oo}from"node:path";h();h();import{randomBytes as Fn,createHash as $n}from"node:crypto";function Jt(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Ye(){let t=Fn(32).toString("base64url"),e=$n("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function ne(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function Je(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Jt(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let i=await o.json();if(!i.issuer||!i.authorization_endpoint||!i.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:i.issuer,authorization_endpoint:i.authorization_endpoint,token_endpoint:i.token_endpoint,device_authorization_endpoint:i.device_authorization_endpoint}}h();import{promises as we,openSync as jn,closeSync as zn,unlinkSync as qt,statSync as Hn}from"node:fs";import{dirname as Vn}from"node:path";var Bn=1e4,Wn=3e4,Yn=50;function qe(t){let e=async()=>{try{let i=await we.readFile(t,"utf8"),r=JSON.parse(i);return r&&typeof r=="object"?r:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},n=async i=>{await we.mkdir(Vn(t),{recursive:!0}),await we.writeFile(t,JSON.stringify(i,null,2),{mode:384}),await we.chmod(t,384).catch(()=>{})};return{store:{async get(i){return(await e())[i]??null},async set(i,r){let a=await e();a[i]=r,await n(a)},async remove(i){let r=await e();i in r&&(delete r[i],await n(r))}},lock:Jn(`${t}.lock`)}}function Jn(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await qn(t);try{return await n()}finally{Xn(t)}});return e=o.then(()=>{},()=>{}),o}}async function qn(t){let e=Date.now()+Bn;for(;;)try{zn(jn(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Hn(t).mtimeMs>Wn){qt(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Zn(Yn)}}function Xn(t){try{qt(t)}catch{}}function Zn(t){return new Promise(e=>setTimeout(e,t))}h();var z=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Xe(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,i=null,r=async()=>{let l=await t.store.get(e);if(!l)return null;try{let c=JSON.parse(l);return c.accessToken?c:null}catch{return null}},a=l=>l.expiresAt-Date.now()>o,s=l=>t.lock(async()=>{let c=await r()??l;if(c.accessToken!==l.accessToken&&a(c))return c.accessToken;if(!c.refreshToken)throw new z("No refresh token available \u2014 sign in again.");let u=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:c.refreshToken})});if(!u.ok){let m=await u.text().catch(()=>"");throw u.status>=400&&u.status<500&&Qn(m)==="invalid_grant"?(await t.store.remove(e),new z):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),d=ne(p,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(l){let c=await r();if(!c)throw new z("Not signed in.");return!l?.forceRefresh&&a(c)?c.accessToken:(i||(i=s(c).finally(()=>{i=null})),i)}}}function Qn(t){try{return JSON.parse(t).error}catch{return}}h();import{createServer as eo}from"node:http";import{randomBytes as to}from"node:crypto";async function Ze(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=f=>t.onEvent?.(f),{codeVerifier:n,codeChallenge:o}=Ye(),i=to(16).toString("hex"),r=t.timeoutMs??5*60*1e3,a=t.transport.successRedirect;e({type:"state",status:"idle"});let s,l,c=new Promise((f,g)=>{s=f,l=g});c.catch(()=>{});let u=eo((f,g)=>{let C=new URL(f.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let y=C.searchParams.get("error"),T=C.searchParams.get("state"),S=C.searchParams.get("code");if(y){Xt(g,a,()=>l(new Error(`OAuth error: ${y}`)));return}if(T!==i){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){g.writeHead(400).end("Missing authorization code");return}Xt(g,a,()=>s(S))}),p=await new Promise((f,g)=>{u.once("error",g),u.listen(t.transport.port??0,"127.0.0.1",()=>{f(u.address().port)})}),d=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),r),m=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",m,{once:!0});try{let f=`http://127.0.0.1:${p}/callback`,g=new URL(t.metadata.authorization_endpoint);g.searchParams.set("client_id",t.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",f),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",i),g.searchParams.set("scope",t.scope??"openid offline_access");let C=g.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let y=await c;e({type:"state",status:"exchanging"});let T=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:y,code_verifier:n,redirect_uri:f})});if(!T.ok){let R=await T.text().catch(()=>"");throw new Error(`Token exchange failed (${T.status}): ${R}`)}let S=ne(await T.json());return e({type:"state",status:"authenticated"}),S}catch(f){throw e({type:"state",status:"error"}),f}finally{clearTimeout(d),t.signal?.removeEventListener("abort",m),u.close()}}function Xt(t,e,n){t.writeHead(302,{location:e}).end(n)}var Re="matilda-code",Zt="matilda-desktop",oe="MATILDA_API_KEY",io="openid profile email offline_access matilda:code",ro="matilda";function ie(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qt(){return oo(st.getGlobalMatildaDir(),"matilda-auth.json")}function Pe(){return qe(Qt())}function ao(t){return t==="desktop"}function re(t){return t?.clientId?t.clientId:ao(t?.channel)?Zt:Re}function H(t){return`matilda:${t}`}function Ee(t){return`${H(t)}:refresh-rejected`}function ae(t){return t===Re?[H(t),ro]:[H(t)]}function so(){try{let t=no(Qt(),"utf8");return JSON.parse(t)}catch{return{}}}function Qe(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function lo(t,e){return ie(t)===ie(e)}function co(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function uo(t,e){let n=co(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function en(t){try{return await Je(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function N(t){try{let e=so(),n=re(t);for(let o of ae(n)){let i=Qe(e[o]);if(i)return i}return null}catch{return null}}async function po(t){let e=re(t),n=Pe().store;for(let o of ae(e))await n.remove(o);await n.set(Ee(e),"1"),delete process.env[oe]}function go(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}async function fo(t,e){let n=re(e),o=Pe().store;await o.set(H(n),JSON.stringify(t)),await o.remove(Ee(n));for(let i of ae(n))i!==H(n)&&await o.remove(i);process.env[oe]=t.accessToken}async function ho(t){let e=re(t),n=Pe().store;for(let o of ae(e))await n.remove(o);await n.remove(Ee(e)),delete process.env[oe]}function Or(t){let e=N(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Lr(t){let e={channel:t?.channel,clientId:t?.clientId},n=N(e);if(n?.accessToken){let o=ie(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await ho(e)}async function et(t){let e=re(t),n=H(e),o=N({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!lo(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[oe]??"";let i=ie(o.baseUrl),r=await en(i),{store:a,lock:s}=Pe(),l=mo(a,s,r.token_endpoint,o.baseUrl,e,n,t?.signal),c;try{c=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(u){throw e===Zt&&go(u)&&await po({channel:t?.channel,clientId:e}),u}return process.env[oe]=c,c}async function Ur(t){await et(t);let e=N(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function mo(t,e,n,o,i,r,a){let s=ae(i);return Xe({tokenEndpoint:n,clientId:i,store:{get:async u=>{let p=u===r?s:[u],d=null;for(let f of p)if(d=Qe(await t.get(f)),d)break;if(!d?.accessToken)return null;let m={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresAt:d.accessTokenExpiresAt};return JSON.stringify(m)},set:async(u,p)=>{let d=JSON.parse(p),m=u===r?s:[u],f={};for(let C of m){let y=Qe(await t.get(C));if(y){f=y;break}}let g={...f,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??f.refreshToken??"",baseUrl:f.baseUrl??o};await t.set(r,JSON.stringify(g)),await t.remove(Ee(i));for(let C of s)C!==r&&await t.remove(C)},remove:async u=>{let p=u===r?s:[u];for(let d of p)await t.remove(d)}},storageKey:r,lock:e,fetchImpl:(u,p)=>fetch(u,{...p,signal:a}),expirySkewMs:3e5})}function Co(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&vt()}async function Dr(t){let e=ie(t.baseUrl),n=await en(e),o="",i=s=>Ze({metadata:n,clientId:Re,scope:s,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Re)}`},signal:t.signal,onEvent:l=>{l.type==="authorize_url"&&(o=l.url,t.onAuthorizeUrl?.(l.url))},openBrowser:async l=>{if(!(t.openBrowser===!1||!Co()))try{let{default:c}=await import("./open-QQ7FWG4A.js");(await c(l)).once("error",()=>{})}catch{}}}),r;try{r=await i(io)}catch(s){if(s instanceof Error&&s.message.includes("invalid_scope"))r=await i("openid offline_access");else throw s}let a=uo(r,t.baseUrl);return await fo(a),{...a,authorizeUrl:o}}var G=(r=>(r.USE_OPENAI="openai",r.MATILDA_OAUTH="matilda-oauth",r.USE_GEMINI="gemini",r.USE_VERTEX_AI="vertex-ai",r.USE_ANTHROPIC="anthropic",r))(G||{}),yo="MATILDA_AGENT_SDK",Oe="MATILDA_API_KEY";function To(t,e){if(t.apiKey||t.apiKeyEnvKey!==Oe)return;let n=N({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[Oe]=n.accessToken)}async function Ao(t,e){if(t.apiKeyEnvKey!==Oe)return;let n=N({channel:e});if(!n?.accessToken)return;let o=await et({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[Oe]=o)}function Mo(t){return t.matildaAgentSdk===!0||process.env[yo]==="1"}function tt(t,e,n){t[e]=n}function So(t,e){return t?.[e]}function vo(t,e,n,o,i){let r={...o||{}},a=i?.strictModelProvider===!0,s={...n||{},authType:e,proxy:t?.getProxy()};tt(r,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&tt(r,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>So(o,u)??{kind:"unknown"};for(let u of Ae)n&&u in n&&!r[u]&&tt(r,u,l(u));To(s,t.getChannel());let c=nn(s,a);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
|
|
9
|
-
`));return{config:s,sources:r}}function nn(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new Se(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Vt(t.authType);n.push(new _e({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new ve(t.authType));else{let o=Bt(t.authType);n.push(new Ie({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new be({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new ke)),{valid:n.length===0,errors:n}}function zr(t,e,n){return vo(t,e,n).config}function tn(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function Hr(t,e,n){await Ao(t,e.getChannel());let o=nn(t,!1);if(!o.valid)throw new Error(o.errors.map(a=>a.message).join(`
|
|
10
|
-
`));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(Mo(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-BZXWJKJ6.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-JACPHIUG.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-BBG5MEI5.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw tn(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-I3ANKUSE.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-GSNXCP36.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=tn(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
|
|
11
|
-
Please exit and restart Matilda to use the '${i}' provider.`,{cause:s}):a}return new ee(r,e,t)}var nt=b("MODEL_REGISTRY");function on(t){if(Object.values(G).includes(t))return t}function _o(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function rn(t,e){return e?`${t}\0${e}`:t}var xe=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return St;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",Me),e)for(let[n,o]of Object.entries(e)){let i=on(n);if(!i){nt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let i of n){let r=rn(i.id,i.baseUrl);if(o.has(r)){nt.warn(`Duplicate model id "${i.id}"${i.baseUrl?` with baseUrl "${i.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let a=this.resolveModelConfig(i,e);o.set(r,a)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??J(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let i=this.modelsByAuthType.get(e);if(!i)return;if(o)return i.get(rn(n,o));let r=i.get(n);if(r)return r;for(let a of i.values())if(a.id===n)return a}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,L);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||_o(e.id))&&(o.modalities=te(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let i=on(n);if(!i){nt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}};export{$e as a,Ot as b,ge as c,$t as d,wn as e,Q as f,ni as g,te as h,ye as i,ri as j,Te as k,di as l,ci as m,Me as n,ui as o,rn as p,xe as q,Yt as r,Qt as s,N as t,fo as u,ho as v,Or as w,Lr as x,et as y,Ur as z,Co as A,Dr as B,G as C,vo as D,nn as E,zr as F,Hr as G};
|
|
12
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2025 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2025 Google LLC
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* @license
|
|
24
|
-
* Copyright 2025 Matilda Team
|
|
25
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
26
|
-
*/
|
|
27
|
-
/**
|
|
28
|
-
* @license
|
|
29
|
-
* Copyright 2026 Matilda Team
|
|
30
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
31
|
-
*/
|
|
32
|
-
/**
|
|
33
|
-
* @license
|
|
34
|
-
* Copyright 2026 Maincode
|
|
35
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
36
|
-
*
|
|
37
|
-
* Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
|
|
38
|
-
* (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
|
|
39
|
-
* grant, and refresh. Vendored (as source) from matilda-core's
|
|
40
|
-
* `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
|
|
41
|
-
* (display identity) that the higher-level flows need. Node built-ins only —
|
|
42
|
-
* no third-party runtime dependencies.
|
|
43
|
-
*/
|
|
44
|
-
/**
|
|
45
|
-
* @license
|
|
46
|
-
* Copyright 2026 Maincode
|
|
47
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
48
|
-
*
|
|
49
|
-
* File-backed token store + cross-process lock. The store persists a JSON map
|
|
50
|
-
* (`{ [key]: value }`) at 0600 so callers can key several credentials in one
|
|
51
|
-
* file; the lock is an O_EXCL lockfile that serialises refreshes across
|
|
52
|
-
* processes (the guarantee a plaintext read/modify/write can't give).
|
|
53
|
-
*/
|
|
54
|
-
/**
|
|
55
|
-
* @license
|
|
56
|
-
* Copyright 2026 Maincode
|
|
57
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
58
|
-
*
|
|
59
|
-
* Hardened access-token manager: returns a valid access token, refreshing via
|
|
60
|
-
* core-auth's token endpoint when expired or forced. Single-flight within the
|
|
61
|
-
* process, serialised across processes by the store's lock, carries a prior
|
|
62
|
-
* refresh token forward when the response omits one, and evicts on a terminal
|
|
63
|
-
* `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
|
|
64
|
-
*/
|
|
65
|
-
/**
|
|
66
|
-
* @license
|
|
67
|
-
* Copyright 2026 Maincode
|
|
68
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
69
|
-
*
|
|
70
|
-
* Browser login orchestration: PKCE + a loopback capture server, driven off
|
|
71
|
-
* discovery metadata. Unlike a bare loopback helper, this emits lifecycle
|
|
72
|
-
* events for a UI, honours an AbortSignal, and — instead of serving its own
|
|
73
|
-
* HTML — 302-redirects the browser to an app-owned branded landing
|
|
74
|
-
* (`successRedirect`). Returns a TokenSet including the `id_token`.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* @license
|
|
78
|
-
* Copyright 2026 Maincode
|
|
79
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
80
|
-
*
|
|
81
|
-
* Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
|
|
82
|
-
* Re-exports the OAuth primitives plus the higher-level login flow, file token
|
|
83
|
-
* store, and hardened token manager that the CLI (`packages/core`) and the
|
|
84
|
-
* Electron desktop app consume.
|
|
85
|
-
*/
|
|
86
|
-
/**
|
|
87
|
-
* @license
|
|
88
|
-
* Copyright 2026 Maincode
|
|
89
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
90
|
-
*
|
|
91
|
-
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
92
|
-
*
|
|
93
|
-
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
94
|
-
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
95
|
-
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
96
|
-
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
97
|
-
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
98
|
-
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
99
|
-
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
100
|
-
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
101
|
-
*/
|
package/chunks/chunk-XYA3SFGC.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Y as te}from"./chunk-QWBNNEV2.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();var Ee="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ee]==="1"}var M=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:f(xe(e)),contents:re(e.contents),systemInstructionBytes:Le(e.config?.systemInstruction),generationConfigBytes:f(se(e.config)),tools:Ue(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Oe(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Ne(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=f(n),s=this.getToolNameDiagnostics(e);s.uses+=1,s.argBytes+=o,s.maxArgBytes=Math.max(s.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=Ie();return this.tools.byName[e]=o,o}},je=new M;function Oe(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],s={};for(let a of n){let c=b(a),h=typeof c.role=="string"?c.role:"unknown";s[h]=(s[h]??0)+f(c.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:f(t),messageCount:n.length,messageBytesByRole:s,toolsCount:o.length,toolSchemaBytes:f(o),topLevelKeys:Object.keys(e).sort()}}function Ne(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],s={};for(let a of n){let c=b(a),h=typeof c.role=="string"?c.role:"unknown";s[h]=(s[h]??0)+f(c.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:f(t),messageCount:n.length,messageBytesByRole:s,systemBytes:f(e.system),toolsCount:o.length,toolSchemaBytes:f(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function Ie(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=f(o);continue}let s=b(o),a=typeof s.role=="string"?s.role:"unknown";e.roleCounts[a]=(e.roleCounts[a]??0)+1;let c=Array.isArray(s.parts)?s.parts:[];ve(c,e)}return e}function Le(t){return re(t).textBytes}function ve(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=f(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=f(o.text));let s=x(o.functionCall);s&&(e.functionCallCount+=1,e.functionCallArgBytes+=f(s.args));let a=x(o.functionResponse);a&&(e.functionResponseCount+=1,e.functionResponseBytes+=f(a.response)+f(a.parts));let c=x(o.inlineData);c&&(e.inlineDataCount+=1,e.inlineDataBytes+=f(c.data)),o.fileData&&(e.fileDataCount+=1)}}function Ue(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let s=b(o),a=Array.isArray(s.functionDeclarations)?s.functionDeclarations:[];n+=a.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:f(e)}}function xe(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,s]of Object.entries(e))o!=="abortSignal"&&(n[o]=s);return n}function f(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Me(t),"utf8")}function Me(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function x(t){return typeof t=="object"&&t!==null?t:null}p();var Xe=131072,He=32e3,Ye=8e3,Ze=64e3,et=2048;function tt(t,e,n,o=2048){let s=e-n-o;return!Number.isFinite(s)||s<=0?0:Math.min(t,s)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var We=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ae=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function qe(t,e="input"){let n=ie(t),o=e==="output"?ae:We;for(let[s,a]of o)if(s.test(n))return a}function nt(t){let e=ie(t);return ae.some(([n])=>n.test(e))}function Pe(t,e="input"){return qe(t,e)}function ot(t,e="input"){return Pe(t,e)??(e==="output"?32e3:131072)}p();p();p();p();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};p();function ue(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
|
|
4
|
-
+`.includes(t)}function W(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function q(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var P=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,$=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function F(t){return`,[]/{}
|
|
5
|
-
+`.includes(t)}function K(t){return E(t)||$e.test(t)}var $e=/^[[{\w-]$/;function le(t){return t===`
|
|
6
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function C(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function me(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function pe(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function E(t){return J(t)||L(t)}function J(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Q(t){return t==='"'}function L(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function z(t){return t==="'"}function B(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function g(t,e){let n=t.length;if(!C(t,n-1))return t+e;for(;C(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function fe(t,e,n){return t.substring(0,e)+t.substring(e+n)}function de(t){return/[,\n][ \t\r]*$/.test(t)}var Fe={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Ke={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
7
|
-
`,r:"\r",t:" "};function j(t){let e=0,n="";V(["```","[```","{```"]),a()||Se(),V(["```","```]","```}"]);let s=S(",");for(s&&c(),K(t[e])&&de(n)?(s||(n=g(n,",")),Ce()):s&&(n=B(n,","));t[e]==="}"||t[e]==="]";)e++,c();if(e>=t.length)return n;Be();function a(){c();let r=Re()||be()||T()||ke()||Ae()||H(!1)||Te();return c(),r}function c(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,u=e,l=h(r);do l=ge(),l&&(l=h(r));while(l);return e>u}function h(r){let u=r?C:me,l="";for(;;)if(u(t,e))l+=t[e],e++;else if(pe(t,e))l+=" ",e++;else break;return l.length>0?(n+=l,!0):!1}function ge(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Je(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
8
|
-
`;)e++;return!0}return!1}function V(r){if(he(r)){if(W(t[e]))for(;e<t.length&&q(t[e]);)e++;return c(),!0}return!1}function he(r){h(!0);for(let u of r){let l=e+u.length;if(t.slice(e,l)===u)return e=l,!0}return!1}function S(r){return t[e]===r?(n+=t[e],e++,!0):!1}function O(r){return t[e]===r?(e++,!0):!1}function ye(){return O("\\")}function G(){return c(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,c(),O(","),!0):!1}function Re(){if(t[e]==="{"){n+="{",e++,c(),O(",")&&c();let r=!0;for(;e<t.length&&t[e]!=="}";){let u;if(r?(u=!0,r=!1):(u=S(","),u||(n=g(n,",")),c()),G(),!(T()||H(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=B(n,","):De();break}c();let I=S(":"),A=e>=t.length;I||(K(t[e])||A?n=g(n,":"):Z()),a()||(I||A?n+="null":Z())}return t[e]==="}"?(n+="}",e++):n=g(n,"}"),!0}return!1}function be(){if(t[e]==="["){n+="[",e++,c(),O(",")&&c();let r=!0;for(;e<t.length&&t[e]!=="]";)if(r?r=!1:S(",")||(n=g(n,",")),G(),!a()){n=B(n,",");break}return t[e]==="]"?(n+="]",e++):n=g(n,"]"),!0}return!1}function Ce(){let r=!0,u=!0;for(;u;)r?r=!1:S(",")||(n=g(n,",")),u=a();u||(n=B(n,",")),n=`[
|
|
9
|
-
${n}
|
|
10
|
-
]`}function T(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,l=t[e]==="\\";if(l&&(e++,l=!0),E(t[e])){let I=Q(t[e])?Q:z(t[e])?z:L(t[e])?L:J,A=e,D=n.length,m='"';for(e++;;){if(e>=t.length){let d=Y(e-1);return!r&&_(t.charAt(d))?(e=A,n=n.substring(0,D),T(!0)):(m=g(m,'"'),n+=m,!0)}if(e===u)return m=g(m,'"'),n+=m,!0;if(I(t[e])){let d=e,U=m.length;if(m+='"',e++,n+=m,c(!1),r||e>=t.length||_(t[e])||E(t[e])||k(t[e]))return X(),!0;let R=Y(d-1),ee=t.charAt(R);if(ee===",")return e=A,n=n.substring(0,D),T(!1,R);if(_(ee))return e=A,n=n.substring(0,D),T(!0);n=n.substring(0,D),e=d+1,m=`${m.substring(0,U)}\\${m.substring(U)}`}else if(r&&F(t[e])){if(t[e-1]===":"&&P.test(t.substring(A+1,e+2)))for(;e<t.length&&$.test(t[e]);)m+=t[e],e++;return m=g(m,'"'),n+=m,X(),!0}else if(t[e]==="\\"){let d=t.charAt(e+1);if(Ke[d]!==void 0)m+=t.slice(e,e+2),e+=2;else if(d==="u"){let R=2;for(;R<6&&ue(t[e+R]);)R++;R===6?(m+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:_e()}else m+=d,e+=2}else{let d=t.charAt(e);d==='"'&&t[e-1]!=="\\"?(m+=`\\${d}`,e++):le(d)?(m+=Fe[d],e++):(ce(d)||we(d),m+=d,e++)}l&&ye()}}return!1}function X(){let r=!1;for(c();t[e]==="+";){r=!0,e++,c(),n=B(n,'"',!0);let u=n.length;T()?n=fe(n,u,1):n=g(n,'"')}return r}function ke(){let r=e;if(t[e]==="-"){if(e++,N())return v(r),!0;if(!k(t[e]))return e=r,!1}for(;k(t[e]);)e++;if(t[e]==="."){if(e++,N())return v(r),!0;if(!k(t[e]))return e=r,!1;for(;k(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,N())return v(r),!0;if(!k(t[e]))return e=r,!1;for(;k(t[e]);)e++}if(!N())return e=r,!1;if(e>r){let u=t.slice(r,e),l=/^0\d/.test(u);return n+=l?`"${u}"`:u,!0}return!1}function Ae(){return w("true","true")||w("false","false")||w("null","null")||w("True","true")||w("False","false")||w("None","null")}function w(r,u){return t.slice(e,e+r.length)===r?(n+=u,e+=r.length,!0):!1}function H(r){let u=e;if(W(t[e])){for(;e<t.length&&q(t[e]);)e++;let l=e;for(;C(t,l);)l++;if(t[l]==="(")return e=l+1,a(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!F(t[e])&&!E(t[e])&&(!r||t[e]!==":");)e++;if(t[e-1]===":"&&P.test(t.substring(u,e+2)))for(;e<t.length&&$.test(t[e]);)e++;if(e>u){for(;C(t,e-1)&&e>0;)e--;let l=t.slice(u,e);return n+=l==="undefined"?"null":JSON.stringify(l),t[e]==='"'&&e++,!0}}function Te(){if(t[e]==="/"){let r=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(r,e)}"`,!0}}function Y(r){let u=r;for(;u>0&&C(t,u);)u--;return u}function N(){return e>=t.length||_(t[e])||C(t,e)}function v(r){n+=`${t.slice(r,e)}0`}function we(r){throw new y(`Invalid character ${JSON.stringify(r)}`,e)}function Be(){throw new y(`Unexpected character ${JSON.stringify(t[e])}`,e)}function Se(){throw new y("Unexpected end of json string",t.length)}function De(){throw new y("Object key expected",e)}function Z(){throw new y("Colon expected",e)}function _e(){let r=t.slice(e,e+6);throw new y(`Invalid unicode character "${r}"`,e)}}function Je(t,e){return t[e]==="*"&&t[e+1]==="/"}var Qe=te("JSON_PARSE");function bt(t,e={}){if(!t||typeof t!="string")return e;try{return JSON.parse(t)}catch(n){try{let o=j(t);return JSON.parse(o)}catch(o){return Qe.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:o,jsonString:t}),e}}}p();function At(t,e="auto"){return e==="openapi_30"?ze(t):t}function ze(t){let e=n=>{if(typeof n!="object"||n===null)return n;if(Array.isArray(n))return n.map(e);let o=n,s={};if(Array.isArray(o.type)){let a=o.type;a.length===2&&a.includes("null")?(s.type=a.find(c=>c!=="null"),s.nullable=!0):s.type=a[0]}else o.type!==void 0&&(s.type=o.type);o.const!==void 0&&(s.enum=[o.const],delete s.const),typeof o.exclusiveMinimum=="number"&&(s.minimum=o.exclusiveMinimum,s.exclusiveMinimum=!0),typeof o.exclusiveMaximum=="number"&&(s.maximum=o.exclusiveMaximum,s.exclusiveMaximum=!0),Array.isArray(o.items)?delete s.items:typeof o.items=="object"&&o.items!==null&&(s.items=e(o.items)),Array.isArray(o.enum)&&(s.enum=o.enum.map(String));for(let[a,c]of Object.entries(o))a==="type"||a==="const"||a==="exclusiveMinimum"||a==="exclusiveMaximum"||a==="items"||a==="enum"||a==="$schema"||a==="$id"||a==="default"||a==="dependencies"||a==="patternProperties"||(s[a]=e(c));return s};return e(t)}p();var Bt="https://api.openai.com/v1",St="https://matilda.maincode.com/api/v1/code";var Dt=process.env.MATILDA_COMPAT_PROXY_BASE_URL;export{bt as a,At as b,ne as c,M as d,je as e,Oe as f,Ne as g,Xe as h,He as i,Ye as j,Ze as k,et as l,tt as m,ie as n,nt as o,Pe as p,ot as q,Bt as r,St as s,Dt as t};
|
|
11
|
-
/**
|
|
12
|
-
* @license
|
|
13
|
-
* Copyright 2026 Matilda
|
|
14
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
15
|
-
*/
|
|
16
|
-
/**
|
|
17
|
-
* @license
|
|
18
|
-
* Copyright 2025 Matilda
|
|
19
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
20
|
-
*/
|
|
21
|
-
/**
|
|
22
|
-
* @license
|
|
23
|
-
* Copyright 2025 Google LLC
|
|
24
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
25
|
-
*/
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{c as a,d as b,e as c}from"./chunk-JFICDNCB.js";import"./chunk-2JIJ6PFL.js";import"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as I,b as F,c as U}from"./chunk-7VE3KGS4.js";import{c as E,y as $}from"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import{b as m,e as P}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as x,n as O}from"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{p as b}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as w}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";w();w();var L="2026-06-23",W="auto",H="instant",J=12e4,h=18e4,V=5e4,v=16e3,X=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),B=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function K(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function T(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}function u(n,e){let o=T(n)?.[e];return typeof o=="string"?o:void 0}function j(n){return G(n)}function G(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
|
|
4
|
-
`):""}function g(n,e){if(n.length<=e)return n;let t=`
|
|
5
|
-
[...omitted to fit Matilda native agent context...]
|
|
6
|
-
`,o=e-t.length,s=Math.floor(o*.6),a=o-s;return`${n.slice(0,s)}${t}${n.slice(-a)}`}function z(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function Q(n){let e=T(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function Y(n){if(C(n)<=h)return n;let e=`
|
|
7
|
-
[...omitted to fit Matilda native request limit...]
|
|
8
|
-
`;for(let t=0;t<n.messages.length;t+=1){let o=n.messages[t];!o||o.content.length<=v||(n.messages[t]={...o,content:g(o.content,v)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,o=n.messages[t];if(!o||o.content.length<=1e3)break;let s=C(n)-h,a=Math.max(1e3,o.content.length-s-e.length-2e3);n.messages[t]={...o,content:g(o.content,a)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function Z(n){let e=T(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let o=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:o}}function q(n){let e=T(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let o=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${o}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let o=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${o?` with ${o}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),o=u(n.data,"message");return t&&o?`**Remote tool** ${t}: ${o}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),o=u(n.data,"status"),s=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${o??"completed"}${s?`: ${g(s,600)}`:""}`:void 0}}function S(n,e,t){let o=new P;return o.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],o.createTime=Date.now().toString(),o.modelVersion=e,t&&(o.usageMetadata=t),o}function ee(n,e){let t=new P;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function te(n,e){let t=new P;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function D(n,e,t){let o=S("",n,t);return o.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],o}async function*ne(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let o=new TextDecoder,s="",a="message",r=[],d=!1,c,i=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},f=()=>{if(r.length===0){a="message";return}let A={event:a,data:r.join(`
|
|
9
|
-
`)};return a="message",r=[],i(),A};i();try{for(;;){let{done:M,value:p}=await t.read();if(M||d)break;s+=o.decode(p,{stream:!0});let N=s.split(`
|
|
10
|
-
`);s=N.pop()??"";for(let k of N){let y=k.endsWith("\r")?k.slice(0,-1):k;if(y.length===0){let _=f();_&&(yield _)}else y.startsWith("event:")?a=y.slice(6).trim():y.startsWith("data:")&&r.push(y.slice(5).trimStart())}}if(s+=o.decode(),s.length>0)for(let M of s.split(`
|
|
11
|
-
`)){let p=M.endsWith("\r")?M.slice(0,-1):M;p.startsWith("event:")?a=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=f();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var R=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let o=await this.generateContentStream(e,t),s="",a,r=m.STOP,d=!1;for await(let i of o){s+=z(i),i.usageMetadata&&(a=i.usageMetadata);let l=i.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new Error("Matilda agent stream ended without an authoritative done signal.");let c=S(s,this.modelFor(e),a);return c.candidates=[{content:{parts:s?[{text:s}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),o=await this.fetchNativeChat(e),s=!1,a=!1,r,d,c=!1;for await(let i of ne(o,J))if(i.data!=="[DONE]"){if(i.event==="token"){let l=u(i.data,"content");l&&(a=!0,yield S(l,t))}else if(i.event==="thinking"||i.event==="generation_status"||i.event==="status"||i.event==="tool_start"||i.event==="tool_progress"||i.event==="tool_result"){let l=q(i);l&&(a=!0,yield ee(l,t))}else if(i.event==="client_tool_call"){let l=Z(i);l&&(a=!0,yield te(l,t))}else if(i.event==="usage")d=Q(i.data)??d;else if(i.event==="safety_replace"){let l=u(i.data,"message")??u(i.data,"content");l&&(a=!0,yield S(l,t))}else if(i.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(i.event==="done"){if(c=!0,r=u(i.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!a)throw new Error("Matilda agent returned an empty response.");yield D(t,r,d),s=!0}else if(i.event==="error"){let l=T(i.data),f=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${f}`)}}if(!s){if(!a)throw new Error("Matilda agent returned an empty response.");c&&(yield D(t,r??m.STOP,d))}}async fetchNativeChat(e){let t=await $({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),o=await this.postNativeChat(e,t);if(o.status!==401)return this.assertOkResponse(o);let s;try{s=await $({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw new b(r instanceof Error?r.message:String(r))}if(!s||s===t)throw new b("Matilda session expired. Please sign in again.");let a=await x("retry",()=>this.postNativeChat(e,s));return this.assertOkResponse(a)}async postNativeChat(e,t){return fetch(`${K(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=`Matilda agent request failed (${e.status}): ${await e.text()}`;throw e.status===401?new b(t):new Error(t)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":L,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[o,s]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))o.toLowerCase()!=="x-matilda-response-mode"&&!F(o)&&(t[o]=s);return U(this.contentGeneratorConfig,e)&&Object.assign(t,I(this.cliConfig),O()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),o=this.clientToolsFromRequest(e),s={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return o.length>0&&(s.clientTools=o),Y(s)}buildNativeMessages(e,t){let o=this.openAIMessagesFromRequest(e),a=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of o){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&a.push(c)}a.length===1&&a.push({role:"user",content:`${this.purposeLabel(t)}:
|
|
12
|
-
(empty prompt)`});let r=a[a.length-1];return r?.role!=="user"?a.push({role:"user",content:`${this.purposeLabel(t)}:
|
|
13
|
-
Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
|
|
14
|
-
`)||(a[a.length-1]={...r,content:`${this.purposeLabel(t)}:
|
|
15
|
-
${r.content}`}),a}buildSystemContext(e,t){let o=["Agent: Matilda Code",t==="code"?`Routing intent:
|
|
16
|
-
${X}`:void 0,`Instructions:
|
|
17
|
-
${this.instructionsFromRequest(e)}`].filter(s=>!!s);return g(o.join(`
|
|
18
|
-
|
|
19
|
-
`),V)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let o=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(o)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(o)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?H:e==="analysis"?"deep":W}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(o=>o.role==="system").map(o=>G(o.content)).filter(o=>o.trim().length>0);return[B,...t,this.localAgentContext()].join(`
|
|
20
|
-
|
|
21
|
-
`)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let o=this.cliConfig.getApprovalMode?.();o&&e.push(`- Approval mode: ${o}`);let s=this.cliConfig.getSandbox?.();e.push(s?`- Sandbox: ${s.command} (${s.image}).`:"- Sandbox: disabled.");let a=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,f]of a)f.length>0&&e.push(`- Permission ${l} rules: ${f.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let i=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return i.length>0&&e.push(`- Local tools available through the CLI loop: ${i.join(", ")}`),e.join(`
|
|
22
|
-
`)}clientToolsFromRequest(e){let t=[];for(let o of e.config?.tools??[])"functionDeclarations"in o&&t.push(...(o.functionDeclarations??[]).filter(s=>!!s.name));return t.map(o=>({name:o.name,...o.description?{description:o.description}:{},...o.parametersJsonSchema?{parameters:o.parametersJsonSchema}:o.parameters?{parameters:o.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>j(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return E.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
|
|
23
|
-
${g(j(e.content),v)}`;if(e.role==="assistant"){let t=G(e.content),o="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(s=>`Tool request: ${s.function.name}(${s.function.arguments})`).join(`
|
|
24
|
-
`):"";return`Assistant:
|
|
25
|
-
${g([t,o].filter(Boolean).join(`
|
|
26
|
-
`),v)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
|
|
27
|
-
${g(G(e.content),v)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};function fe(n,e){return new R(n,e)}export{R as MatildaAgentContentGenerator,fe as createMatildaAgentContentGenerator};
|
|
28
|
-
/**
|
|
29
|
-
* @license
|
|
30
|
-
* Copyright 2026 Matilda Team
|
|
31
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
32
|
-
*/
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as d,i as u}from"./chunk-FIUFMVRX.js";import"./chunk-QCIDUZV6.js";import"./chunk-7VE3KGS4.js";import"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import{d as s}from"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as o}from"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{c}from"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{Y as i}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var l=class extends u{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new d(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=c.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||s,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await o("retry",t);throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{l as MatildaContentGenerator};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Matilda
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as Z}from"./chunk-I55PXD4N.js";import{Kd as D,Ld as Y,Ob as Q,de as y,ja as R,oe as X}from"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import{J as B,K as k,L as U,Lb as z,M as K,N as q,O as b,P as W,Q as j,R as C,S as J,T as V,U as w,V as M,_c as H,ca as G}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as L,p as c,q as x}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{A as N,C as T,Y as F,z as _}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();import*as E from"node:fs";import*as m from"node:path";var ee=F("NOTEBOOK_EDIT");function g(d,r,t){return ee.debug("prior-read-rejected",{path:d,reason:r,type:t.type,displayMessage:t.displayMessage}),t}var u=class extends Error{constructor(t,e){super(t);this.type=e;this.name="NotebookEditError"}};function te(d,r){if(r==="delete")return"";if(typeof d!="string")throw new u(`new_source is required when edit_mode is "${r}".`,"invalid_tool_params");return d}function I(d,r){return d?q(d,r):`cell-${r}`}function oe(d,r,t){if(!r){if(t==="insert")return-1;throw new u("cell_id is required for replace and delete operations.","invalid_tool_params")}if(W(d,r))throw new u(`Cell ID "${r}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params");let e=j(d,r);if(e===-1)throw new u(`Cell with ID "${r}" not found in notebook.`,"notebook_cell_not_found");return e}function ie(d,r,t,e){let o={cell_type:r,metadata:{},source:w(t,e)},i=J(d);return i&&(o.id=i),M(o,r),o}function O(d,r){let t;try{t=k(d)}catch(a){throw new u(a instanceof Error?a.message:String(a),"notebook_invalid_json")}let e=r.edit_mode??"replace",o=te(r.new_source,e),i=b(t),n=oe(t,r.cell_id,e),l=C(t),p=U(d),s=(a,f)=>{let h=e==="insert"||e==="delete";return{...f,updatedContent:K(a,p),requiresReadAfterWrite:h&&!(i&&b(a))}};switch(e){case"insert":{let a=r.cell_type??"code",f=n===-1?0:n+1,h=ie(t,a,o,V(t,f));return t.cells.splice(f,0,h),s(t,{editedCellId:I(h,f),editedCellType:a,language:l,mode:e})}case"delete":{let[a]=t.cells.splice(n,1);return s(t,{editedCellId:I(a,n),editedCellType:a?.cell_type,language:l,mode:e})}case"replace":{let a=t.cells[n];if(!a)throw new u(`Cell index ${n} is out of range.`,"notebook_cell_not_found");let f=r.cell_type??a.cell_type;return a.source=w(o,Array.isArray(a.source)),M(a,f),s(t,{editedCellId:I(a,n),editedCellType:f,language:l,mode:e})}default:throw new u(`Unsupported notebook edit mode: ${e}`,"invalid_tool_params")}}function re(d,r,t){let e,o;try{e=k(r),o=k(d)}catch(i){throw new u(i instanceof Error?i.message:String(i),"notebook_invalid_json")}return{updatedContent:r,editedCellId:t.cell_id??"user-modified-notebook",editedCellType:void 0,language:C(e),mode:t.edit_mode??"replace",requiresReadAfterWrite:!b(o)||!b(e)}}async function A(d,r,t={}){if(d.getFileReadCacheDisabled())return{ok:!0};let e;try{e=await E.promises.stat(r)}catch(i){let n=i?.code;return n==="ENOENT"?t.expectExisting?g(r,"missing-after-read",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} disappeared after it was read. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${c.READ_FILE} first.`}):{ok:!0}:g(r,"stat-failed",{ok:!1,type:"prior_read_verification_failed",rawMessage:`Could not stat ${r} to verify prior notebook read (${n??"unknown error"}). Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${r}; re-run ${c.READ_FILE} before editing this notebook.`})}if(e.isDirectory())return g(r,"target-is-directory",{ok:!1,type:"target_is_directory",rawMessage:`${r} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."});if(!e.isFile())return g(r,"target-not-regular-file",{ok:!1,type:"target_not_regular_file",rawMessage:`${r} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."});let o=d.getFileReadCache().check(e);return o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadWasFull?{ok:!0}:o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadWasFull?g(r,"truncated-cache-entry",{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."}):o.state==="stale"?g(r,"stale-cache-entry",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} has been modified since you last read it. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${c.READ_FILE} first.`}):g(r,`cache-${o.state}`,{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} has not been fully read in this session. Use the ${c.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${c.READ_FILE} required before editing this notebook.`})}var P=class extends ${constructor(t,e,o){super(e);this.config=t;this.modifyMetadata=o}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){let t=N(this.params.notebook_path,this.config.getTargetDir()),e=this.params.edit_mode??"replace",o=this.params.cell_id??"beginning";return`${e} notebook cell ${o} in ${_(t)}`}async getDefaultPermission(){return"ask"}async getConfirmationDetails(t){let e=await this.prepareEdit(t),o=m.basename(this.params.notebook_path),i=R(o,e.originalContent,e.updatedContent,"Current","Proposed",D);return{type:"edit",title:`Confirm Notebook Edit: ${_(N(this.params.notebook_path,this.config.getTargetDir()))}`,fileName:o,filePath:this.params.notebook_path,fileDiff:i,originalContent:e.originalContent,newContent:e.updatedContent,onConfirm:async l=>{l==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async prepareEdit(t){let e=await A(this.config,this.params.notebook_path);if(!e.ok)throw new y(e.rawMessage,e.type);let o,i=!1,n,l="lf";try{let s=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});o=s.content,i=s._meta?.bom??!1,n=s._meta?.encoding,l=s._meta?.lineEnding??X(s.content)}catch(s){throw t.aborted?s:s?.code==="ENOENT"?new y(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found"):new y(`Error reading notebook: ${s instanceof Error?s.message:String(s)}`,"read_content_failure")}let p=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!p.ok)throw new y(p.rawMessage,p.type);try{return this.modifyMetadata?.modifiedNotebookContent!==void 0?{...re(o,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}:{...O(o,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}}catch(s){throw s instanceof u?new y(s.message,s.type):s}}async execute(t){let e;try{e=await this.prepareEdit(t)}catch(o){if(t.aborted)throw o;let i=o instanceof y?o.errorType:"notebook_edit_failure",n=o instanceof Error?o.message:String(o);return{llmContent:n,returnDisplay:`Error: ${n}`,error:{message:n,type:i}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}let o=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!o.ok)return{llmContent:o.rawMessage,returnDisplay:`Error: ${o.displayMessage}`,error:{message:o.rawMessage,type:o.type}};await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:e.updatedContent,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}}),this.modifyMetadata?.modifiedByUser||Q.getInstance().recordEdit(this.params.notebook_path,e.originalContent,e.updatedContent);try{let a=E.statSync(this.params.notebook_path),f=this.config.getFileReadCache();e.requiresReadAfterWrite?f.invalidate(a):f.recordWrite(this.params.notebook_path,a,{cacheable:!1})}catch(a){ee.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${a instanceof Error?a.message:String(a)}`)}let i=m.basename(this.params.notebook_path),n=R(i,e.originalContent,e.updatedContent,"Current","Proposed",D),l=Y(i,e.originalContent,this.modifyMetadata?.aiProposedContent??e.updatedContent,e.updatedContent);z(this.config,new H(S.Name,"update",e.updatedContent.split(`
|
|
4
|
-
`).length,G(this.params.notebook_path),".ipynb",e.language));let p={fileDiff:n,fileName:i,originalContent:e.originalContent,newContent:e.updatedContent,diffStat:l},s=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated. Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${e.mode} cell ${e.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated. ${e.mode} cell ${e.editedCellId}.${e.mode==="delete"?"":`
|
|
5
|
-
|
|
6
|
-
Updated source:
|
|
7
|
-
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
${B(this.params.new_source??"")}`}`;try{let a=await Z(this.config,this.params.notebook_path);a&&(s+=`
|
|
11
|
-
|
|
12
|
-
${a}`)}catch{}return{llmContent:s,returnDisplay:p,resultFilePaths:[this.params.notebook_path]}}catch(o){let i=o instanceof Error?o.message:String(o);return{llmContent:`Error writing notebook: ${i}`,returnDisplay:`Error writing notebook: ${i}`,error:{message:i,type:"file_write_failure"}}}}},S=class d extends L{constructor(t){super(d.Name,x.NOTEBOOK_EDIT,`Edits a Jupyter notebook (.ipynb) safely at the cell level. Use this instead of ${c.EDIT} or ${c.WRITE_FILE} for notebook cells. Supports replacing, inserting, and deleting cells. Always read the notebook first with ${c.READ_FILE}; then use the cell IDs shown in that output.`,"edit",{properties:{notebook_path:{description:"Absolute path to the Jupyter notebook file to edit. Must end with .ipynb.",type:"string"},cell_id:{description:"Target cell ID from read_file output, or cell-N 0-based fallback. Required for replace and delete. For insert, the new cell is inserted after this cell; if omitted, inserted at the beginning.",type:"string"},new_source:{description:"New source content for replace and insert operations. Not required for delete.",type:"string"},cell_type:{description:"Cell type for inserted cells or type conversion on replace.",type:"string",enum:["code","markdown"]},edit_mode:{description:"Notebook edit operation. Defaults to replace.",type:"string",enum:["replace","insert","delete"]}},required:["notebook_path"],additionalProperties:!1,type:"object"});this.config=t}static Name=c.NOTEBOOK_EDIT;modifyMetadataByParams=new WeakMap;modifyMetadataByKey=new Map;validateToolParamValues(t){if(t.notebook_path=T(t.notebook_path.trim()),!t.notebook_path)return"The 'notebook_path' parameter must be non-empty.";if(!m.isAbsolute(t.notebook_path))return`Notebook path must be absolute: ${t.notebook_path}`;if(m.extname(t.notebook_path).toLowerCase()!==".ipynb")return"File must be a Jupyter notebook (.ipynb). Use the edit tool for other file types.";let e=t.edit_mode??"replace";return["replace","insert","delete"].includes(e)?t.cell_type&&!["code","markdown"].includes(t.cell_type)?"cell_type must be 'code' or 'markdown'.":e!=="insert"&&!t.cell_id?"cell_id is required for replace and delete operations.":e!=="delete"&&typeof t.new_source!="string"?`new_source is required when edit_mode is "${e}".`:this.config.getFileService().shouldMatildaIgnoreFile(t.notebook_path)?`File path '${t.notebook_path}' is ignored by .matildaignore pattern(s).`:null:"edit_mode must be 'replace', 'insert', or 'delete'."}createInvocation(t){return new P(this.config,t,this.consumeModifyMetadata(t))}getModifyMetadataKey(t){return JSON.stringify({notebook_path:T(t.notebook_path.trim()),cell_id:t.cell_id,new_source:t.new_source,cell_type:t.cell_type,edit_mode:t.edit_mode})}rememberModifyMetadata(t,e){this.modifyMetadataByParams.set(t,e);let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o)??[];i.push(e),this.modifyMetadataByKey.set(o,i)}consumeModifyMetadata(t){let e=this.modifyMetadataByParams.get(t);if(e)return this.modifyMetadataByParams.delete(t),this.removeQueuedModifyMetadata(t,e),e;let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o),n=i?.shift();return i&&i.length===0&&this.modifyMetadataByKey.delete(o),n}removeQueuedModifyMetadata(t,e){let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o);if(!i)return;let n=i.indexOf(e);n!==-1&&i.splice(n,1),i.length===0&&this.modifyMetadataByKey.delete(o)}getModifyContext(t){let e=new Map,o=async i=>{let n=e.get(i.notebook_path);if(n!==void 0)return n;let{content:l}=await this.config.getFileSystemService().readTextFile({path:i.notebook_path});return e.set(i.notebook_path,l),l};return{getFilePath:i=>i.notebook_path,getCurrentContent:async i=>o(i),getProposedContent:async i=>{let n=await o(i);return O(n,i).updatedContent},createUpdatedParams:(i,n,l)=>{let p=this.modifyMetadataByParams.get(l)?.aiProposedContent;if(p===void 0)try{p=O(i,l).updatedContent}catch{p=n}let s={...l};return this.rememberModifyMetadata(s,{aiProposedContent:p,modifiedByUser:!0,modifiedNotebookContent:n}),s}}}};export{S as NotebookEditTool,O as applyNotebookEdit};
|
|
13
|
-
/**
|
|
14
|
-
* @license
|
|
15
|
-
* Copyright 2026 Matilda Team
|
|
16
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
17
|
-
*/
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m}from"./chunk-FIUFMVRX.js";import"./chunk-QCIDUZV6.js";import"./chunk-7VE3KGS4.js";import"./chunk-S4K76QPI.js";import{c as a}from"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{h as ContentGenerationPipeline,c as DeepSeekOpenAICompatibleProvider,i as EnhancedErrorHandler,b as MatildaOpenAICompatibleProvider,k as MatildaOpenAIContentGenerator,g as MiMoOpenAICompatibleProvider,e as MiniMaxOpenAICompatibleProvider,f as MistralOpenAICompatibleProvider,a as OpenAIContentConverter,j as OpenAIContentGenerator,d as OpenRouterOpenAICompatibleProvider,l as createOpenAIContentGenerator,m as determineProvider};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{bj as a,cj as b}from"./chunk-2D5W3WW7.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-OVZKSZIR.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-7VBRP4XQ.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as RipGrepTool,a as _resetRipGrepCachesForTest};
|