@code-yeongyu/senpi 2026.10.5 → 2026.10.7
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/CHANGELOG.md +46 -0
- package/dist/bundle/chunks/{anthropic-messages-G5236QNK.js → anthropic-messages-4MNFPQ66.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-3Q5G4CAF.js → app-server-command-SO5RJ2N7.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-NTA2HGG4.js → azure-openai-responses-A5OEHSJM.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-ECDLITEY.js → chunk-6EH7QXOG.js} +2 -2
- package/dist/bundle/chunks/{chunk-JVSOW4QU.js → chunk-7A3WRAKP.js} +1 -1
- package/dist/bundle/chunks/chunk-7SMFF2QJ.js +14 -0
- package/dist/bundle/chunks/{chunk-WTJU5B2C.js → chunk-BE66QJ3Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-6JXPZACL.js → chunk-CM5QTRC2.js} +1 -1
- package/dist/bundle/chunks/{chunk-UHRXXTFZ.js → chunk-D2W3MXRF.js} +2 -2
- package/dist/bundle/chunks/{chunk-U7CI2JGX.js → chunk-DDEAZX22.js} +1 -1
- package/dist/bundle/chunks/{chunk-UXIQK5NQ.js → chunk-ESSQUSRC.js} +1 -1
- package/dist/bundle/chunks/{chunk-EEOKVSNF.js → chunk-EUU6W5B3.js} +180 -176
- package/dist/bundle/chunks/{chunk-KLBKUBDV.js → chunk-GQ3YLXVZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-HKG7XL4H.js → chunk-HY4AOLON.js} +1 -1
- package/dist/bundle/chunks/{chunk-2WV426OJ.js → chunk-JJNIU2A2.js} +8 -4
- package/dist/bundle/chunks/{chunk-22DAHAHO.js → chunk-LUWWM7GA.js} +2 -2
- package/dist/bundle/chunks/{chunk-CTQU2XNX.js → chunk-MLNJNJFE.js} +1 -1
- package/dist/bundle/chunks/{chunk-BPX6QWPD.js → chunk-PELNNWGO.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBK6SSYT.js → chunk-TAV6QZFM.js} +1 -1
- package/dist/bundle/chunks/{chunk-QUROHJLP.js → chunk-TFO5JGLR.js} +1 -1
- package/dist/bundle/chunks/chunk-VJJ53ORU.js +2 -0
- package/dist/bundle/chunks/{chunk-XYDZ3LIE.js → chunk-YI7SPFDN.js} +2 -2
- package/dist/bundle/chunks/chunk-ZJHRDQCH.js +2 -0
- package/dist/bundle/chunks/cli-main-XBQN73O2.js +3 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-5ZUHUKMU.js → cloudflare-workers-ai-system-one-TE3OEJEL.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-OTMG6ZXI.js → google-generative-ai-JBC53AMK.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-2LXS3ICC.js → google-vertex-46ODNPM2.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-SHZJ3QWQ.js → help-fast-path-FUMH5NSA.js} +1 -1
- package/dist/bundle/chunks/host-command-YXQAXNKK.js +2 -0
- package/dist/bundle/chunks/{host-lifecycle-7OVWGVIZ.js → host-lifecycle-L4XQIATP.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/interactive-mode-ROO5W56P.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-U5XAMKZE.js → llama-cpp-classify-AD6TTKNL.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-34WOINP4.js → multi-session-host-5WTKAQJM.js} +5 -5
- package/dist/bundle/chunks/{openai-codex-responses-WNTYIPFZ.js → openai-codex-responses-Q4OWIK7Y.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-VSH22FCN.js → openai-completions-6HU7GIGD.js} +1 -1
- package/dist/bundle/chunks/{openai-images-XBTUJXPR.js → openai-images-M73YANTR.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-WLBHCFYL.js → openai-responses-S4QYZXF3.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-3LVJZY3G.js → openrouter-images-PCJFX2KO.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-2QLVGQSC.js → package-manager-cli-NCD5FQGV.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-JUCEXHWU.js → rotation-stream-7E37KOCX.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-MWURKCP2.js +2 -0
- package/dist/bundle/chunks/{schedule-command-QTYSUYO2.js → schedule-command-UTXB465F.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-J6RHZXWB.js +3 -0
- package/dist/bundle/chunks/{session-picker-HX4LOJZ7.js → session-picker-VTTRFGE7.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +376 -368
- package/dist/bundle/chunks/{typesafe-system-one-FNI3UASE.js → typesafe-system-one-TF23RUVG.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session-runtime.d.ts +12 -0
- package/dist/core/agent-session.d.ts +18 -0
- package/dist/core/agent-session.js +55 -19
- package/dist/core/dynamic-prompt/handoff.d.ts +4 -2
- package/dist/core/dynamic-prompt/handoff.js +1 -1
- package/dist/core/extensions/builtin/diff.js +14 -9
- package/dist/core/extensions/builtin/files.js +6 -2
- package/dist/core/extensions/builtin/gpt-apply-patch/parser.js +5 -1
- package/dist/core/extensions/builtin/gpt-apply-patch/streaming-parser.d.ts +8 -0
- package/dist/core/extensions/builtin/gpt-apply-patch/streaming-parser.js +26 -2
- package/dist/core/extensions/builtin/gpt-apply-patch/streaming-render.js +82 -11
- package/dist/core/extensions/builtin/gpt-apply-patch/types.d.ts +9 -1
- package/dist/core/extensions/builtin/permission-system/auto-credentials.d.ts +2 -0
- package/dist/core/extensions/builtin/permission-system/auto-credentials.js +17 -0
- package/dist/core/extensions/builtin/permission-system/auto-paths.d.ts +14 -0
- package/dist/core/extensions/builtin/permission-system/auto-paths.js +93 -0
- package/dist/core/extensions/builtin/permission-system/auto-policy.d.ts +20 -0
- package/dist/core/extensions/builtin/permission-system/auto-policy.js +126 -0
- package/dist/core/extensions/builtin/permission-system/auto-program-rules.d.ts +6 -0
- package/dist/core/extensions/builtin/permission-system/auto-program-rules.js +139 -0
- package/dist/core/extensions/builtin/permission-system/auto-shell-grammar.d.ts +29 -0
- package/dist/core/extensions/builtin/permission-system/auto-shell-grammar.js +74 -0
- package/dist/core/extensions/builtin/permission-system/auto-shell-segments.d.ts +13 -0
- package/dist/core/extensions/builtin/permission-system/auto-shell-segments.js +23 -0
- package/dist/core/extensions/builtin/permission-system/cli.d.ts +1 -0
- package/dist/core/extensions/builtin/permission-system/cli.js +9 -10
- package/dist/core/extensions/builtin/permission-system/config.d.ts +4 -1
- package/dist/core/extensions/builtin/permission-system/config.js +13 -1
- package/dist/core/extensions/builtin/permission-system/index.js +20 -12
- package/dist/core/extensions/builtin/permission-system/non-interactive.d.ts +11 -6
- package/dist/core/extensions/builtin/permission-system/non-interactive.js +8 -33
- package/dist/core/extensions/builtin/permission-system/service.d.ts +20 -1
- package/dist/core/extensions/builtin/permission-system/service.js +43 -7
- package/dist/core/extensions/builtin/permission-system/settings.d.ts +1 -0
- package/dist/core/extensions/builtin/permission-system/settings.js +4 -3
- package/dist/core/extensions/builtin/permission-system/types.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +16 -3
- package/dist/core/extensions/eval-handle-host.d.ts +82 -0
- package/dist/core/extensions/eval-handle-host.js +28 -0
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/runner.js +4 -0
- package/dist/core/extensions/types.d.ts +15 -0
- package/dist/core/retry-fallback/usage-limit.js +5 -1
- package/dist/core/tools/diff-render.d.ts +4 -0
- package/dist/core/tools/diff-render.js +13 -0
- package/dist/core/tools/renderers/edit.js +6 -4
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/main.js +12 -0
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.js +55 -11
- package/dist/modes/interactive/provider-error-presentation.d.ts +25 -0
- package/dist/modes/interactive/provider-error-presentation.js +42 -0
- package/dist/modes/interactive/session-control-registry.js +2 -0
- package/dist/modes/interactive/theme/dark.json +5 -5
- package/dist/modes/interactive/theme/light.json +5 -5
- package/dist/modes/rpc/custom-capability.d.ts +6 -0
- package/dist/modes/rpc/custom-capability.js +6 -0
- package/dist/modes/rpc/host-daemon-registration.d.ts +9 -0
- package/dist/modes/rpc/host-daemon-registration.js +2 -4
- package/dist/modes/rpc/host-ensure-start.js +2 -0
- package/dist/modes/rpc/host-handoff-unregistered.d.ts +24 -0
- package/dist/modes/rpc/host-handoff-unregistered.js +50 -0
- package/dist/modes/rpc/host-handoff.d.ts +7 -2
- package/dist/modes/rpc/host-handoff.js +7 -3
- package/dist/modes/rpc/host-legacy.d.ts +3 -0
- package/dist/modes/rpc/host-legacy.js +10 -5
- package/dist/modes/rpc/host-probe.d.ts +12 -0
- package/dist/modes/rpc/host-probe.js +53 -5
- package/dist/modes/rpc/host-runner.js +1 -1
- package/dist/modes/rpc/host-successor.d.ts +5 -4
- package/dist/modes/rpc/host-successor.js +11 -4
- package/dist/modes/rpc/rpc-client.d.ts +3 -0
- package/dist/modes/rpc/rpc-input-validation.d.ts +7 -0
- package/dist/modes/rpc/rpc-input-validation.js +37 -0
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/session-command-activity.d.ts +2 -0
- package/dist/modes/rpc/session-command-activity.js +25 -0
- package/dist/modes/rpc/session-command-router.js +11 -4
- package/dist/modes/rpc/session-registry-attach.js +1 -0
- package/dist/modes/rpc/session-registry-types.d.ts +7 -0
- package/dist/modes/rpc/session-registry-types.js +11 -0
- package/dist/modes/rpc/session-registry.js +6 -3
- package/dist/modes/rpc/session-sweep.d.ts +12 -2
- package/dist/modes/rpc/session-sweep.js +36 -3
- package/dist/modes/rpc/session-teardown.d.ts +2 -0
- package/dist/modes/rpc/session-teardown.js +1 -0
- package/dist/modes/rpc/worker-session-registry.js +5 -1
- package/docs/rpc.md +49 -7
- package/docs/settings.md +3 -1
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-K3BXFPWZ.js +0 -2
- package/dist/bundle/chunks/chunk-UUAKEDVS.js +0 -14
- package/dist/bundle/chunks/cli-main-VZWSUHFB.js +0 -3
- package/dist/bundle/chunks/host-command-7JIGGOWR.js +0 -2
- package/dist/bundle/chunks/interactive-mode-JA7AHYYL.js +0 -2
- package/dist/bundle/chunks/rpc-mode-QEBSN2OH.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-UGQIP6ZN.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{SYSTEM_THEME_NAME,SettingsManager,appendHiddenTuiStdout,getTerminalTheme,initTheme,isStdoutTakenOver,loadThemeFromPath,markTerminalColorsPending,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,theme}from"./chunk-UXIQK5NQ.js";import{KeybindingsManager}from"./chunk-V2VQ4BHG.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatchLower,getKeybindings,nextRenderRevision,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-K4AZKFRB.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{dropFailedAssistantTurns}from"./chunk-UHRXXTFZ.js";import{copyContextProvenance}from"./chunk-KC5TT7DH.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getSessionsDir,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,normalizePath,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-463OK2Y4.js";import{getCurrentSystemMessage,isModelType,lazyStream,normalizeProviderId}from"./chunk-XL5KIYQF.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_index_min=__commonJS({"node_modules/lru-cache/dist/commonjs/node/index.min.js"(exports){"use strict";var j=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports),I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0}),O.tracing=O.metrics=void 0;var U=__require("node:diagnostics_channel");O.metrics=(0,U.channel)("lru-cache:metrics"),O.tracing=(0,U.tracingChannel)("lru-cache")}),P=j(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0}),R.defaultPerf=void 0,R.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),C=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(u,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(u,t,e,i):console.error(`[${e}] ${t}: ${u}`)},q=u=>!k.has(u),T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),H=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},L=class u{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];u.#o=!0;let i=new u(t,e);return u.#o=!1,i}constructor(t,e){if(!u.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},M=class u{#o;#c;#m;#W;#S;#x;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#_;#r;#y;#F;#d;#g;#T;#U;#f;#R;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#M(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#x}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:l,allowStale:h,dispose:r,onInsert:c,disposeAfter:w,noDisposeOnSet:y,noUpdateTTL:d,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:_,fetchMethod:a,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:x=1,perf:v}=t;if(this.backgroundFetchSize=x,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,a!==void 0&&typeof a!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#x=a,this.#U=!!a,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#_=L.create(e),this.#n=0,this.#b=0,typeof r=="function"&&(this.#m=r),typeof c=="function"&&(this.#W=c),typeof w=="function"?(this.#S=w,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#R=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!y,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!l,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let D="LRU_CACHE_UNBOUNDED";q(D)&&(k.add(D),V("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",D,u))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,r,c=this.#w.now())=>{e[h]=r!==0?c:0,t[h]=r,s(h,r)},this.#D=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,r)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),r&&r!==0&&i){let c=setTimeout(()=>{this.#p(h)?(this.#v(this.#i[h],"expire"),i[h]=void 0):s(h,l(h))},r+1);c.unref&&c.unref(),i[h]=c}}:()=>{};this.#E=(h,r)=>{if(t[r]){let c=t[r],w=e[r];if(!c||!w)return;h.ttl=c,h.start=w,h.now=n||o();let y=h.now-w;h.remainingTTL=c-y}};let n=0,o=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let r=setTimeout(()=>n=0,this.ttlResolution);r.unref&&r.unref()}return h};this.getRemainingTTL=h=>{let r=this.#s.get(h);return r===void 0?0:l(r)};let l=h=>{let r=t[h],c=e[h];if(!r||!c)return 1/0;let w=(n||o())-c;return r-w};this.#p=h=>{let r=e[h],c=t[h];return!!c&&!!r&&(n||o())-r>c}}#D=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#y=t,this.#C=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return s},this.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#C=t=>{};#I=(t,e,i)=>{};#N=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#z())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#z()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#z())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.#L(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#z({allowStale:!0}))this.#p(e)&&(this.#v(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let o=this.#d[e],l=this.#F[e];if(o&&l){let h=o-(this.#w.now()-l);n.ttl=h,n.start=Date.now()}}return this.#y&&(n.size=this.#y[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let o={value:n};if(this.#d&&this.#F){o.ttl=this.#d[e];let l=this.#w.now()-this.#F[e];o.start=Math.floor(Date.now()-l)}this.#y&&(o.size=this.#y[e]),t.unshift([i,o])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:o,noDisposeOnSet:l=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:r}=i,c=this.#e(e);if(e===void 0)return r&&(r.set="deleted"),this.delete(t),this;let{noUpdateTTL:w=this.noUpdateTTL}=i;r&&!c&&(r.value=e);let y=this.#N(t,e,i.size||0,h,r);if(this.maxEntrySize&&y>this.maxEntrySize)return this.#v(t,"set"),r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this;let d=this.#n===0?void 0:this.#s.get(t);if(d===void 0)d=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[d]=t,this.#t[d]=e,this.#s.set(t,d),this.#l[this.#h]=d,this.#u[d]=this.#h,this.#h=d,this.#n++,this.#I(d,y,r),r&&(r.set="add"),w=!1,this.#R&&!c&&this.#W?.(e,t,"add");else{this.#M(d);let p=this.#t[d];if(e!==p){if(!l)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#C(d),this.#I(d,y,r),this.#t[d]=e,!c){let f=p&&this.#e(p)?p.__staleWhileFetching:p,_=f===void 0?"add":e!==f?"replace":"update";r&&(r.set=_,f!==void 0&&(r.oldValue=f)),this.#R&&this.onInsert?.(e,t,_)}}else c||(r&&(r.set="update"),this.#R&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(w||this.#H(d,n,o),r&&this.#E(r,d)),!l&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let o=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&o!==void 0&&(this.#T&&this.#m?.(o,i,"evict"),this.#f&&this.#r?.push([o,i,"evict"])),this.#C(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#a=this.#h=0,this.#_.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let o=this.#t[n];if(this.#e(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=C()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let o=this.#t[n],l=this.#e(o)?o.__staleWhileFetching:o;return i&&(l!==void 0?(i.peek="hit",i.value=l):i.peek="miss"),l}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let o=new AbortController,{signal:l}=i;l?.addEventListener("abort",()=>o.abort(l.reason),{signal:o.signal});let h={signal:o.signal,options:i,context:s},r=(f,_=!1)=>{let{aborted:a}=o.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(a&&!_?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!S&&!_)return w(o.signal.reason,F);let b=d,m=this.#t[e];return(m===d||m===void 0&&S&&_)&&(f===void 0?b.__staleWhileFetching!==void 0?this.#t[e]=b.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,h.options,b))),f},c=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),w(f,!1)),w=(f,_)=>{let{aborted:a}=o.signal,S=a&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,b=F||i.noDeleteOnFetchRejection,m=d;if(this.#t[e]===d&&(!b||!_&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},y=(f,_)=>{let a=this.#x?.(t,n,h);o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>r(S,!0)))}),a&&a instanceof Promise?a.then(S=>f(S===void 0?void 0:S),_):a!==void 0&&f(a)};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(y).then(r,c),p=Object.assign(d,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...h.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#q(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#q(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:h=0,sizeCalculation:r=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:_=!1,status:a,signal:S}=e;if(a&&(a.op="fetch",a.key=t,_&&(a.forceRefresh=!0),a.cache=this),!this.#U)return a&&(a.fetch="get"),this.#L(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:l,size:h,sizeCalculation:r,noUpdateTTL:c,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:a,signal:S},b=this.#s.get(t);if(b===void 0){a&&(a.fetch="miss");let m=this.#G(t,b,F,f);return m.__returned=m}else{let m=this.#t[b];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",E&&(a.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(b);if(!_&&!A)return a&&(a.fetch="hit"),this.#M(b),s&&this.#D(b),a&&this.#E(a,b),m;let z=this.#G(t,b,F,f),v=z.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=A?"stale":"refresh",v&&A&&(a.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#q(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:o,...l}=e;n&&o&&(n.forceRefresh=!0);let h=this.#L(t,l),r=o||h===void 0;if(n&&(n.memo=r?"miss":"hit",r||(n.value=h)),!r)return h;let c=i(t,h,{options:l,context:s});return n&&(n.value=c),this.#O(t,c,l),c}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#L(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#L(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,l=this.#s.get(t);if(l===void 0){o&&(o.get="miss");return}let h=this.#t[l],r=this.#e(h);return o&&this.#E(o,l),this.#p(l)?r?(o&&(o.get="stale-fetching"),i&&h.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),h.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),o&&(o.get="stale"),i?(o&&(o.returnedStale=!0),h):void 0):(o&&(o.get=r?"fetching":"hit"),this.#M(l),s&&this.#D(l),r?h.__staleWhileFetching:h)}#B(t,e){this.#u[e]=t,this.#l[t]=e}#M(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#B(this.#u[t],this.#l[t]),this.#B(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#C(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let o=this.#u[s];this.#l[o]=this.#l[s];let l=this.#l[s];this.#u[l]=this.#u[s]}this.#n--,this.#_.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#a=0,this.#h=0,this.#_.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=M}});var require_hosts=__commonJS({"node_modules/hosted-git-info/lib/hosts.js"(exports,module){"use strict";var maybeJoin=(...args)=>args.every(arg=>arg)?args.join(""):"",maybeEncode=arg=>arg?encodeURIComponent(arg):"",formatHashFragment=f=>f.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),defaults2={sshtemplate:({domain,user,project,committish})=>`git@${domain}:${user}/${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,user,project,committish})=>`git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath,path:path2})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path2)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,docstemplate:({domain,user,project,treepath,committish})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}#readme`,httpstemplate:({auth,domain,user,project,committish})=>`git+https://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path2}`,shortcuttemplate:({type,user,project,committish})=>`${type}:${user}/${project}${maybeJoin("#",committish)}`,pathtemplate:({user,project,committish})=>`${user}/${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,user,project})=>`https://${domain}/${user}/${project}/issues`,hashformat:formatHashFragment},hosts={};hosts.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth,user,project,committish,path:path2})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path2}`,gittemplate:({auth,domain,user,project,committish})=>`git://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,type,committish]=url.pathname.split("/",5);if(!(type&&type!=="tree")&&(type||(committish=url.hash.slice(1)),project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish}}};hosts.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain,user,project,committish,treepath,path:path2,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path2,editpath)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/get/${maybeEncode(committish||"HEAD")}.tar.gz`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["get"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};hosts.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",tarballtemplate:({domain,user,project,committish})=>`https://${domain}/api/v4/projects/${maybeEncode(user+"/"+project)}/repository/archive.tar.gz?sha=${maybeEncode(committish||"HEAD")}`,extract:url=>{let path2=url.pathname.slice(1);if(path2.includes("/-/")||path2.includes("/archive.tar.gz"))return;let segments=path2.split("/"),project=segments.pop();project.endsWith(".git")&&(project=project.slice(0,-4));let user=segments.join("/");if(!(!user||!project))return{user,project,committish:url.hash.slice(1)}}};hosts.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain,project,committish})=>`git@${domain}:${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,project,committish})=>`git+ssh://git@${domain}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",maybeEncode(committish))}/${editpath}`,browsetemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,browsetreetemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,browseblobtemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,docstemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,httpstemplate:({domain,project,committish})=>`git+https://${domain}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({user,project,committish,path:path2})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path2}`,shortcuttemplate:({type,project,committish})=>`${type}:${project}${maybeJoin("#",committish)}`,pathtemplate:({project,committish})=>`${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,project})=>`https://${domain}/${project}`,gittemplate:({domain,project,committish})=>`git://${domain}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({project,committish})=>`https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(aux!=="raw"){if(!project){if(!user)return;project=user,user=null}return project.endsWith(".git")&&(project=project.slice(0,-4)),{user,project,committish:url.hash.slice(1)}}},hashformat:function(fragment){return fragment&&"file-"+formatHashFragment(fragment)}};hosts.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path2}`,httpstemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/archive/${maybeEncode(committish)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["archive"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};for(let[name,host]of Object.entries(hosts))hosts[name]=Object.assign({},defaults2,host);module.exports=hosts}});var require_parse_url=__commonJS({"node_modules/hosted-git-info/lib/parse-url.js"(exports,module){var lastIndexOfBefore=(str,char,beforeChar)=>{let startPosition=str.indexOf(beforeChar);return str.lastIndexOf(char,startPosition>-1?startPosition:1/0)},safeUrl=u=>{try{return new URL(u)}catch{}},correctProtocol=(arg,protocols)=>{let firstColon=arg.indexOf(":"),proto=arg.slice(0,firstColon+1);if(Object.prototype.hasOwnProperty.call(protocols,proto)||arg.substr(firstColon,3)==="://")return arg;let firstAt=arg.indexOf("@");return firstAt>-1?firstAt>firstColon?`git+ssh://${arg}`:arg:`${arg.slice(0,firstColon+1)}//${arg.slice(firstColon+1)}`},correctUrl=giturl=>{let firstAt=lastIndexOfBefore(giturl,"@","#"),lastColonBeforeHash=lastIndexOfBefore(giturl,":","#");return lastColonBeforeHash>firstAt&&(giturl=giturl.slice(0,lastColonBeforeHash)+"/"+giturl.slice(lastColonBeforeHash+1)),lastIndexOfBefore(giturl,":","#")===-1&&giturl.indexOf("//")===-1&&(giturl=`git+ssh://${giturl}`),giturl};module.exports=(giturl,protocols)=>{let withProtocol=protocols?correctProtocol(giturl,protocols):giturl;return safeUrl(withProtocol)||safeUrl(correctUrl(withProtocol))}}});var require_from_url=__commonJS({"node_modules/hosted-git-info/lib/from-url.js"(exports,module){"use strict";var parseUrl=require_parse_url(),isGitHubShorthand=arg=>{let firstHash=arg.indexOf("#"),firstSlash=arg.indexOf("/"),secondSlash=arg.indexOf("/",firstSlash+1),firstColon=arg.indexOf(":"),firstSpace=/\s/.exec(arg),firstAt=arg.indexOf("@"),spaceOnlyAfterHash=!firstSpace||firstHash>-1&&firstSpace.index>firstHash,atOnlyAfterHash=firstAt===-1||firstHash>-1&&firstAt>firstHash,colonOnlyAfterHash=firstColon===-1||firstHash>-1&&firstColon>firstHash,secondSlashOnlyAfterHash=secondSlash===-1||firstHash>-1&&secondSlash>firstHash,hasSlash=firstSlash>0,doesNotEndWithSlash=firstHash>-1?arg[firstHash-1]!=="/":!arg.endsWith("/"),doesNotStartWithDot=!arg.startsWith(".");return spaceOnlyAfterHash&&hasSlash&&doesNotEndWithSlash&&doesNotStartWithDot&&atOnlyAfterHash&&colonOnlyAfterHash&&secondSlashOnlyAfterHash};module.exports=(giturl,opts,{gitHosts,protocols})=>{if(!giturl)return;let correctedUrl=isGitHubShorthand(giturl)?`github:${giturl}`:giturl,parsed=parseUrl(correctedUrl,protocols);if(!parsed)return;let gitHostShortcut=gitHosts.byShortcut[parsed.protocol],gitHostDomain=gitHosts.byDomain[parsed.hostname.startsWith("www.")?parsed.hostname.slice(4):parsed.hostname],gitHostName=gitHostShortcut||gitHostDomain;if(!gitHostName)return;let gitHostInfo=gitHosts[gitHostShortcut||gitHostDomain],auth=null;protocols[parsed.protocol]?.auth&&(parsed.username||parsed.password)&&(auth=`${parsed.username}${parsed.password?":"+parsed.password:""}`);let committish=null,user=null,project=null,defaultRepresentation=null;try{if(gitHostShortcut){let pathname=parsed.pathname.startsWith("/")?parsed.pathname.slice(1):parsed.pathname,firstAt=pathname.indexOf("@");firstAt>-1&&(pathname=pathname.slice(firstAt+1));let lastSlash=pathname.lastIndexOf("/");lastSlash>-1?(user=decodeURIComponent(pathname.slice(0,lastSlash)),user||(user=null),project=decodeURIComponent(pathname.slice(lastSlash+1))):project=decodeURIComponent(pathname),project.endsWith(".git")&&(project=project.slice(0,-4)),parsed.hash&&(committish=decodeURIComponent(parsed.hash.slice(1))),defaultRepresentation="shortcut"}else{if(!gitHostInfo.protocols.includes(parsed.protocol))return;let segments=gitHostInfo.extract(parsed);if(!segments)return;user=segments.user&&decodeURIComponent(segments.user),project=decodeURIComponent(segments.project),committish=decodeURIComponent(segments.committish),defaultRepresentation=protocols[parsed.protocol]?.name||parsed.protocol.slice(0,-1)}}catch(err){if(err instanceof URIError)return;throw err}return[gitHostName,user,auth,project,committish,defaultRepresentation,opts]}}});var require_lib=__commonJS({"node_modules/hosted-git-info/lib/index.js"(exports,module){"use strict";var{LRUCache}=require_index_min(),hosts=require_hosts(),fromUrl=require_from_url(),parseUrl=require_parse_url(),cache2=new LRUCache({max:1e3});function unknownHostedUrl(url){try{let{protocol,hostname,pathname}=new URL(url);if(!hostname)return null;let proto=/(?:git\+)http:$/.test(protocol)?"http:":"https:",path2=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path2}`}catch{return null}}var GitHost=class _GitHost{constructor(type,user,auth,project,committish,defaultRepresentation,opts={}){Object.assign(this,_GitHost.#gitHosts[type],{type,user,auth,project,committish,default:defaultRepresentation,opts})}static#gitHosts={byShortcut:{},byDomain:{}};static#protocols={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(name,host){_GitHost.#gitHosts[name]=host,_GitHost.#gitHosts.byDomain[host.domain]=name,_GitHost.#gitHosts.byShortcut[`${name}:`]=name,_GitHost.#protocols[`${name}:`]={name}}static fromUrl(giturl,opts){if(typeof giturl!="string")return;let key=giturl+JSON.stringify(opts||{});if(!cache2.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache2.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache2.get(key)}static fromManifest(manifest,opts={}){if(!manifest||typeof manifest!="object")return;let r=manifest.repository,rurl=r&&(typeof r=="string"?r:typeof r=="object"&&typeof r.url=="string"?r.url:null);if(!rurl)throw new Error("no repository");let info=rurl&&_GitHost.fromUrl(rurl.replace(/^git\+/,""),opts)||null;if(info)return info;let unk=unknownHostedUrl(rurl);return _GitHost.fromUrl(unk,opts)||unk}static parseUrl(url){return parseUrl(url)}#fill(template,opts){if(typeof template!="function")return null;let options={...this,...this.opts,...opts};options.path||(options.path=""),options.path.startsWith("/")&&(options.path=options.path.slice(1)),options.noCommittish&&(options.committish=null);let result=template(options);return options.noGitPlus&&result.startsWith("git+")?result.slice(4):result}hash(){return this.committish?`#${this.committish}`:""}ssh(opts){return this.#fill(this.sshtemplate,opts)}sshurl(opts){return this.#fill(this.sshurltemplate,opts)}browse(path2,...args){return typeof path2!="string"?this.#fill(this.browsetemplate,path2):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path2}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path2})}browseFile(path2,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path2}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path2})}docs(opts){return this.#fill(this.docstemplate,opts)}bugs(opts){return this.#fill(this.bugstemplate,opts)}https(opts){return this.#fill(this.httpstemplate,opts)}git(opts){return this.#fill(this.gittemplate,opts)}shortcut(opts){return this.#fill(this.shortcuttemplate,opts)}path(opts){return this.#fill(this.pathtemplate,opts)}tarball(opts){return this.#fill(this.tarballtemplate,{...opts,noCommittish:!1})}file(path2,opts){return this.#fill(this.filetemplate,{...opts,path:path2})}edit(path2,opts){return this.#fill(this.edittemplate,{...opts,path:path2})}getDefaultRepresentation(){return this.default}toString(opts){return this.default&&typeof this[this.default]=="function"?this[this.default](opts):this.sshurl(opts)}};for(let[name,host]of Object.entries(hosts))GitHost.addHost(name,host);module.exports=GitHost}});var require_ignore=__commonJS({"node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object,key,value)=>(Object.defineProperty(object,key,{value}),value),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY,prev=EMPTY;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match2=>`\\${match2}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str)=>index+6<str.length?str.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":"\\/.+","*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match2,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match2,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match2,range2,endEscape,close)=>`\\[${range2}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",TRAILING_WILD_CARD_REPLACERS={[MODE_IGNORE](_,p1){return`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`},[MODE_CHECK_IGNORE](_,p1){return`${p1?`${p1}[^/]*`:"[^/]*"}(?=$|\\/$)`}},WILDCARD="[^\\/]*",pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${run[at+1].single})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match2,index)=>sources[index]):replaced},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path2=>{let end=path2.length-1,index=path2.lastIndexOf(SLASH,path2[end]===SLASH?end-1:end);return index<0?path2:path2.slice(index+1)},parentOf=path2=>{if(path2.charCodeAt(0)===SLASH_CODE||path2.indexOf(DOUBLE_SLASH)>=0){let slices=path2.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path2.length-1,cut=path2.lastIndexOf(SLASH,path2.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path2.slice(0,cut+1)},isString=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str=pinWildcards(this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,TRAILING_WILD_CARD_REPLACERS[mode])),regex=this.ignoreCase?new RegExp(str,"i"):new RegExp(str);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added}test(path2,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename4=shortcut?basenameOf(path2):path2;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename4:path2)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path2,originalPath,doThrow)=>isString(path2)?path2?checkPath.isNotRelative(path2)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path2=>{let first=path2.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path2.length===1)return!0;let second=path2.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path2.length===2||path2.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache2,checkUnignored){let path2=originalPath&&checkPath.convert(originalPath);return checkPath(path2,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path2,cache2,checkUnignored)}checkIgnore(path2){if(path2.charCodeAt(path2.length-1)!==SLASH_CODE)return this.test(path2);let parentPath=parentOf(path2);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path2,!1,MODE_CHECK_IGNORE)}_t(path2,cache2,checkUnignored){if(path2 in cache2)return cache2[path2];let parentPath=parentOf(path2),parent=parentPath?this._t(parentPath,cache2,checkUnignored):UNDEFINED;return cache2[path2]=parent&&parent.ignored?parent:this._rules.test(path2,checkUnignored,MODE_IGNORE)}ignores(path2){return this._test(path2,this._ignoreCache,!1).ignored}createFilter(){return path2=>!this.ignores(path2)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path2){return this._test(path2,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path2=>checkPath(path2&&checkPath.convert(path2),path2,RETURN_FALSE),setupWindows=()=>{let makePosix=str=>/^\\\\\?\\/.test(str)||/["<>|\u0000-\u001F]+/u.test(str)?str:str.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path2=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path2)||isNotRelative(path2)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
2
|
+
import{SYSTEM_THEME_NAME,SettingsManager,appendHiddenTuiStdout,getTerminalTheme,initTheme,isStdoutTakenOver,loadThemeFromPath,markTerminalColorsPending,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,theme}from"./chunk-ESSQUSRC.js";import{KeybindingsManager}from"./chunk-V2VQ4BHG.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatchLower,getKeybindings,nextRenderRevision,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-K4AZKFRB.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{dropFailedAssistantTurns}from"./chunk-D2W3MXRF.js";import{copyContextProvenance}from"./chunk-KC5TT7DH.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getSessionsDir,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,normalizePath,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-463OK2Y4.js";import{getCurrentSystemMessage,isModelType,lazyStream,normalizeProviderId}from"./chunk-XL5KIYQF.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_index_min=__commonJS({"node_modules/lru-cache/dist/commonjs/node/index.min.js"(exports){"use strict";var j=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports),I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0}),O.tracing=O.metrics=void 0;var U=__require("node:diagnostics_channel");O.metrics=(0,U.channel)("lru-cache:metrics"),O.tracing=(0,U.tracingChannel)("lru-cache")}),P=j(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0}),R.defaultPerf=void 0,R.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),C=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(u,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(u,t,e,i):console.error(`[${e}] ${t}: ${u}`)},q=u=>!k.has(u),T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),H=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},L=class u{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];u.#o=!0;let i=new u(t,e);return u.#o=!1,i}constructor(t,e){if(!u.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},M=class u{#o;#c;#m;#W;#S;#x;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#_;#r;#y;#F;#d;#g;#T;#U;#f;#R;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#M(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#x}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:l,allowStale:h,dispose:r,onInsert:c,disposeAfter:w,noDisposeOnSet:y,noUpdateTTL:d,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:_,fetchMethod:a,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:x=1,perf:v}=t;if(this.backgroundFetchSize=x,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,a!==void 0&&typeof a!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#x=a,this.#U=!!a,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#_=L.create(e),this.#n=0,this.#b=0,typeof r=="function"&&(this.#m=r),typeof c=="function"&&(this.#W=c),typeof w=="function"?(this.#S=w,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#R=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!y,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!l,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let D="LRU_CACHE_UNBOUNDED";q(D)&&(k.add(D),V("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",D,u))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,r,c=this.#w.now())=>{e[h]=r!==0?c:0,t[h]=r,s(h,r)},this.#D=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,r)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),r&&r!==0&&i){let c=setTimeout(()=>{this.#p(h)?(this.#v(this.#i[h],"expire"),i[h]=void 0):s(h,l(h))},r+1);c.unref&&c.unref(),i[h]=c}}:()=>{};this.#E=(h,r)=>{if(t[r]){let c=t[r],w=e[r];if(!c||!w)return;h.ttl=c,h.start=w,h.now=n||o();let y=h.now-w;h.remainingTTL=c-y}};let n=0,o=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let r=setTimeout(()=>n=0,this.ttlResolution);r.unref&&r.unref()}return h};this.getRemainingTTL=h=>{let r=this.#s.get(h);return r===void 0?0:l(r)};let l=h=>{let r=t[h],c=e[h];if(!r||!c)return 1/0;let w=(n||o())-c;return r-w};this.#p=h=>{let r=e[h],c=t[h];return!!c&&!!r&&(n||o())-r>c}}#D=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#y=t,this.#C=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return s},this.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#C=t=>{};#I=(t,e,i)=>{};#N=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#z())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#z()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#z())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.#L(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#z({allowStale:!0}))this.#p(e)&&(this.#v(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let o=this.#d[e],l=this.#F[e];if(o&&l){let h=o-(this.#w.now()-l);n.ttl=h,n.start=Date.now()}}return this.#y&&(n.size=this.#y[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let o={value:n};if(this.#d&&this.#F){o.ttl=this.#d[e];let l=this.#w.now()-this.#F[e];o.start=Math.floor(Date.now()-l)}this.#y&&(o.size=this.#y[e]),t.unshift([i,o])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:o,noDisposeOnSet:l=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:r}=i,c=this.#e(e);if(e===void 0)return r&&(r.set="deleted"),this.delete(t),this;let{noUpdateTTL:w=this.noUpdateTTL}=i;r&&!c&&(r.value=e);let y=this.#N(t,e,i.size||0,h,r);if(this.maxEntrySize&&y>this.maxEntrySize)return this.#v(t,"set"),r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this;let d=this.#n===0?void 0:this.#s.get(t);if(d===void 0)d=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[d]=t,this.#t[d]=e,this.#s.set(t,d),this.#l[this.#h]=d,this.#u[d]=this.#h,this.#h=d,this.#n++,this.#I(d,y,r),r&&(r.set="add"),w=!1,this.#R&&!c&&this.#W?.(e,t,"add");else{this.#M(d);let p=this.#t[d];if(e!==p){if(!l)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#C(d),this.#I(d,y,r),this.#t[d]=e,!c){let f=p&&this.#e(p)?p.__staleWhileFetching:p,_=f===void 0?"add":e!==f?"replace":"update";r&&(r.set=_,f!==void 0&&(r.oldValue=f)),this.#R&&this.onInsert?.(e,t,_)}}else c||(r&&(r.set="update"),this.#R&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(w||this.#H(d,n,o),r&&this.#E(r,d)),!l&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let o=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&o!==void 0&&(this.#T&&this.#m?.(o,i,"evict"),this.#f&&this.#r?.push([o,i,"evict"])),this.#C(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#a=this.#h=0,this.#_.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let o=this.#t[n];if(this.#e(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=C()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let o=this.#t[n],l=this.#e(o)?o.__staleWhileFetching:o;return i&&(l!==void 0?(i.peek="hit",i.value=l):i.peek="miss"),l}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let o=new AbortController,{signal:l}=i;l?.addEventListener("abort",()=>o.abort(l.reason),{signal:o.signal});let h={signal:o.signal,options:i,context:s},r=(f,_=!1)=>{let{aborted:a}=o.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(a&&!_?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!S&&!_)return w(o.signal.reason,F);let b=d,m=this.#t[e];return(m===d||m===void 0&&S&&_)&&(f===void 0?b.__staleWhileFetching!==void 0?this.#t[e]=b.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,h.options,b))),f},c=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),w(f,!1)),w=(f,_)=>{let{aborted:a}=o.signal,S=a&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,b=F||i.noDeleteOnFetchRejection,m=d;if(this.#t[e]===d&&(!b||!_&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},y=(f,_)=>{let a=this.#x?.(t,n,h);o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>r(S,!0)))}),a&&a instanceof Promise?a.then(S=>f(S===void 0?void 0:S),_):a!==void 0&&f(a)};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(y).then(r,c),p=Object.assign(d,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...h.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#q(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#q(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:h=0,sizeCalculation:r=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:_=!1,status:a,signal:S}=e;if(a&&(a.op="fetch",a.key=t,_&&(a.forceRefresh=!0),a.cache=this),!this.#U)return a&&(a.fetch="get"),this.#L(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:l,size:h,sizeCalculation:r,noUpdateTTL:c,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:a,signal:S},b=this.#s.get(t);if(b===void 0){a&&(a.fetch="miss");let m=this.#G(t,b,F,f);return m.__returned=m}else{let m=this.#t[b];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",E&&(a.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(b);if(!_&&!A)return a&&(a.fetch="hit"),this.#M(b),s&&this.#D(b),a&&this.#E(a,b),m;let z=this.#G(t,b,F,f),v=z.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=A?"stale":"refresh",v&&A&&(a.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#q(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:o,...l}=e;n&&o&&(n.forceRefresh=!0);let h=this.#L(t,l),r=o||h===void 0;if(n&&(n.memo=r?"miss":"hit",r||(n.value=h)),!r)return h;let c=i(t,h,{options:l,context:s});return n&&(n.value=c),this.#O(t,c,l),c}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#L(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#L(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,l=this.#s.get(t);if(l===void 0){o&&(o.get="miss");return}let h=this.#t[l],r=this.#e(h);return o&&this.#E(o,l),this.#p(l)?r?(o&&(o.get="stale-fetching"),i&&h.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),h.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),o&&(o.get="stale"),i?(o&&(o.returnedStale=!0),h):void 0):(o&&(o.get=r?"fetching":"hit"),this.#M(l),s&&this.#D(l),r?h.__staleWhileFetching:h)}#B(t,e){this.#u[e]=t,this.#l[t]=e}#M(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#B(this.#u[t],this.#l[t]),this.#B(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#C(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let o=this.#u[s];this.#l[o]=this.#l[s];let l=this.#l[s];this.#u[l]=this.#u[s]}this.#n--,this.#_.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#a=0,this.#h=0,this.#_.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=M}});var require_hosts=__commonJS({"node_modules/hosted-git-info/lib/hosts.js"(exports,module){"use strict";var maybeJoin=(...args)=>args.every(arg=>arg)?args.join(""):"",maybeEncode=arg=>arg?encodeURIComponent(arg):"",formatHashFragment=f=>f.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),defaults2={sshtemplate:({domain,user,project,committish})=>`git@${domain}:${user}/${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,user,project,committish})=>`git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath,path:path2})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path2)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,docstemplate:({domain,user,project,treepath,committish})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}#readme`,httpstemplate:({auth,domain,user,project,committish})=>`git+https://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path2}`,shortcuttemplate:({type,user,project,committish})=>`${type}:${user}/${project}${maybeJoin("#",committish)}`,pathtemplate:({user,project,committish})=>`${user}/${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,user,project})=>`https://${domain}/${user}/${project}/issues`,hashformat:formatHashFragment},hosts={};hosts.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth,user,project,committish,path:path2})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path2}`,gittemplate:({auth,domain,user,project,committish})=>`git://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,type,committish]=url.pathname.split("/",5);if(!(type&&type!=="tree")&&(type||(committish=url.hash.slice(1)),project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish}}};hosts.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain,user,project,committish,treepath,path:path2,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path2,editpath)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/get/${maybeEncode(committish||"HEAD")}.tar.gz`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["get"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};hosts.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",tarballtemplate:({domain,user,project,committish})=>`https://${domain}/api/v4/projects/${maybeEncode(user+"/"+project)}/repository/archive.tar.gz?sha=${maybeEncode(committish||"HEAD")}`,extract:url=>{let path2=url.pathname.slice(1);if(path2.includes("/-/")||path2.includes("/archive.tar.gz"))return;let segments=path2.split("/"),project=segments.pop();project.endsWith(".git")&&(project=project.slice(0,-4));let user=segments.join("/");if(!(!user||!project))return{user,project,committish:url.hash.slice(1)}}};hosts.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain,project,committish})=>`git@${domain}:${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,project,committish})=>`git+ssh://git@${domain}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",maybeEncode(committish))}/${editpath}`,browsetemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,browsetreetemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,browseblobtemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,docstemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,httpstemplate:({domain,project,committish})=>`git+https://${domain}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({user,project,committish,path:path2})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path2}`,shortcuttemplate:({type,project,committish})=>`${type}:${project}${maybeJoin("#",committish)}`,pathtemplate:({project,committish})=>`${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,project})=>`https://${domain}/${project}`,gittemplate:({domain,project,committish})=>`git://${domain}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({project,committish})=>`https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(aux!=="raw"){if(!project){if(!user)return;project=user,user=null}return project.endsWith(".git")&&(project=project.slice(0,-4)),{user,project,committish:url.hash.slice(1)}}},hashformat:function(fragment){return fragment&&"file-"+formatHashFragment(fragment)}};hosts.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path2}`,httpstemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/archive/${maybeEncode(committish)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["archive"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};for(let[name,host]of Object.entries(hosts))hosts[name]=Object.assign({},defaults2,host);module.exports=hosts}});var require_parse_url=__commonJS({"node_modules/hosted-git-info/lib/parse-url.js"(exports,module){var lastIndexOfBefore=(str,char,beforeChar)=>{let startPosition=str.indexOf(beforeChar);return str.lastIndexOf(char,startPosition>-1?startPosition:1/0)},safeUrl=u=>{try{return new URL(u)}catch{}},correctProtocol=(arg,protocols)=>{let firstColon=arg.indexOf(":"),proto=arg.slice(0,firstColon+1);if(Object.prototype.hasOwnProperty.call(protocols,proto)||arg.substr(firstColon,3)==="://")return arg;let firstAt=arg.indexOf("@");return firstAt>-1?firstAt>firstColon?`git+ssh://${arg}`:arg:`${arg.slice(0,firstColon+1)}//${arg.slice(firstColon+1)}`},correctUrl=giturl=>{let firstAt=lastIndexOfBefore(giturl,"@","#"),lastColonBeforeHash=lastIndexOfBefore(giturl,":","#");return lastColonBeforeHash>firstAt&&(giturl=giturl.slice(0,lastColonBeforeHash)+"/"+giturl.slice(lastColonBeforeHash+1)),lastIndexOfBefore(giturl,":","#")===-1&&giturl.indexOf("//")===-1&&(giturl=`git+ssh://${giturl}`),giturl};module.exports=(giturl,protocols)=>{let withProtocol=protocols?correctProtocol(giturl,protocols):giturl;return safeUrl(withProtocol)||safeUrl(correctUrl(withProtocol))}}});var require_from_url=__commonJS({"node_modules/hosted-git-info/lib/from-url.js"(exports,module){"use strict";var parseUrl=require_parse_url(),isGitHubShorthand=arg=>{let firstHash=arg.indexOf("#"),firstSlash=arg.indexOf("/"),secondSlash=arg.indexOf("/",firstSlash+1),firstColon=arg.indexOf(":"),firstSpace=/\s/.exec(arg),firstAt=arg.indexOf("@"),spaceOnlyAfterHash=!firstSpace||firstHash>-1&&firstSpace.index>firstHash,atOnlyAfterHash=firstAt===-1||firstHash>-1&&firstAt>firstHash,colonOnlyAfterHash=firstColon===-1||firstHash>-1&&firstColon>firstHash,secondSlashOnlyAfterHash=secondSlash===-1||firstHash>-1&&secondSlash>firstHash,hasSlash=firstSlash>0,doesNotEndWithSlash=firstHash>-1?arg[firstHash-1]!=="/":!arg.endsWith("/"),doesNotStartWithDot=!arg.startsWith(".");return spaceOnlyAfterHash&&hasSlash&&doesNotEndWithSlash&&doesNotStartWithDot&&atOnlyAfterHash&&colonOnlyAfterHash&&secondSlashOnlyAfterHash};module.exports=(giturl,opts,{gitHosts,protocols})=>{if(!giturl)return;let correctedUrl=isGitHubShorthand(giturl)?`github:${giturl}`:giturl,parsed=parseUrl(correctedUrl,protocols);if(!parsed)return;let gitHostShortcut=gitHosts.byShortcut[parsed.protocol],gitHostDomain=gitHosts.byDomain[parsed.hostname.startsWith("www.")?parsed.hostname.slice(4):parsed.hostname],gitHostName=gitHostShortcut||gitHostDomain;if(!gitHostName)return;let gitHostInfo=gitHosts[gitHostShortcut||gitHostDomain],auth=null;protocols[parsed.protocol]?.auth&&(parsed.username||parsed.password)&&(auth=`${parsed.username}${parsed.password?":"+parsed.password:""}`);let committish=null,user=null,project=null,defaultRepresentation=null;try{if(gitHostShortcut){let pathname=parsed.pathname.startsWith("/")?parsed.pathname.slice(1):parsed.pathname,firstAt=pathname.indexOf("@");firstAt>-1&&(pathname=pathname.slice(firstAt+1));let lastSlash=pathname.lastIndexOf("/");lastSlash>-1?(user=decodeURIComponent(pathname.slice(0,lastSlash)),user||(user=null),project=decodeURIComponent(pathname.slice(lastSlash+1))):project=decodeURIComponent(pathname),project.endsWith(".git")&&(project=project.slice(0,-4)),parsed.hash&&(committish=decodeURIComponent(parsed.hash.slice(1))),defaultRepresentation="shortcut"}else{if(!gitHostInfo.protocols.includes(parsed.protocol))return;let segments=gitHostInfo.extract(parsed);if(!segments)return;user=segments.user&&decodeURIComponent(segments.user),project=decodeURIComponent(segments.project),committish=decodeURIComponent(segments.committish),defaultRepresentation=protocols[parsed.protocol]?.name||parsed.protocol.slice(0,-1)}}catch(err){if(err instanceof URIError)return;throw err}return[gitHostName,user,auth,project,committish,defaultRepresentation,opts]}}});var require_lib=__commonJS({"node_modules/hosted-git-info/lib/index.js"(exports,module){"use strict";var{LRUCache}=require_index_min(),hosts=require_hosts(),fromUrl=require_from_url(),parseUrl=require_parse_url(),cache2=new LRUCache({max:1e3});function unknownHostedUrl(url){try{let{protocol,hostname,pathname}=new URL(url);if(!hostname)return null;let proto=/(?:git\+)http:$/.test(protocol)?"http:":"https:",path2=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path2}`}catch{return null}}var GitHost=class _GitHost{constructor(type,user,auth,project,committish,defaultRepresentation,opts={}){Object.assign(this,_GitHost.#gitHosts[type],{type,user,auth,project,committish,default:defaultRepresentation,opts})}static#gitHosts={byShortcut:{},byDomain:{}};static#protocols={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(name,host){_GitHost.#gitHosts[name]=host,_GitHost.#gitHosts.byDomain[host.domain]=name,_GitHost.#gitHosts.byShortcut[`${name}:`]=name,_GitHost.#protocols[`${name}:`]={name}}static fromUrl(giturl,opts){if(typeof giturl!="string")return;let key=giturl+JSON.stringify(opts||{});if(!cache2.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache2.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache2.get(key)}static fromManifest(manifest,opts={}){if(!manifest||typeof manifest!="object")return;let r=manifest.repository,rurl=r&&(typeof r=="string"?r:typeof r=="object"&&typeof r.url=="string"?r.url:null);if(!rurl)throw new Error("no repository");let info=rurl&&_GitHost.fromUrl(rurl.replace(/^git\+/,""),opts)||null;if(info)return info;let unk=unknownHostedUrl(rurl);return _GitHost.fromUrl(unk,opts)||unk}static parseUrl(url){return parseUrl(url)}#fill(template,opts){if(typeof template!="function")return null;let options={...this,...this.opts,...opts};options.path||(options.path=""),options.path.startsWith("/")&&(options.path=options.path.slice(1)),options.noCommittish&&(options.committish=null);let result=template(options);return options.noGitPlus&&result.startsWith("git+")?result.slice(4):result}hash(){return this.committish?`#${this.committish}`:""}ssh(opts){return this.#fill(this.sshtemplate,opts)}sshurl(opts){return this.#fill(this.sshurltemplate,opts)}browse(path2,...args){return typeof path2!="string"?this.#fill(this.browsetemplate,path2):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path2}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path2})}browseFile(path2,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path2}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path2})}docs(opts){return this.#fill(this.docstemplate,opts)}bugs(opts){return this.#fill(this.bugstemplate,opts)}https(opts){return this.#fill(this.httpstemplate,opts)}git(opts){return this.#fill(this.gittemplate,opts)}shortcut(opts){return this.#fill(this.shortcuttemplate,opts)}path(opts){return this.#fill(this.pathtemplate,opts)}tarball(opts){return this.#fill(this.tarballtemplate,{...opts,noCommittish:!1})}file(path2,opts){return this.#fill(this.filetemplate,{...opts,path:path2})}edit(path2,opts){return this.#fill(this.edittemplate,{...opts,path:path2})}getDefaultRepresentation(){return this.default}toString(opts){return this.default&&typeof this[this.default]=="function"?this[this.default](opts):this.sshurl(opts)}};for(let[name,host]of Object.entries(hosts))GitHost.addHost(name,host);module.exports=GitHost}});var require_ignore=__commonJS({"node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object,key,value)=>(Object.defineProperty(object,key,{value}),value),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY,prev=EMPTY;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match2=>`\\${match2}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str)=>index+6<str.length?str.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":"\\/.+","*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match2,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match2,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match2,range2,endEscape,close)=>`\\[${range2}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",TRAILING_WILD_CARD_REPLACERS={[MODE_IGNORE](_,p1){return`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`},[MODE_CHECK_IGNORE](_,p1){return`${p1?`${p1}[^/]*`:"[^/]*"}(?=$|\\/$)`}},WILDCARD="[^\\/]*",pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${run[at+1].single})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match2,index)=>sources[index]):replaced},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path2=>{let end=path2.length-1,index=path2.lastIndexOf(SLASH,path2[end]===SLASH?end-1:end);return index<0?path2:path2.slice(index+1)},parentOf=path2=>{if(path2.charCodeAt(0)===SLASH_CODE||path2.indexOf(DOUBLE_SLASH)>=0){let slices=path2.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path2.length-1,cut=path2.lastIndexOf(SLASH,path2.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path2.slice(0,cut+1)},isString=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str=pinWildcards(this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,TRAILING_WILD_CARD_REPLACERS[mode])),regex=this.ignoreCase?new RegExp(str,"i"):new RegExp(str);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added}test(path2,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename4=shortcut?basenameOf(path2):path2;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename4:path2)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path2,originalPath,doThrow)=>isString(path2)?path2?checkPath.isNotRelative(path2)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path2=>{let first=path2.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path2.length===1)return!0;let second=path2.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path2.length===2||path2.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache2,checkUnignored){let path2=originalPath&&checkPath.convert(originalPath);return checkPath(path2,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path2,cache2,checkUnignored)}checkIgnore(path2){if(path2.charCodeAt(path2.length-1)!==SLASH_CODE)return this.test(path2);let parentPath=parentOf(path2);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path2,!1,MODE_CHECK_IGNORE)}_t(path2,cache2,checkUnignored){if(path2 in cache2)return cache2[path2];let parentPath=parentOf(path2),parent=parentPath?this._t(parentPath,cache2,checkUnignored):UNDEFINED;return cache2[path2]=parent&&parent.ignored?parent:this._rules.test(path2,checkUnignored,MODE_IGNORE)}ignores(path2){return this._test(path2,this._ignoreCache,!1).ignored}createFilter(){return path2=>!this.ignores(path2)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path2){return this._test(path2,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path2=>checkPath(path2&&checkPath.convert(path2),path2,RETURN_FALSE),setupWindows=()=>{let makePosix=str=>/^\\\\\?\\/.test(str)||/["<>|\u0000-\u001F]+/u.test(str)?str:str.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path2=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path2)||isNotRelative(path2)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
3
3
|
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}var PROVIDER_IMAGE_REJECTION_PATTERN=/does not represent a valid image|image_parse_error|invalid_image|unsupported image|could not process image|unable to process input image|image_url'?\.?[^\n]*invalid base64|expected a base64-encoded data url|image was specified using the image\/[a-z]+ media type|unsupported media type for base64 image|invalid data url for image/i;function isProviderImageRejection(errorMessage){return errorMessage!==void 0&&PROVIDER_IMAGE_REJECTION_PATTERN.test(errorMessage)}function rejectedImagePlaceholder(source){return`[Image omitted: the provider rejected this image (${source}) as invalid, so it is no longer sent with the conversation.]`}function field(message,key){return key in message?message[key]:void 0}function contentBlocks2(message){let content=field(message,"content");return Array.isArray(content)?content:[]}function toolCallSource(block){let args=block.arguments;if(typeof args!="object"||args===null)return;let record=args;for(let key of["path","file_path","filePath"]){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value}}function imageSource(message,toolCallSources){if(message.role!=="toolResult")return"an attached image";let toolCallId=field(message,"toolCallId"),known=typeof toolCallId=="string"?toolCallSources.get(toolCallId):void 0;if(known)return known;let toolName=field(message,"toolName");return typeof toolName=="string"?`${toolName} tool result`:"a tool result"}function scanRejectedImages(messages){let toolCallSources=new Map,rejections=new Map,unconfirmed=[];return messages.forEach((message,messageIndex)=>{if(message.role==="assistant"){for(let block of contentBlocks2(message)){let source=block.type==="toolCall"?toolCallSource(block):void 0;source&&typeof block.id=="string"&&toolCallSources.set(block.id,source)}let stopReason=field(message,"stopReason"),errorMessage=field(message,"errorMessage");stopReason==="error"&&isProviderImageRejection(typeof errorMessage=="string"?errorMessage:void 0)?(unconfirmed.length>0&&rejections.set(messageIndex,unconfirmed),unconfirmed=[]):stopReason!=="error"&&stopReason!=="aborted"&&(unconfirmed=[]);return}message.role!=="user"&&message.role!=="toolResult"||contentBlocks2(message).forEach((block,blockIndex)=>{block.type==="image"&&unconfirmed.push({messageIndex,blockIndex,source:imageSource(message,toolCallSources)})})}),rejections}function rejectedImageSources(messages,failedTurn){let failedIndex=messages.lastIndexOf(failedTurn);return(scanRejectedImages(messages).get(failedIndex)??[]).map(image=>image.source)}function omitProviderRejectedImages(messages){let rejected=new Map;for(let images of scanRejectedImages(messages).values())for(let image of images){let blocks=rejected.get(image.messageIndex)??new Map;blocks.set(image.blockIndex,image.source),rejected.set(image.messageIndex,blocks)}return rejected.size===0?messages:messages.map((message,messageIndex)=>{let blocks=rejected.get(messageIndex);if(!blocks)return message;let content=contentBlocks2(message).map((block,blockIndex)=>{let source=blocks.get(blockIndex);return source===void 0?block:{type:"text",text:rejectedImagePlaceholder(source)}});return{...message,content}})}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
4
4
|
|
|
5
5
|
<summary>
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{HOST_DAEMON_LAYOUT,ProcessIdentityUnreadableError,canonicalEndpointPath,claimOwnerIsLive,createHostDaemonPaths,generationPaths,hostDaemonDirectoryPaths,parseDaemonPidFile,parseJson,processMatchesPidFile,readFileOrUndefined,readSessionPathClaims,readSocketSecret,resolveSocketTransportAddress,socketNamesDirectory,socketSecretPath}from"./chunk-22DAHAHO.js";import{readdir}from"node:fs/promises";import{basename as basename2,join}from"node:path";import{createHash}from"node:crypto";import{basename}from"node:path";var TUI_SOCKET_NAME=/^t-[0-9a-f]{16}\.sock$/;function tuiSocketName(instanceId){return`t-${createHash("sha256").update(instanceId,"utf8").digest("hex").slice(0,16)}.sock`}function isTuiControlSocket(socket){return TUI_SOCKET_NAME.test(basename(socket))}function socketNeedsHandshake(socket,platform=process.platform){return platform==="win32"||isTuiControlSocket(socket)}var ENDPOINT_DIRECTORY_NAME=/^[0-9a-f]{16}$/;async function listHostEndpoints(agentDir){let flatDir=join(agentDir,"rpc-host-daemon");if(parseJson(await readFileOrUndefined(join(flatDir,"layout.json")).catch(()=>{}))?.layout!==HOST_DAEMON_LAYOUT)return[];let dirs=(await readdir(flatDir,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isDirectory()&&ENDPOINT_DIRECTORY_NAME.test(entry.name)).map(entry=>join(flatDir,entry.name)).sort(),endpoints=[];for(let dir of dirs)endpoints.push(await identifyEndpoint(dir));return endpoints}async function identifyEndpoint(dir){let paths=hostDaemonDirectoryPaths(dir),named=await recordNaming(paths.endpointFile,dir);if(named!==void 0)return{socket:named.socket,dir,identity:"endpoint",endpoint_kind:endpointKindOf(named.record)};let booted=await recordNaming(paths.settingsFile,dir);if(booted!==void 0)return{socket:booted.socket,dir,identity:"settings",endpoint_kind:"rpc_host"};let generations=await readdir(paths.generationsDir).catch(()=>[]);for(let instanceId of generations.sort()){let recorded=await recordNaming(join(paths.generationsDir,instanceId,"settings.json"),dir);if(recorded!==void 0)return{socket:recorded.socket,dir,identity:"generation-settings",endpoint_kind:"rpc_host"}}return{socket:null,dir,identity:"unknown",endpoint_kind:"rpc_host"}}async function endpointKindOfSocket(socket,agentDir){if(isTuiControlSocket(socket))return"tui";let paths=createHostDaemonPaths({socket,agentDir}),named=await recordNaming(paths.endpointFile,paths.dir);return named===void 0?"rpc_host":endpointKindOf(named.record)}function endpointKindOf(record){return record.endpoint_kind==="tui"?"tui":"rpc_host"}async function recordNaming(file,dir){let record=parseJson(await readFileOrUndefined(file).catch(()=>{})),socket=record?.socket;if(!(record===void 0||typeof socket!="string"||socket===""))return socketNamesDirectory(socket,basename2(dir))?{socket,record}:void 0}import{lstat as lstat2,rm}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";import{createHash as createHash2}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join as join2}from"node:path";import{stat}from"node:fs/promises";var LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100};async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error)&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error}}}async function rejectLegacyDirectory(lockPath){try{if((await stat(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error){if(error instanceof LegacyLockArtifactError||error.code!=="ENOENT")throw error}}function isBusy(error){let message=error instanceof Error?error.message:String(error);return/busy|locked/i.test(message)||error?.code==="SQLITE_BUSY"}var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join2(tmpdir(),"senpi-rpc-host-locks",createSocketLockName(socket))}async function acquireHostEnsureLock(socket,waitMs){let lockTarget=hostEnsureLockTarget(socket);return await mkdir(dirname(lockTarget),{recursive:!0}),await writeFile(lockTarget,"",{flag:"a",mode:384}),acquireOwnershipSafeLock(`${lockTarget}.lock`,hostEnsureLockOptions(waitMs))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash2("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}import{lstat,readdir as readdir2}from"node:fs/promises";import{createConnection}from"node:net";import{basename as basename3,dirname as dirname2,join as join3}from"node:path";var SOCKET_PROBE_TIMEOUT_MS=2e3;async function endpointInUse(paths,socket){if(await anyGenerationLive(paths))return{inUse:"live_generation"};for(let claim of await readSessionPathClaims(paths.reservationsDir))if(await claimOwnerIsLive(claim.owner))return{inUse:"live_claim"};let silence=await socketSilence(socket);if(silence===void 0)return{inUse:"reachable"};let successors=(await socketSiblings(socket)).filter(name=>name.startsWith(`${basename3(socket)}.next-`));for(let successor of successors)if(await socketSilence(join3(dirname2(socket),successor))===void 0)return{inUse:"reachable"};return{inUse:void 0,silence}}async function socketSiblings(socket){let name=basename3(socket);return(await readdir2(dirname2(socket)).catch(()=>[])).filter(entry=>entry.startsWith(`${name}.next-`)||entry.startsWith(`${name}.shield-`))}async function anyGenerationLive(paths){for(let instanceId of await readdir2(paths.generationsDir).catch(()=>[])){let record=generationRecord(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));if(record!==void 0&&await recordIsLive(record))return!0}return!1}function generationRecord(text){if(text===void 0)return;let record=parseDaemonPidFile(text);if(record!==void 0)return record;let pid=parseJson(text)?.pid;return typeof pid=="number"&&Number.isInteger(pid)&&pid>0?{pid,processStartTime:null}:void 0}async function recordIsLive(record){try{return await processMatchesPidFile(record)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}}async function socketSilence(socket){let secret;return process.platform==="win32"&&(secret=await readSocketSecret(socketSecretPath(socket)).catch(()=>{}),secret===void 0)?"socket_absent":new Promise(resolveProbe=>{let connection=createConnection(resolveSocketTransportAddress(socket,process.platform,secret)),finish=value=>{clearTimeout(timeout),connection.destroy(),resolveProbe(value)},timeout=setTimeout(()=>finish(void 0),SOCKET_PROBE_TIMEOUT_MS);connection.once("connect",()=>finish(void 0)),connection.once("error",error=>{error.code==="ECONNREFUSED"?refusedBySocket(socket).then(finish):error.code==="ENOENT"?finish("socket_absent"):finish(void 0)})})}async function refusedBySocket(socket){if(process.platform==="win32"||socket.startsWith("\0"))return"socket_refused";try{return(await lstat(socket)).isSocket()?"socket_refused":void 0}catch(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"?"socket_absent":void 0}}var GC_LOCK_WAIT_MS=2e3;async function gcHostEndpoints(agentDir,options={}){let removed=[],kept=[],wanted=kind=>options.kinds===void 0||options.kinds.includes(kind),legacy=wanted("rpc_host")?await legacyFlatDirectory(agentDir):void 0;legacy!==void 0&&kept.push({socket:null,dir:legacy,reason:"legacy_layout"});for(let endpoint of await listHostEndpoints(agentDir)){if(!wanted(endpoint.endpoint_kind))continue;if(endpoint.socket===null){kept.push({socket:null,dir:endpoint.dir,reason:"unknown_identity"});continue}let entry={socket:endpoint.socket,dir:endpoint.dir};try{let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,options);outcome.removed?outcome.skipped.length===0?removed.push({...entry,reason:outcome.reason}):removed.push({...entry,reason:outcome.reason,skipped:outcome.skipped}):kept.push({...entry,reason:outcome.reason})}catch(error){kept.push({...entry,reason:"failed",error:error instanceof Error?error.message:String(error)})}}return{removed,kept}}async function gcEndpoint(socket,dir,options){let release=await acquireEnsureLock(socket);if(release===void 0)return{removed:!1,reason:"locked"};try{await options._test?.afterLockAcquired?.(socket);let evidence=await endpointInUse(hostDaemonDirectoryPaths(dir),socket);if(evidence.inUse!==void 0)return{removed:!1,reason:evidence.inUse};let skipped=await removeEndpoint(socket,dir);return{removed:!0,reason:evidence.silence,skipped}}finally{await release()}}async function removeEndpoint(socket,dir){let skipped=[];for(let sibling of await socketSiblings(socket)){let path=join4(dirname3(socket),sibling),entry=await lstat2(path).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});entry?.isDirectory()?skipped.push({path,type:"directory"}):entry!==void 0&&await rm(path,{force:!0})}return await rm(socket,{force:!0}),await rm(dir,{recursive:!0,force:!0}),skipped}async function acquireEnsureLock(socket){return acquireHostEnsureLock(socket,GC_LOCK_WAIT_MS).catch(()=>{})}async function legacyFlatDirectory(agentDir){let flatDir=join4(agentDir,"rpc-host-daemon");return parseJson(await readFileOrUndefined(join4(flatDir,"layout.json")).catch(()=>{}))?.layout===HOST_DAEMON_LAYOUT?void 0:await readFileOrUndefined(join4(flatDir,"host.pid")).catch(()=>{})!==void 0?flatDir:void 0}export{tuiSocketName,socketNeedsHandshake,listHostEndpoints,endpointKindOfSocket,acquireOwnershipSafeLock,hostEnsureLockTarget,acquireHostEnsureLock,hostEnsureLockOptions,anyGenerationLive,gcHostEndpoints,gcEndpoint};
|
|
2
|
+
import{HOST_DAEMON_LAYOUT,ProcessIdentityUnreadableError,canonicalEndpointPath,claimOwnerIsLive,createHostDaemonPaths,generationPaths,hostDaemonDirectoryPaths,parseDaemonPidFile,parseJson,processMatchesPidFile,readFileOrUndefined,readSessionPathClaims,readSocketSecret,resolveSocketTransportAddress,socketNamesDirectory,socketSecretPath}from"./chunk-LUWWM7GA.js";import{readdir}from"node:fs/promises";import{basename as basename2,join}from"node:path";import{createHash}from"node:crypto";import{basename}from"node:path";var TUI_SOCKET_NAME=/^t-[0-9a-f]{16}\.sock$/;function tuiSocketName(instanceId){return`t-${createHash("sha256").update(instanceId,"utf8").digest("hex").slice(0,16)}.sock`}function isTuiControlSocket(socket){return TUI_SOCKET_NAME.test(basename(socket))}function socketNeedsHandshake(socket,platform=process.platform){return platform==="win32"||isTuiControlSocket(socket)}var ENDPOINT_DIRECTORY_NAME=/^[0-9a-f]{16}$/;async function listHostEndpoints(agentDir){let flatDir=join(agentDir,"rpc-host-daemon");if(parseJson(await readFileOrUndefined(join(flatDir,"layout.json")).catch(()=>{}))?.layout!==HOST_DAEMON_LAYOUT)return[];let dirs=(await readdir(flatDir,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isDirectory()&&ENDPOINT_DIRECTORY_NAME.test(entry.name)).map(entry=>join(flatDir,entry.name)).sort(),endpoints=[];for(let dir of dirs)endpoints.push(await identifyEndpoint(dir));return endpoints}async function identifyEndpoint(dir){let paths=hostDaemonDirectoryPaths(dir),named=await recordNaming(paths.endpointFile,dir);if(named!==void 0)return{socket:named.socket,dir,identity:"endpoint",endpoint_kind:endpointKindOf(named.record)};let booted=await recordNaming(paths.settingsFile,dir);if(booted!==void 0)return{socket:booted.socket,dir,identity:"settings",endpoint_kind:"rpc_host"};let generations=await readdir(paths.generationsDir).catch(()=>[]);for(let instanceId of generations.sort()){let recorded=await recordNaming(join(paths.generationsDir,instanceId,"settings.json"),dir);if(recorded!==void 0)return{socket:recorded.socket,dir,identity:"generation-settings",endpoint_kind:"rpc_host"}}return{socket:null,dir,identity:"unknown",endpoint_kind:"rpc_host"}}async function endpointKindOfSocket(socket,agentDir){if(isTuiControlSocket(socket))return"tui";let paths=createHostDaemonPaths({socket,agentDir}),named=await recordNaming(paths.endpointFile,paths.dir);return named===void 0?"rpc_host":endpointKindOf(named.record)}function endpointKindOf(record){return record.endpoint_kind==="tui"?"tui":"rpc_host"}async function recordNaming(file,dir){let record=parseJson(await readFileOrUndefined(file).catch(()=>{})),socket=record?.socket;if(!(record===void 0||typeof socket!="string"||socket===""))return socketNamesDirectory(socket,basename2(dir))?{socket,record}:void 0}import{lstat as lstat2,rm}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";import{createHash as createHash2}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join as join2}from"node:path";import{stat}from"node:fs/promises";var LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100};async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error)&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error}}}async function rejectLegacyDirectory(lockPath){try{if((await stat(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error){if(error instanceof LegacyLockArtifactError||error.code!=="ENOENT")throw error}}function isBusy(error){let message=error instanceof Error?error.message:String(error);return/busy|locked/i.test(message)||error?.code==="SQLITE_BUSY"}var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join2(tmpdir(),"senpi-rpc-host-locks",createSocketLockName(socket))}async function acquireHostEnsureLock(socket,waitMs){let lockTarget=hostEnsureLockTarget(socket);return await mkdir(dirname(lockTarget),{recursive:!0}),await writeFile(lockTarget,"",{flag:"a",mode:384}),acquireOwnershipSafeLock(`${lockTarget}.lock`,hostEnsureLockOptions(waitMs))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash2("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}import{lstat,readdir as readdir2}from"node:fs/promises";import{createConnection}from"node:net";import{basename as basename3,dirname as dirname2,join as join3}from"node:path";var SOCKET_PROBE_TIMEOUT_MS=2e3;async function endpointInUse(paths,socket){if(await anyGenerationLive(paths))return{inUse:"live_generation"};for(let claim of await readSessionPathClaims(paths.reservationsDir))if(await claimOwnerIsLive(claim.owner))return{inUse:"live_claim"};let silence=await socketSilence(socket);if(silence===void 0)return{inUse:"reachable"};let successors=(await socketSiblings(socket)).filter(name=>name.startsWith(`${basename3(socket)}.next-`));for(let successor of successors)if(await socketSilence(join3(dirname2(socket),successor))===void 0)return{inUse:"reachable"};return{inUse:void 0,silence}}async function socketSiblings(socket){let name=basename3(socket);return(await readdir2(dirname2(socket)).catch(()=>[])).filter(entry=>entry.startsWith(`${name}.next-`)||entry.startsWith(`${name}.shield-`))}async function anyGenerationLive(paths){for(let instanceId of await readdir2(paths.generationsDir).catch(()=>[])){let record=generationRecord(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));if(record!==void 0&&await recordIsLive(record))return!0}return!1}function generationRecord(text){if(text===void 0)return;let record=parseDaemonPidFile(text);if(record!==void 0)return record;let pid=parseJson(text)?.pid;return typeof pid=="number"&&Number.isInteger(pid)&&pid>0?{pid,processStartTime:null}:void 0}async function recordIsLive(record){try{return await processMatchesPidFile(record)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}}async function socketSilence(socket){let secret;return process.platform==="win32"&&(secret=await readSocketSecret(socketSecretPath(socket)).catch(()=>{}),secret===void 0)?"socket_absent":new Promise(resolveProbe=>{let connection=createConnection(resolveSocketTransportAddress(socket,process.platform,secret)),finish=value=>{clearTimeout(timeout),connection.destroy(),resolveProbe(value)},timeout=setTimeout(()=>finish(void 0),SOCKET_PROBE_TIMEOUT_MS);connection.once("connect",()=>finish(void 0)),connection.once("error",error=>{error.code==="ECONNREFUSED"?refusedBySocket(socket).then(finish):error.code==="ENOENT"?finish("socket_absent"):finish(void 0)})})}async function refusedBySocket(socket){if(process.platform==="win32"||socket.startsWith("\0"))return"socket_refused";try{return(await lstat(socket)).isSocket()?"socket_refused":void 0}catch(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"?"socket_absent":void 0}}var GC_LOCK_WAIT_MS=2e3;async function gcHostEndpoints(agentDir,options={}){let removed=[],kept=[],wanted=kind=>options.kinds===void 0||options.kinds.includes(kind),legacy=wanted("rpc_host")?await legacyFlatDirectory(agentDir):void 0;legacy!==void 0&&kept.push({socket:null,dir:legacy,reason:"legacy_layout"});for(let endpoint of await listHostEndpoints(agentDir)){if(!wanted(endpoint.endpoint_kind))continue;if(endpoint.socket===null){kept.push({socket:null,dir:endpoint.dir,reason:"unknown_identity"});continue}let entry={socket:endpoint.socket,dir:endpoint.dir};try{let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,options);outcome.removed?outcome.skipped.length===0?removed.push({...entry,reason:outcome.reason}):removed.push({...entry,reason:outcome.reason,skipped:outcome.skipped}):kept.push({...entry,reason:outcome.reason})}catch(error){kept.push({...entry,reason:"failed",error:error instanceof Error?error.message:String(error)})}}return{removed,kept}}async function gcEndpoint(socket,dir,options){let release=await acquireEnsureLock(socket);if(release===void 0)return{removed:!1,reason:"locked"};try{await options._test?.afterLockAcquired?.(socket);let evidence=await endpointInUse(hostDaemonDirectoryPaths(dir),socket);if(evidence.inUse!==void 0)return{removed:!1,reason:evidence.inUse};let skipped=await removeEndpoint(socket,dir);return{removed:!0,reason:evidence.silence,skipped}}finally{await release()}}async function removeEndpoint(socket,dir){let skipped=[];for(let sibling of await socketSiblings(socket)){let path=join4(dirname3(socket),sibling),entry=await lstat2(path).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});entry?.isDirectory()?skipped.push({path,type:"directory"}):entry!==void 0&&await rm(path,{force:!0})}return await rm(socket,{force:!0}),await rm(dir,{recursive:!0,force:!0}),skipped}async function acquireEnsureLock(socket){return acquireHostEnsureLock(socket,GC_LOCK_WAIT_MS).catch(()=>{})}async function legacyFlatDirectory(agentDir){let flatDir=join4(agentDir,"rpc-host-daemon");return parseJson(await readFileOrUndefined(join4(flatDir,"layout.json")).catch(()=>{}))?.layout===HOST_DAEMON_LAYOUT?void 0:await readFileOrUndefined(join4(flatDir,"host.pid")).catch(()=>{})!==void 0?flatDir:void 0}export{tuiSocketName,socketNeedsHandshake,listHostEndpoints,endpointKindOfSocket,acquireOwnershipSafeLock,hostEnsureLockTarget,acquireHostEnsureLock,hostEnsureLockOptions,anyGenerationLive,gcHostEndpoints,gcEndpoint};
|
|
@@ -140,7 +140,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
140
140
|
`)}function extractUserMessageText(msg){if(msg.role!=="user")return"";let content=msg.content;return typeof content=="string"?content.trim():content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
141
141
|
`).trim()}function hasUserMessageImages(msg){return msg.role==="user"&&Array.isArray(msg.content)&&msg.content.some(item=>item.type==="image")}function buildCursorRootPromptContent(content){if(typeof content=="string"){let text=content.trim();return text?[{type:"text",text}]:[]}let parts=[];for(let item of content)if(item.type==="text"){let text=item.text.trim();text&&parts.push({type:"text",text})}else parts.push({type:"image",image:`data:${item.mimeType};base64,${item.data}`,mediaType:item.mimeType});return parts}function cursorUserContentKey(content){if(typeof content=="string")return content.trim();let hash=createHash("sha256");for(let item of content)hash.update(item.type),item.type==="text"?hash.update(item.text):(hash.update(item.mimeType),hash.update(item.data));return hash.digest("hex")}function buildCursorAssistantContent(msg){let content=[];for(let item of msg.content)item.type==="text"?item.text&&content.push({type:"text",text:item.text}):item.type==="toolCall"&&content.push({type:"tool-call",toolCallId:item.id,toolName:item.name,args:item.arguments});return content}function findLastUserMessageIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="user")return i;return-1}function buildRootPromptMessagesJson(messages,systemPromptIds,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let entries=[...systemPromptIds],pushJson=obj=>{let bytes=new TextEncoder().encode(JSON.stringify(obj));entries.push(storeCursorBlob(blobStore,bytes))};for(let i=0;i<messages.length&&i!==activeUserMessageIndex;i++){let msg=messages[i];if(msg.role==="user"){let content=buildCursorRootPromptContent(msg.content);if(content.length===0)continue;pushJson({role:"user",content})}else if(msg.role==="assistant"){let content=buildCursorAssistantContent(msg);if(content.length===0)continue;pushJson({role:"assistant",content})}else msg.role==="toolResult"&&pushJson({role:"tool",id:msg.toolCallId,content:[{type:"tool-result",toolName:msg.toolName,toolCallId:msg.toolCallId,result:toolResultToText(msg),...msg.isError?{isError:!0}:{}}]})}return entries}function isPlainRecord(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isJsonValue(value){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isJsonValue);if(!isPlainRecord(value))return!1;for(let key in value)if(!isJsonValue(value[key]))return!1;return!0}function encodeCursorMcpArguments(toolCall){let encoded={};for(let name in toolCall.arguments){let value=toolCall.arguments[name];if(value!==void 0){if(!isJsonValue(value))throw new Error(`Cursor tool argument ${toolCall.name}.${name} is not JSON-serializable`);encoded[name]=toBinary(ValueSchema,fromJson(ValueSchema,value))}}return encoded}function createCursorMcpResult(result){return result.isError?create(McpToolResultSchema,{result:{case:"error",value:create(McpToolErrorSchema,{error:toolResultToText(result)})}}):create(McpToolResultSchema,{result:{case:"success",value:create(McpSuccessSchema,{content:result.content.map(item=>item.type==="text"?create(McpToolResultContentItemSchema,{content:{case:"text",value:create(McpTextContentSchema,{text:item.text})}}):create(McpToolResultContentItemSchema,{content:{case:"image",value:create(McpImageContentSchema,{data:Uint8Array.from(Uint8Array.from(atob(item.data),c=>c.charCodeAt(0))),mimeType:item.mimeType})}}))})}})}function createCursorToolCallStep(toolCall,result){let mcpCall=create(McpToolCallSchema,{args:create(McpArgsSchema,{name:toolCall.name,args:encodeCursorMcpArguments(toolCall),toolCallId:toolCall.id,providerIdentifier:"pi-agent",toolName:toolCall.name}),...result?{result:createCursorMcpResult(result)}:{}});return create(ConversationStepSchema,{message:{case:"toolCall",value:create(ToolCallSchema,{tool:{case:"mcpToolCall",value:mcpCall},toolCallId:toolCall.id})}})}function buildConversationTurns(messages,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let turns=[],historyEnd=activeUserMessageIndex>=0?activeUserMessageIndex:messages.length,toolResults=new Map,pairedToolCallIds=new Set;for(let index=0;index<historyEnd;index++){let message=messages[index];if(message.role==="toolResult")toolResults.set(message.toolCallId,message);else if(message.role==="assistant")for(let item of message.content)item.type==="toolCall"&&pairedToolCallIds.add(item.id)}let i=0;for(;i<messages.length;){let msg=messages[i];if(msg.role!=="user"){i++;continue}if(i===activeUserMessageIndex)break;let userText=extractUserMessageText(msg);if(userText.length===0&&!hasUserMessageImages(msg)){i++;continue}let userMessage=createCursorUserMessage(msg.content,userText,deterministicUuid(`u:${turns.length}:${cursorUserContentKey(msg.content)}`)),userMessageBlobId=storeCursorBlob(blobStore,toBinary(UserMessageSchema,userMessage)),stepBlobIds=[];for(i++;i<messages.length&&messages[i].role!=="user";){let stepMsg=messages[i];if(stepMsg.role==="assistant")for(let item of stepMsg.content){let step;if(item.type==="text"){if(!item.text)continue;step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:item.text})}})}else{if(item.type==="thinking")continue;if(item.type==="toolCall")step=createCursorToolCallStep(item,toolResults.get(item.id));else continue}stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}else if(stepMsg.role==="toolResult"&&!pairedToolCallIds.has(stepMsg.toolCallId)){let text=toolResultToText(stepMsg);if(text){let prefix=stepMsg.isError?"[Tool Error]":"[Tool Result]",step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:`${prefix}
|
|
142
142
|
${text}`})}});stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}}i++}let agentTurn=create(AgentConversationTurnStructureSchema,{userMessage:userMessageBlobId,steps:stepBlobIds}),turn=create(ConversationTurnStructureSchema,{turn:{case:"agentConversationTurn",value:agentTurn}});turns.push(storeCursorBlob(blobStore,toBinary(ConversationTurnStructureSchema,turn)))}return turns}function createCursorUserMessage(content,text,messageId=randomUUID()){let images=typeof content=="string"?[]:extractImages(content);return create(UserMessageSchema,{text,messageId,...images.length>0?{selectedContext:create(SelectedContextSchema,{selectedImages:images})}:{}})}function extractImages(content){return content.filter(item=>item.type==="image").map(image=>create(SelectedImageSchema,{uuid:randomUUID(),mimeType:image.mimeType,dataOrBlobId:{case:"data",value:Uint8Array.from(atob(image.data),c=>c.charCodeAt(0))}}))}function measureCursorModelInputSerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map,total=0;for(let blobId of buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex))total+=readCursorBlob(blobStore,blobId).byteLength;return total}function measureCursorHistorySerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){return buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex).reduce((total,bytes)=>total+bytes.byteLength,0)}function buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map;return buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex),buildConversationTurns(messages,blobStore,activeUserMessageIndex),[...blobStore.values()]}function piReadArgs(path,offset,limit){return limit!==void 0&&Math.floor(limit)<=0?null:{path,offset:offset!==void 0?Math.max(1,Math.floor(offset)):void 0,limit:limit!==void 0?Math.floor(limit):void 0}}function piLsPath(basePath){return basePath||"."}function piLimit(limit){return limit===void 0?void 0:Math.max(1,Math.floor(limit))}function piTimeout(timeout){return timeout!==void 0&&timeout>=0?timeout:void 0}function composeShellCommand(command,workingDirectory){return workingDirectory?`cd ${`'${workingDirectory.replace(/'/g,"'\\''")}'`} && { ${command}
|
|
143
|
-
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-2OVOFKEU.js"),import("./anthropic-messages-
|
|
143
|
+
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-2OVOFKEU.js"),import("./anthropic-messages-4MNFPQ66.js")]),headers=providerHeadersToRecord(options.headers),client=new Anthropic({apiKey:options.apiKey??null,baseURL:anthropicModel.baseUrl,dangerouslyAllowBrowser:!0,fetch:options.fetch,defaultHeaders:{...anthropicModel.headers,...headers}}),params=buildAnthropicWarmPromptCacheParams(anthropicModel,context,options),transformed=await options.onPayload?.(params,anthropicModel,{model:anthropicModel,headers});transformed!==void 0&&(params=transformed);let sanitized={...params};delete sanitized.stream,delete sanitized.thinking,delete sanitized.output_config,delete sanitized.tool_choice,sanitized.max_tokens=0;let usageRaw=(await client.beta.messages.create(sanitized,{maxRetries:0,...options.signal?{signal:options.signal}:{},...options.timeoutMs!==void 0?{timeout:options.timeoutMs}:{}})).usage;return{supported:!0,usage:{input:usageRaw.input_tokens,output:usageRaw.output_tokens,cacheRead:usageRaw.cache_read_input_tokens??0,cacheWrite:usageRaw.cache_creation_input_tokens??0},usageRaw}}var DEFAULT_API="faux",DEFAULT_PROVIDER="faux",DEFAULT_MODEL_ID="faux-1",DEFAULT_MODEL_NAME="Faux Model",DEFAULT_BASE_URL="http://localhost:0",DEFAULT_MIN_TOKEN_SIZE=3,DEFAULT_MAX_TOKEN_SIZE=5,DEFAULT_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function fauxText(text){return{type:"text",text}}function fauxThinking(thinking){return{type:"thinking",thinking}}function fauxToolCall(name,arguments_,options={}){return{type:"toolCall",id:options.id??randomId("tool"),name,arguments:arguments_}}function normalizeFauxAssistantContent(content){return typeof content=="string"?[fauxText(content)]:Array.isArray(content)?content:[content]}function fauxAssistantMessage(content,options={}){return{role:"assistant",content:normalizeFauxAssistantContent(content),api:DEFAULT_API,provider:DEFAULT_PROVIDER,model:DEFAULT_MODEL_ID,usage:DEFAULT_USAGE,stopReason:options.stopReason??"stop",...options.stopDetails===void 0?{}:{stopDetails:options.stopDetails},...options.deferred===void 0?{}:{deferred:options.deferred},...options.errorMessage===void 0?{}:{errorMessage:options.errorMessage},...options.abortSource===void 0?{}:{abortSource:options.abortSource},...options.responseId===void 0?{}:{responseId:options.responseId},timestamp:options.timestamp??Date.now()}}function estimateTokens(text){return Math.ceil(text.length/4)}function randomId(prefix){return`${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function cloneStreamOptionsForLog(options){if(options)return{...options}}function cloneToolForLog(tool){return{name:tool.name,description:tool.description,parameters:structuredClone(tool.parameters),...tool.freeform?{freeform:structuredClone(tool.freeform)}:{}}}function toLoggedContext(transcript){let systemPrompt=getCurrentSystemPrompt(transcript.messages),tools=getCurrentTools(transcript.messages);return{...systemPrompt?{systemPrompt}:{},messages:structuredClone(transcript.messages.filter(message=>message.role!=="system")),...tools.length>0?{tools:tools.map(cloneToolForLog)}:{},...transcript.activeToolNames?{activeToolNames:[...transcript.activeToolNames]}:{}}}function contentToText(content){return typeof content=="string"?content:content.map(block=>block.type==="text"?block.text:`[image:${block.mimeType}:${block.data.length}]`).join(`
|
|
144
144
|
`)}function assistantContentToText(content){return content.map(block=>block.type==="text"?block.text:block.type==="thinking"?block.thinking:block.type==="providerNative"?"":`${block.name}:${JSON.stringify(block.arguments)}`).join(`
|
|
145
145
|
`)}function toolResultToText2(message){return[message.toolName,...message.content.map(block=>contentToText([block]))].join(`
|
|
146
146
|
`)}function messageToText(message){return message.role==="system"?[getSystemMessageText(message),...message.toolsRemoved?.map(tool=>`tool-:${JSON.stringify(tool)}`)??[],...message.toolsAdded?.map(tool=>`tool+:${JSON.stringify(tool)}`)??[]].filter(part=>part.length>0).join(`
|
|
@@ -323,4 +323,4 @@ ${yamlBody.length>0?yamlBody:"null"}
|
|
|
323
323
|
`).map(line=>` ${line}`),"</tool_response>"].join(`
|
|
324
324
|
`)}function parseYamlXmlGeneratedText(text,tools,options){if(tools.length===0||text.length===0)return[];let parsedToolCalls=[],toolNames=tools.map(tool=>tool.name),cursor=0;for(;cursor<text.length;){let openingTag=findEarliestXmlToolTag(text.slice(cursor),toolNames);if(!openingTag)break;let absoluteIndex=cursor+openingTag.index;if(openingTag.selfClosing){parsedToolCalls.push({name:openingTag.name,arguments:{}}),cursor=absoluteIndex+openingTag.tag.length;continue}let contentStart=absoluteIndex+openingTag.tag.length,closingTagEnd=findClosingTagEnd(text,contentStart,openingTag.name);if(closingTagEnd===-1)break;let closingTagText=text.slice(contentStart,closingTagEnd),closingTagIndex=new RegExp(`</\\s*${escapeRegExp4(openingTag.name)}\\s*>`).exec(closingTagText)?.index;if(closingTagIndex===void 0){cursor=closingTagEnd;continue}let yamlContent=closingTagText.slice(0,closingTagIndex),parsedArguments=parseYamlMapping(yamlContent);parsedArguments!==null?parsedToolCalls.push({name:openingTag.name,arguments:parsedArguments}):options?.onError?.("Could not process YAML XML tool call, keeping original text.",{toolCall:text.slice(absoluteIndex,closingTagEnd)}),cursor=closingTagEnd}return parsedToolCalls}function createYamlXmlStreamParser(tools,options){let toolNames=tools.map(tool=>tool.name),buffer="",currentToolState=null,nextToolCallIndex=0;function emitSnapshot(events,yamlContent){if(!currentToolState)return;let parsedArguments=parseYamlMapping(yamlContent);if(parsedArguments===null)return;let snapshot=JSON.stringify(parsedArguments);snapshot==="{}"||snapshot===currentToolState.lastArgumentsSnapshot||(currentToolState.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id}),currentToolState.lastArgumentsSnapshot=snapshot,events.push({type:"toolcall_delta",index:currentToolState.index,argumentsDelta:snapshot}))}function processBuffer(){let events=[];for(;buffer.length>0;){if(currentToolState){let closingTagMatch=new RegExp(`</\\s*${escapeRegExp4(currentToolState.name)}\\s*>`).exec(buffer);if(!closingTagMatch||closingTagMatch.index===void 0){emitSnapshot(events,buffer);break}let yamlContent=buffer.slice(0,closingTagMatch.index),originalCallText=`<${currentToolState.name}>${yamlContent}${closingTagMatch[0]}`,parsedArguments=parseYamlMapping(yamlContent);if(buffer=buffer.slice(closingTagMatch.index+closingTagMatch[0].length),parsedArguments===null){options?.onError?.("Could not process YAML XML tool call, keeping original text.",{toolCall:originalCallText}),currentToolState.lastArgumentsSnapshot!==null&&events.push({type:"toolcall_end",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id,arguments:{},incomplete:!0,errorMessage:"Tool call arguments could not be parsed"}),shouldEmitRawToolCallTextOnError4(options)&&events.push({type:"text",text:originalCallText}),currentToolState=null;continue}emitSnapshot(events,yamlContent),currentToolState.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id}),events.push({type:"toolcall_end",index:currentToolState.index,name:currentToolState.name,id:currentToolState.id,arguments:parsedArguments}),currentToolState=null;continue}let openingTag=findEarliestXmlToolTag(buffer,toolNames);if(!openingTag){let textLength=getSafeXmlTextLength(buffer,toolNames);if(textLength===0)break;events.push({type:"text",text:buffer.slice(0,textLength)}),buffer=buffer.slice(textLength);continue}if(openingTag.index>0&&events.push({type:"text",text:buffer.slice(0,openingTag.index)}),buffer=buffer.slice(openingTag.index+openingTag.tag.length),openingTag.selfClosing){let id=`yaml-xml-tool-${nextToolCallIndex}`,index=nextToolCallIndex;nextToolCallIndex+=1,events.push({type:"toolcall_start",index,name:openingTag.name,id}),events.push({type:"toolcall_end",index,name:openingTag.name,id,arguments:{}});continue}currentToolState={id:`yaml-xml-tool-${nextToolCallIndex}`,index:nextToolCallIndex,name:openingTag.name,lastArgumentsSnapshot:null},nextToolCallIndex+=1}return events}return{feed(textDelta){return textDelta.length===0?[]:(buffer+=textDelta,processBuffer())},finish(){let events=processBuffer();if(!currentToolState&&buffer.length>0&&(events.push({type:"text",text:buffer}),buffer=""),currentToolState){let state=currentToolState,parsedArguments=parseYamlMapping(buffer),tool=tools.find(candidate=>candidate.name===state.name),validatedArguments=null;if(parsedArguments!==null&&tool)try{validatedArguments=validateToolArguments(tool,{type:"toolCall",id:state.id,name:state.name,arguments:parsedArguments})}catch{validatedArguments=null}validatedArguments!==null?(emitSnapshot(events,buffer),state.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:state.index,name:state.name,id:state.id}),events.push({type:"toolcall_end",index:state.index,name:state.name,id:state.id,arguments:validatedArguments})):(state.lastArgumentsSnapshot===null&&events.push({type:"toolcall_start",index:state.index,name:state.name,id:state.id}),events.push({type:"toolcall_end",index:state.index,name:state.name,id:state.id,arguments:parsedArguments??{},incomplete:!0,errorMessage:"Tool call was truncated mid-arguments"}),options?.onError?.("Could not complete streaming YAML XML tool call at finish.",{protocol:"yaml-xml",retainedLength:buffer.length})),buffer="",currentToolState=null}return events}}}var hermesProtocol={formatToolsSystemPrompt:hermesFormatToolsSystemPrompt,formatToolResponse:hermesFormatToolResponse,formatToolCall:hermesFormatToolCall,parseGeneratedText:hermesParseGeneratedText,createStreamParser:hermesCreateStreamParser},morphXmlProtocol={formatToolsSystemPrompt:morphXmlFormatToolsSystemPrompt,formatToolResponse:morphXmlFormatToolResponse,formatToolCall:morphXmlFormatToolCall,parseGeneratedText:parseMorphXmlGeneratedText,createStreamParser:createMorphXmlStreamParser},yamlXmlProtocol={formatToolsSystemPrompt:yamlXmlFormatToolsSystemPrompt,formatToolResponse:yamlXmlFormatToolResponse,formatToolCall:yamlXmlFormatToolCall,parseGeneratedText:parseYamlXmlGeneratedText,createStreamParser:createYamlXmlStreamParser},gemma4Protocol={formatToolsSystemPrompt:gemma4FormatToolsSystemPrompt,formatToolResponse:gemma4FormatToolResponse,formatToolCall:gemma4FormatToolCall,parseGeneratedText:gemma4ParseGeneratedText,createStreamParser:gemma4CreateStreamParser},antmlProtocol={formatToolsSystemPrompt:antmlFormatToolsSystemPrompt,formatToolResponse:antmlFormatToolResponse,formatToolCall:antmlFormatToolCall,parseGeneratedText:parseAntmlGeneratedText,createStreamParser:createAntmlStreamParser},kimiXtmlProtocol={formatToolsSystemPrompt:kimiXtmlFormatToolsSystemPrompt,formatToolResponse:kimiXtmlFormatToolResponse,formatToolCall:kimiXtmlFormatToolCall,parseGeneratedText:parseKimiXtmlGeneratedText,createStreamParser:createKimiXtmlStreamParser},anthropicXmlProtocol={formatToolsSystemPrompt:anthropicXmlFormatToolsSystemPrompt,formatToolResponse:anthropicXmlFormatToolResponse,formatToolCall:anthropicXmlFormatToolCall,parseGeneratedText:parseAnthropicXmlGeneratedText,createStreamParser:createAnthropicXmlStreamParser},protocolRegistry={"anthropic-xml":anthropicXmlProtocol,antml:antmlProtocol,hermes:hermesProtocol,xml:morphXmlProtocol,"morph-xml":morphXmlProtocol,"yaml-xml":yamlXmlProtocol,"gemma4-delimiter":gemma4Protocol,"kimi-xtml":kimiXtmlProtocol};function getProtocol(format){let protocol=protocolRegistry[format];if(!protocol)throw new Error(`Unsupported tool call format: ${format}`);return protocol}function transformContext(context,protocol){let transcript=normalizeContext(context),tools=getCurrentTools(transcript.messages),toolPrompt=tools.length>0?protocol.formatToolsSystemPrompt(tools):"",initial=getInitialSystemMessage(transcript.messages),head=initial?withoutToolDeclarations(initial):void 0,messages=[];if(toolPrompt){let leading=head??{role:"system",content:"",timestamp:0},basePrompt=contentText(leading.content);messages.push({...leading,content:basePrompt?`${toolPrompt}
|
|
325
325
|
|
|
326
|
-
${basePrompt}`:toolPrompt})}else head&&hasSystemContent(head)&&messages.push(head);for(let message of initial?transcript.messages.slice(1):transcript.messages){if(message.role==="system"){let stripped=withoutToolDeclarations(message);hasSystemContent(stripped)&&messages.push(stripped);continue}messages.push(transformMessage(message,protocol))}return{messages}}function withoutToolDeclarations(message){return{role:"system",content:message.content,...message.sections?{sections:message.sections}:{},timestamp:message.timestamp}}function hasSystemContent(message){return contentText(message.content).length>0||Object.keys(message.sections??{}).length>0}function transformMessage(message,protocol){switch(message.role){case"assistant":return transformAssistantMessage(message,protocol);case"toolResult":return transformToolResultMessage(message,protocol);default:return message}}function transformAssistantMessage(message,protocol){if(!message.content.some(block=>block.type==="toolCall"))return message;let newContent=[];for(let block of message.content)switch(block.type){case"text":{newContent.push(block);break}case"thinking":{newContent.push(block);break}case"toolCall":{let toolCallText=protocol.formatToolCall(block.name,block.arguments);newContent.push({type:"text",text:toolCallText});break}}return{...message,content:newContent}}function transformToolResultMessage(message,protocol){return{role:"user",content:protocol.formatToolResponse(message.toolName,message.toolCallId,message.content),timestamp:message.timestamp}}function wrapStreamWithToolCallMiddleware(innerStream,protocol,tools){let outerStream=new AssistantMessageEventStream,parser=protocol.createStreamParser(tools);return(async()=>{let projection=null,sawToolCall=!1,parserHasPendingInput=!1,flushParser=()=>{if(!projection||!parserHasPendingInput)return;let result=projection.projectParserEvents(parser.finish());sawToolCall=sawToolCall||result.sawToolCall,projection.finishText(),parserHasPendingInput=!1};try{for await(let event of innerStream)switch(event.type){case"start":projection=new StreamMessageProjection(outerStream,event.partial),outerStream.push({type:"start",partial:projection.message});break;case"text_start":if(!projection)break;projection.sync(event.partial),projection.startText(event.contentIndex,event.partial.content[event.contentIndex]);break;case"text_delta":{if(!projection)break;projection.sync(event.partial),event.delta.length>0&&(parserHasPendingInput=!0);let result=projection.projectParserEvents(parser.feed(event.delta));sawToolCall=sawToolCall||result.sawToolCall;break}case"text_end":if(!projection)break;projection.sync(event.partial),flushParser();break;case"thinking_start":if(!projection)break;projection.sync(event.partial),projection.startThinking(event.contentIndex,event.partial);break;case"thinking_delta":if(!projection)break;projection.sync(event.partial),projection.projectThinkingDelta(event.contentIndex,event.delta,event.partial);break;case"thinking_end":if(!projection)break;projection.sync(event.partial),projection.finishThinking(event.contentIndex,event.content,event.partial);break;case"done":{projection??=new StreamMessageProjection(outerStream,event.message),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.message,sawToolCall),reason=(sawToolCall||projection.hasFinalizedToolCallContent())&&(event.reason==="stop"||event.reason==="length")?"toolUse":event.reason;outerStream.push({type:"done",reason,message}),outerStream.end();return}case"error":{if(!projection){outerStream.push(event),outerStream.end(event.error);return}projection.sync(event.error),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.error,sawToolCall);if(projection.hasFinalizedToolCallContent()){let recovered={...message,stopReason:"toolUse"};outerStream.push({type:"done",reason:"toolUse",message:recovered}),outerStream.end(recovered);return}outerStream.push({type:"error",reason:event.reason,error:message}),outerStream.end(message);return}case"toolcall_start":case"toolcall_delta":case"toolcall_end":break}let innerMessage=await innerStream.result();projection??=new StreamMessageProjection(outerStream,innerMessage),flushParser(),projection.finalizeDanglingToolCalls(),outerStream.end(projection.finalize(innerMessage,sawToolCall))}catch(error){flushParser(),projection??=new StreamMessageProjection(outerStream,await innerStream.result()),projection.finalizeDanglingToolCalls();let fallback=projection.message;fallback.stopReason="error",fallback.errorMessage=error instanceof Error?error.message:JSON.stringify(error),outerStream.push({type:"error",reason:"error",error:fallback}),outerStream.end()}})(),outerStream}function getToolCallFormat(model){if(model.api!=="openai-completions")return;let format=model.compat?.toolCallFormat;if(format&&(format==="hermes"||format==="xml"||format==="morph-xml"||format==="yaml-xml"||format==="gemma4-delimiter"||format==="anthropic-xml"||format==="antml"||format==="kimi-xtml"))return format}function shouldRecoverTextToolCalls(model){return getToolCallFormat(model)!==void 0?!1:model.recoverTextToolCalls!==void 0?typeof model.recoverTextToolCalls=="boolean"?model.recoverTextToolCalls:!1:model.api==="cursor-agent"?!1:CLAUDE_MODEL_ID_PATTERN.test(model.id)||KIMI_MODEL_ID_PATTERN.test(model.id)}var CLAUDE_MODEL_ID_PATTERN=/(^|[^a-z0-9])claude([^a-z0-9]|$)/i,KIMI_MODEL_ID_PATTERN=/(^|[^a-z0-9])kimi([^a-z0-9]|$)/i;function hasKimiTextToolCallRecovery(model){return KIMI_MODEL_ID_PATTERN.test(model.id)}function wrapStreamWithModelRecovery(innerStream,model,tools){let recoveredStream=hasKimiTextToolCallRecovery(model)?wrapStreamWithKimiThinkingRecovery(innerStream):innerStream;return!shouldRecoverTextToolCalls(model)||tools.length===0?recoveredStream:wrapStreamWithInvokeRecovery(recoveredStream,tools,hasKimiTextToolCallRecovery(model)?{createParser:createXtmlRecoveryStreamParser,protocol:"kimi-xtml"}:void 0)}function cloneTextContent(content){return{type:"text",text:content.text,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}function cloneThinkingContent(content){return{type:"thinking",thinking:content.thinking,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}function cloneToolCall2(toolCall){return{type:"toolCall",id:toolCall.id,name:toolCall.name,arguments:structuredClone(toolCall.arguments),...toolCall.thoughtSignature===void 0?{}:{thoughtSignature:toolCall.thoughtSignature},...toolCall.namespace===void 0?{}:{namespace:toolCall.namespace}}}function cloneStartMessage(message){return{role:"assistant",content:[],api:message.api,provider:message.provider,model:message.model,...message.responseModel===void 0?{}:{responseModel:message.responseModel},...message.responseId===void 0?{}:{responseId:message.responseId},...message.providerThinkingLevel===void 0?{}:{providerThinkingLevel:message.providerThinkingLevel},...message.diagnostics===void 0?{}:{diagnostics:structuredClone(message.diagnostics)},usage:structuredClone(message.usage),stopReason:"pending",timestamp:message.timestamp}}function assertContentIndex(contentIndex){if(!Number.isSafeInteger(contentIndex)||contentIndex<0)throw new Error(`Invalid assistant message frame contentIndex: ${contentIndex}`)}function eventBlock(event){assertContentIndex(event.contentIndex);let block=event.partial.content[event.contentIndex];if(!block)throw new Error(`${event.type} event has no content block at index ${event.contentIndex}`);return block}function serializedArguments(argumentsValue){let serialized=JSON.stringify(argumentsValue);if(serialized===void 0)throw new Error("Tool-call arguments are not JSON-serializable");return serialized}var EMPTY_PARSED_TOOL_ARGUMENTS=serializedArguments(parseStreamingJson(""));function isJsonPrefix(snapshot,current){if(typeof snapshot=="string")return typeof current=="string"&¤t.startsWith(snapshot);if(Array.isArray(snapshot))return Array.isArray(current)&&snapshot.length<=current.length&&snapshot.every((value,index)=>isJsonPrefix(value,current[index]));if(typeof snapshot!="object"||snapshot===null)return Object.is(snapshot,current);if(typeof current!="object"||current===null||Array.isArray(current))return!1;let currentRecord=current;return Object.entries(snapshot).every(([key,value])=>Object.hasOwn(currentRecord,key)&&isJsonPrefix(value,currentRecord[key]))}var AssistantMessageFrameEncoder=class{constructor(){this.started=!1,this.terminal=!1,this.blocks=new Map}encode(event){if(this.terminal)throw new Error(`Assistant message event ${event.type} follows a terminal event`);switch(event.type){case"start":if(this.started)throw new Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cloneStartMessage(event.partial)};case"done":if(!this.started)throw new Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw new Error(`Assistant message ${event.type} event appears before start`);switch(event.type){case"text_start":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"text",coveredChars:content.text.length,deltaChars:0}),{type:"text_start",contentIndex:event.contentIndex,content:cloneTextContent(content)}}case"text_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"text");case"text_end":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"text"),{type:"text_end",contentIndex:event.contentIndex,content:event.content,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}case"thinking_start":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"thinking",coveredChars:content.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:event.contentIndex,content:cloneThinkingContent(content)}}case"thinking_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"thinking");case"thinking_end":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"thinking"),{type:"thinking_end",contentIndex:event.contentIndex,content:event.content,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}case"toolcall_start":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_start event points to ${content.type} block at index ${event.contentIndex}`);let snapshotArguments=serializedArguments(content.arguments),caughtUp=snapshotArguments===EMPTY_PARSED_TOOL_ARGUMENTS;return this.startBlock(event.contentIndex,{kind:"toolCall",caughtUp,catchupJson:"",snapshotArguments:caughtUp?"":snapshotArguments}),{type:"toolcall_start",contentIndex:event.contentIndex,toolCall:cloneToolCall2(content)}}case"toolcall_delta":{let state=this.block(event.contentIndex,"toolCall");if(state.kind!=="toolCall")throw new Error("Unreachable tool-call encoder state");if(state.caughtUp)return event.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:event.contentIndex,delta:event.delta};state.catchupJson+=event.delta;let argumentsValue=parseStreamingJson(state.catchupJson);if(serializedArguments(argumentsValue)!==state.snapshotArguments){let snapshotArguments=parseStreamingJson(state.snapshotArguments);if(!isJsonPrefix(snapshotArguments,argumentsValue))return}state.caughtUp=!0,state.snapshotArguments="";let json=state.catchupJson;return state.catchupJson="",json.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:event.contentIndex,json}}case"toolcall_end":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_end event points to ${content.type} block at index ${event.contentIndex}`);if(event.toolCall.type!=="toolCall")throw new Error(`toolcall_end event has invalid tool call at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:event.contentIndex,id:event.toolCall.id,name:event.toolCall.name,arguments:structuredClone(event.toolCall.arguments),...event.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:event.toolCall.thoughtSignature},...event.toolCall.namespace===void 0?{}:{namespace:event.toolCall.namespace}}}}}startBlock(contentIndex,state){if(assertContentIndex(contentIndex),this.blocks.has(contentIndex))throw new Error(`Assistant message block ${contentIndex} starts more than once`);this.blocks.set(contentIndex,state)}block(contentIndex,kind){assertContentIndex(contentIndex);let state=this.blocks.get(contentIndex);if(state===void 0)throw new Error(`Assistant message ${kind} block ${contentIndex} has not started`);if(state.kind!==kind)throw new Error(`Assistant message block ${contentIndex} is ${state.kind}, not ${kind}`);return state}endBlock(contentIndex,kind){this.block(contentIndex,kind),this.blocks.delete(contentIndex)}encodeTextDelta(contentIndex,delta,kind){let state=this.block(contentIndex,kind);if(state.kind==="toolCall")throw new Error("Unreachable text encoder state");let deltaStart=state.deltaChars;state.deltaChars+=delta.length;let covered=Math.max(0,state.coveredChars-deltaStart);if(covered>=delta.length)return;let uncovered=covered===0?delta:delta.slice(covered);return kind==="text"?{type:"text_delta",contentIndex,delta:uncovered}:{type:"thinking_delta",contentIndex,delta:uncovered}}};function appendBlock(message,states,contentIndex,block,state){if(assertContentIndex(contentIndex),contentIndex!==message.content.length){let reason=contentIndex<message.content.length?"already exists":"would leave a gap";throw new Error(`Cannot start assistant message block at index ${contentIndex}: ${reason}`)}message.content.push(structuredClone(block)),states.set(contentIndex,state)}function activeBlock(message,states,contentIndex,expectedKind,frameType){assertContentIndex(contentIndex);let state=states.get(contentIndex),block=message.content[contentIndex];if(!state||!block)throw new Error(`${frameType} frame has no started block at index ${contentIndex}`);if(state.kind!==expectedKind||block.type!==expectedKind)throw new Error(`${frameType} frame expected ${expectedKind} block at index ${contentIndex}, found ${block.type}`);if(state.ended)throw new Error(`${frameType} frame follows the end of block at index ${contentIndex}`);return{block,state}}function reduceAssistantMessageFrames(frames){let message,frameBeforeStart,states=new Map;for(let frame of frames){if(frame.type==="start"){if(message)throw new Error("Assistant message frame sequence contains more than one start frame");if(frameBeforeStart!==void 0)throw new Error(`${frameBeforeStart} frame appears before the start frame`);message=structuredClone(frame.partial);continue}if(!message){frameBeforeStart??=frame.type;continue}switch(frame.type){case"text_start":if(frame.content.type!=="text")throw new Error(`text_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"text",ended:!1});break;case"text_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text+=frame.delta;break}case"text_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text=frame.content,delete block.textSignature,frame.textSignature!==void 0&&(block.textSignature=frame.textSignature),state.ended=!0;break}case"thinking_start":if(frame.content.type!=="thinking")throw new Error(`thinking_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking+=frame.delta;break}case"thinking_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking=frame.content,delete block.thinkingSignature,delete block.redacted,frame.thinkingSignature!==void 0&&(block.thinkingSignature=frame.thinkingSignature),frame.redacted!==void 0&&(block.redacted=frame.redacted),state.ended=!0;break}case"toolcall_start":if(frame.toolCall.type!=="toolCall")throw new Error(`toolcall_start frame contains ${frame.toolCall.type} content`);appendBlock(message,states,frame.contentIndex,frame.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call checkpoint state");state.json=frame.json,block.arguments=parseStreamingJson(frame.json);break}case"toolcall_delta":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call frame state");state.json+=frame.delta;break}case"toolcall_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.id=frame.id,block.name=frame.name,block.arguments=structuredClone(frame.arguments),delete block.thoughtSignature,delete block.namespace,frame.thoughtSignature!==void 0&&(block.thoughtSignature=frame.thoughtSignature),frame.namespace!==void 0&&(block.namespace=frame.namespace),state.ended=!0;break}}}if(message){for(let[contentIndex,state]of states){if(state.kind!=="toolCall"||state.ended||state.json.length===0)continue;let block=message.content[contentIndex];if(block?.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.arguments=parseStreamingJson(state.json)}return message}}var kCursorExecResolved=Symbol.for("provider.block.cursorExecResolved");function isCursorExecResolved(block){return block?.[kCursorExecResolved]===!0}function copyCursorExecResolved(target,source){source[kCursorExecResolved]===!0&&(target[kCursorExecResolved]=!0)}function dropFailedAssistantTurns(messages){let callIdsByKeptAssistants=new Set,callIdsByFailedAssistants=new Set;for(let message of messages){let assistant=asAssistantTurn(message);if(!assistant)continue;let declared=isFailedStop(assistant.stopReason)?callIdsByFailedAssistants:callIdsByKeptAssistants;for(let block of assistant.content)block.type==="toolCall"&&typeof block.id=="string"&&declared.add(block.id)}for(let id of callIdsByKeptAssistants)callIdsByFailedAssistants.delete(id);return messages.filter(message=>{let assistant=asAssistantTurn(message);return assistant?!isFailedStop(assistant.stopReason):message.role==="toolResult"&&"toolCallId"in message&&typeof message.toolCallId=="string"?!callIdsByFailedAssistants.has(message.toolCallId):!0})}function asAssistantTurn(message){if(message.role==="assistant"&&!(!("content"in message)||!Array.isArray(message.content)))return{stopReason:"stopReason"in message?message.stopReason:void 0,content:message.content}}function isFailedStop(stopReason){return stopReason==="error"||stopReason==="aborted"}var OVERFLOW_PATTERNS=[/^Context window exhausted: /,/^The conversation is too long to resend \(about \d+ tokens, limit \d+\)/,/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/model_max_prompt_tokens_exceeded|exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./,/Model context limit reached\. Conversation size exceeds model capacity\./],CEREBRAS_BODYLESS_OVERFLOW_PATTERN=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,NON_OVERFLOW_PATTERNS=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i,/tokens per (?:min|minute|hour|day)/i,/\bTPM\b/i,/\bRPM\b/i,/quota exceeded/i,/retry (?:after|in) \d/i,/^429\b/,/status code 429/i,/overloaded/i],RESOURCE_EXHAUSTED_PATTERN=/resource.?exhausted/i;function isContextOverflow(message,contextWindow){if(message.stopReason==="error"&&message.errorMessage){let isNonOverflow=NON_OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage));if(!isNonOverflow&&(OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage))||message.provider==="cerebras"&&CEREBRAS_BODYLESS_OVERFLOW_PATTERN.test(message.errorMessage)))return!0;let usage=message.usage,hasTokenEvidence=(usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite)>0;if(!isNonOverflow&&hasTokenEvidence&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)&&(contextWindow===void 0||contextWindow<=0||cursorZeroTokenCount(message)>=contextWindow*.5))return!0}return!!(contextWindow&&message.stopReason==="stop"&&message.usage.input+message.usage.cacheRead>contextWindow||contextWindow&&message.stopReason==="length"&&message.usage.output===0&&message.usage.input+message.usage.cacheRead>=contextWindow*.99)}function isRecoverableLength(message,desiredMaxOutput){return message.stopReason==="length"&&desiredMaxOutput>0&&message.usage.output<desiredMaxOutput}function getOverflowPatterns(){return[...OVERFLOW_PATTERNS]}function cursorZeroTokenCount(message){let usage=message.usage;return usage?usage.totalTokens||(usage.input??0)+(usage.output??0)+(usage.cacheRead??0)+(usage.cacheWrite??0):0}function isCursorPayloadResourceExhausted(message,_estimateTokens){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function isCursorQuotaResourceExhausted(message,contextWindow){let tokens=cursorZeroTokenCount(message);return message.stopReason==="error"&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage||"")&&contextWindow>0&&tokens>0&&tokens<contextWindow*.5}function isCursorZeroTokenResourceExhausted(message){return message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function shouldSkipProviderFallbackForCursorZeroRe(options){return options?.sameModelRemint===!0}function shouldRetryOverflowWithoutCompact(compacted,errorMessage){return compacted?!1:/Nothing to compact/i.test(errorMessage||"")}function cursorOverflowCompactionSettings(settings,provider,reason){return reason!=="overflow"||provider!=="cursor"&&provider!=="cursor-cli-oauth"?settings:{...settings,keepRecentTokens:0,restorationEnabled:!1}}var ANTHROPIC_POLICY_REFUSAL_PATTERN=/This request triggered restrictions on [\s\S]+? and was blocked under Anthropic's Usage Policy\b/i;function isClassifierRefusal(message){return message.stopReason!=="error"&&message.stopReason!=="toolUse"?!1:message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"?!0:message.errorMessage?ANTHROPIC_POLICY_REFUSAL_PATTERN.test(message.errorMessage):!1}var TOOL_RESULT_PLACEHOLDER="Tool output unavailable (context compacted)";function incompleteToolCallRetryText(name,errorMessage){return errorMessage!==void 0?`${errorMessage}${errorMessage.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${name}" was not executed: the response ended before the tool call was complete. Re-issue the tool call with complete arguments.`}function repairOrphanedToolResults(messages){let toolCallIds=new Set,toolResultIds=new Set;for(let message of messages){if(message.role==="assistant")for(let block of message.content)block.type==="toolCall"&&toolCallIds.add(block.id);message.role==="toolResult"&&toolResultIds.add(message.toolCallId)}let output=[],dangling=new Set([...toolCallIds].filter(id=>!toolResultIds.has(id)));for(let message of messages){if(message.role==="toolResult"){if(!toolCallIds.has(message.toolCallId)){output.push({...message,content:[{type:"text",text:TOOL_RESULT_PLACEHOLDER}]});continue}output.push(message);continue}if(output.push(message),message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted")continue;for(let block of message.content){if(block.type!=="toolCall"||!dangling.has(block.id))continue;let incomplete=block.incomplete===!0,text=incomplete?incompleteToolCallRetryText(block.name,block.errorMessage):TOOL_RESULT_PLACEHOLDER;output.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text}],isError:incomplete,timestamp:message.timestamp?message.timestamp+1:Date.now()}),dangling.delete(block.id)}}}return output}function StringEnum(values,options){return typebox_exports.Unsafe({type:"string",enum:values,...options?.description&&{description:options.description},...options?.default&&{default:options.default}})}var INVISIBLE_FORMAT_CHARS=new RegExp("\\p{Cf}","gu");function hasVisibleText(text){return text.replace(INVISIBLE_FORMAT_CHARS,"").trim().length>0}function hasVisibleAssistantContent(message){return message.content.some(block=>block.type==="toolCall"||block.type==="text"&&hasVisibleText(block.text))}export{create,messageDesc,fromBinary,fileDesc,toBinary,measureCursorModelInputSerializedBytes,measureCursorHistorySerializedBytes,piReadArgs,piLsPath,piLimit,piTimeout,composeShellCommand,omitUndefinedArgs,registerPromptCacheWarmer,warmPromptCache,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,getRegisteredFauxProvider,fauxOverflowError,fauxProvider,installProviderScopeAccessor,registerApiProvider,registerBuiltinApiProvider,getApiProvider,getApiProviders,unregisterApiProviders,clearApiProviders,envApiKeyAuth,lazyOAuth,CURSOR_MODEL_CAPABILITIES,parseCursorVariantId,getCursorVariantAlias,getCursorBaseIdForVariant,getCursorCapabilityForBase,deriveCursorVariantAliases,normalizeCursorCatalog,resolveCursorSelectionDescriptor,renderCursorCliModelString,parseEndpointReasoningEfforts,modelSupportsAssistantPrefill,supportsAllowedToolChoice,createXtmlRecoveryStreamParser,wrapStreamWithInvokeRecovery,Compile,compile_exports,validateToolCall,validateToolArguments,require_dist,getProtocol,transformContext,wrapStreamWithToolCallMiddleware,getToolCallFormat,shouldRecoverTextToolCalls,hasKimiTextToolCallRecovery,wrapStreamWithModelRecovery,AssistantMessageFrameEncoder,reduceAssistantMessageFrames,kCursorExecResolved,isCursorExecResolved,copyCursorExecResolved,dropFailedAssistantTurns,isContextOverflow,isRecoverableLength,getOverflowPatterns,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,shouldSkipProviderFallbackForCursorZeroRe,shouldRetryOverflowWithoutCompact,cursorOverflowCompactionSettings,isClassifierRefusal,TOOL_RESULT_PLACEHOLDER,repairOrphanedToolResults,StringEnum,hasVisibleText,hasVisibleAssistantContent};
|
|
326
|
+
${basePrompt}`:toolPrompt})}else head&&hasSystemContent(head)&&messages.push(head);for(let message of initial?transcript.messages.slice(1):transcript.messages){if(message.role==="system"){let stripped=withoutToolDeclarations(message);hasSystemContent(stripped)&&messages.push(stripped);continue}messages.push(transformMessage(message,protocol))}return{messages}}function withoutToolDeclarations(message){return{role:"system",content:message.content,...message.sections?{sections:message.sections}:{},timestamp:message.timestamp}}function hasSystemContent(message){return contentText(message.content).length>0||Object.keys(message.sections??{}).length>0}function transformMessage(message,protocol){switch(message.role){case"assistant":return transformAssistantMessage(message,protocol);case"toolResult":return transformToolResultMessage(message,protocol);default:return message}}function transformAssistantMessage(message,protocol){if(!message.content.some(block=>block.type==="toolCall"))return message;let newContent=[];for(let block of message.content)switch(block.type){case"text":{newContent.push(block);break}case"thinking":{newContent.push(block);break}case"toolCall":{let toolCallText=protocol.formatToolCall(block.name,block.arguments);newContent.push({type:"text",text:toolCallText});break}}return{...message,content:newContent}}function transformToolResultMessage(message,protocol){return{role:"user",content:protocol.formatToolResponse(message.toolName,message.toolCallId,message.content),timestamp:message.timestamp}}function wrapStreamWithToolCallMiddleware(innerStream,protocol,tools){let outerStream=new AssistantMessageEventStream,parser=protocol.createStreamParser(tools);return(async()=>{let projection=null,sawToolCall=!1,parserHasPendingInput=!1,flushParser=()=>{if(!projection||!parserHasPendingInput)return;let result=projection.projectParserEvents(parser.finish());sawToolCall=sawToolCall||result.sawToolCall,projection.finishText(),parserHasPendingInput=!1};try{for await(let event of innerStream)switch(event.type){case"start":projection=new StreamMessageProjection(outerStream,event.partial),outerStream.push({type:"start",partial:projection.message});break;case"text_start":if(!projection)break;projection.sync(event.partial),projection.startText(event.contentIndex,event.partial.content[event.contentIndex]);break;case"text_delta":{if(!projection)break;projection.sync(event.partial),event.delta.length>0&&(parserHasPendingInput=!0);let result=projection.projectParserEvents(parser.feed(event.delta));sawToolCall=sawToolCall||result.sawToolCall;break}case"text_end":if(!projection)break;projection.sync(event.partial),flushParser();break;case"thinking_start":if(!projection)break;projection.sync(event.partial),projection.startThinking(event.contentIndex,event.partial);break;case"thinking_delta":if(!projection)break;projection.sync(event.partial),projection.projectThinkingDelta(event.contentIndex,event.delta,event.partial);break;case"thinking_end":if(!projection)break;projection.sync(event.partial),projection.finishThinking(event.contentIndex,event.content,event.partial);break;case"done":{projection??=new StreamMessageProjection(outerStream,event.message),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.message,sawToolCall),reason=(sawToolCall||projection.hasFinalizedToolCallContent())&&(event.reason==="stop"||event.reason==="length")?"toolUse":event.reason;outerStream.push({type:"done",reason,message}),outerStream.end();return}case"error":{if(!projection){outerStream.push(event),outerStream.end(event.error);return}projection.sync(event.error),flushParser(),projection.finalizeDanglingToolCalls();let message=projection.finalize(event.error,sawToolCall);if(projection.hasFinalizedToolCallContent()){let recovered={...message,stopReason:"toolUse"};outerStream.push({type:"done",reason:"toolUse",message:recovered}),outerStream.end(recovered);return}outerStream.push({type:"error",reason:event.reason,error:message}),outerStream.end(message);return}case"toolcall_start":case"toolcall_delta":case"toolcall_end":break}let innerMessage=await innerStream.result();projection??=new StreamMessageProjection(outerStream,innerMessage),flushParser(),projection.finalizeDanglingToolCalls(),outerStream.end(projection.finalize(innerMessage,sawToolCall))}catch(error){flushParser(),projection??=new StreamMessageProjection(outerStream,await innerStream.result()),projection.finalizeDanglingToolCalls();let fallback=projection.message;fallback.stopReason="error",fallback.errorMessage=error instanceof Error?error.message:JSON.stringify(error),outerStream.push({type:"error",reason:"error",error:fallback}),outerStream.end()}})(),outerStream}function getToolCallFormat(model){if(model.api!=="openai-completions")return;let format=model.compat?.toolCallFormat;if(format&&(format==="hermes"||format==="xml"||format==="morph-xml"||format==="yaml-xml"||format==="gemma4-delimiter"||format==="anthropic-xml"||format==="antml"||format==="kimi-xtml"))return format}function shouldRecoverTextToolCalls(model){return getToolCallFormat(model)!==void 0?!1:model.recoverTextToolCalls!==void 0?typeof model.recoverTextToolCalls=="boolean"?model.recoverTextToolCalls:!1:model.api==="cursor-agent"?!1:CLAUDE_MODEL_ID_PATTERN.test(model.id)||KIMI_MODEL_ID_PATTERN.test(model.id)}var CLAUDE_MODEL_ID_PATTERN=/(^|[^a-z0-9])claude([^a-z0-9]|$)/i,KIMI_MODEL_ID_PATTERN=/(^|[^a-z0-9])kimi([^a-z0-9]|$)/i;function hasKimiTextToolCallRecovery(model){return KIMI_MODEL_ID_PATTERN.test(model.id)}function wrapStreamWithModelRecovery(innerStream,model,tools){let recoveredStream=hasKimiTextToolCallRecovery(model)?wrapStreamWithKimiThinkingRecovery(innerStream):innerStream;return!shouldRecoverTextToolCalls(model)||tools.length===0?recoveredStream:wrapStreamWithInvokeRecovery(recoveredStream,tools,hasKimiTextToolCallRecovery(model)?{createParser:createXtmlRecoveryStreamParser,protocol:"kimi-xtml"}:void 0)}function cloneTextContent(content){return{type:"text",text:content.text,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}function cloneThinkingContent(content){return{type:"thinking",thinking:content.thinking,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}function cloneToolCall2(toolCall){return{type:"toolCall",id:toolCall.id,name:toolCall.name,arguments:structuredClone(toolCall.arguments),...toolCall.thoughtSignature===void 0?{}:{thoughtSignature:toolCall.thoughtSignature},...toolCall.namespace===void 0?{}:{namespace:toolCall.namespace}}}function cloneStartMessage(message){return{role:"assistant",content:[],api:message.api,provider:message.provider,model:message.model,...message.responseModel===void 0?{}:{responseModel:message.responseModel},...message.responseId===void 0?{}:{responseId:message.responseId},...message.providerThinkingLevel===void 0?{}:{providerThinkingLevel:message.providerThinkingLevel},...message.diagnostics===void 0?{}:{diagnostics:structuredClone(message.diagnostics)},usage:structuredClone(message.usage),stopReason:"pending",timestamp:message.timestamp}}function assertContentIndex(contentIndex){if(!Number.isSafeInteger(contentIndex)||contentIndex<0)throw new Error(`Invalid assistant message frame contentIndex: ${contentIndex}`)}function eventBlock(event){assertContentIndex(event.contentIndex);let block=event.partial.content[event.contentIndex];if(!block)throw new Error(`${event.type} event has no content block at index ${event.contentIndex}`);return block}function serializedArguments(argumentsValue){let serialized=JSON.stringify(argumentsValue);if(serialized===void 0)throw new Error("Tool-call arguments are not JSON-serializable");return serialized}var EMPTY_PARSED_TOOL_ARGUMENTS=serializedArguments(parseStreamingJson(""));function isJsonPrefix(snapshot,current){if(typeof snapshot=="string")return typeof current=="string"&¤t.startsWith(snapshot);if(Array.isArray(snapshot))return Array.isArray(current)&&snapshot.length<=current.length&&snapshot.every((value,index)=>isJsonPrefix(value,current[index]));if(typeof snapshot!="object"||snapshot===null)return Object.is(snapshot,current);if(typeof current!="object"||current===null||Array.isArray(current))return!1;let currentRecord=current;return Object.entries(snapshot).every(([key,value])=>Object.hasOwn(currentRecord,key)&&isJsonPrefix(value,currentRecord[key]))}var AssistantMessageFrameEncoder=class{constructor(){this.started=!1,this.terminal=!1,this.blocks=new Map}encode(event){if(this.terminal)throw new Error(`Assistant message event ${event.type} follows a terminal event`);switch(event.type){case"start":if(this.started)throw new Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cloneStartMessage(event.partial)};case"done":if(!this.started)throw new Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw new Error(`Assistant message ${event.type} event appears before start`);switch(event.type){case"text_start":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"text",coveredChars:content.text.length,deltaChars:0}),{type:"text_start",contentIndex:event.contentIndex,content:cloneTextContent(content)}}case"text_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"text");case"text_end":{let content=eventBlock(event);if(content.type!=="text")throw new Error(`text_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"text"),{type:"text_end",contentIndex:event.contentIndex,content:event.content,...content.textSignature===void 0?{}:{textSignature:content.textSignature}}}case"thinking_start":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_start event points to ${content.type} block at index ${event.contentIndex}`);return this.startBlock(event.contentIndex,{kind:"thinking",coveredChars:content.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:event.contentIndex,content:cloneThinkingContent(content)}}case"thinking_delta":return this.encodeTextDelta(event.contentIndex,event.delta,"thinking");case"thinking_end":{let content=eventBlock(event);if(content.type!=="thinking")throw new Error(`thinking_end event points to ${content.type} block at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"thinking"),{type:"thinking_end",contentIndex:event.contentIndex,content:event.content,...content.thinkingSignature===void 0?{}:{thinkingSignature:content.thinkingSignature},...content.redacted===void 0?{}:{redacted:content.redacted}}}case"toolcall_start":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_start event points to ${content.type} block at index ${event.contentIndex}`);let snapshotArguments=serializedArguments(content.arguments),caughtUp=snapshotArguments===EMPTY_PARSED_TOOL_ARGUMENTS;return this.startBlock(event.contentIndex,{kind:"toolCall",caughtUp,catchupJson:"",snapshotArguments:caughtUp?"":snapshotArguments}),{type:"toolcall_start",contentIndex:event.contentIndex,toolCall:cloneToolCall2(content)}}case"toolcall_delta":{let state=this.block(event.contentIndex,"toolCall");if(state.kind!=="toolCall")throw new Error("Unreachable tool-call encoder state");if(state.caughtUp)return event.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:event.contentIndex,delta:event.delta};state.catchupJson+=event.delta;let argumentsValue=parseStreamingJson(state.catchupJson);if(serializedArguments(argumentsValue)!==state.snapshotArguments){let snapshotArguments=parseStreamingJson(state.snapshotArguments);if(!isJsonPrefix(snapshotArguments,argumentsValue))return}state.caughtUp=!0,state.snapshotArguments="";let json=state.catchupJson;return state.catchupJson="",json.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:event.contentIndex,json}}case"toolcall_end":{let content=eventBlock(event);if(content.type!=="toolCall")throw new Error(`toolcall_end event points to ${content.type} block at index ${event.contentIndex}`);if(event.toolCall.type!=="toolCall")throw new Error(`toolcall_end event has invalid tool call at index ${event.contentIndex}`);return this.endBlock(event.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:event.contentIndex,id:event.toolCall.id,name:event.toolCall.name,arguments:structuredClone(event.toolCall.arguments),...event.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:event.toolCall.thoughtSignature},...event.toolCall.namespace===void 0?{}:{namespace:event.toolCall.namespace}}}}}startBlock(contentIndex,state){if(assertContentIndex(contentIndex),this.blocks.has(contentIndex))throw new Error(`Assistant message block ${contentIndex} starts more than once`);this.blocks.set(contentIndex,state)}block(contentIndex,kind){assertContentIndex(contentIndex);let state=this.blocks.get(contentIndex);if(state===void 0)throw new Error(`Assistant message ${kind} block ${contentIndex} has not started`);if(state.kind!==kind)throw new Error(`Assistant message block ${contentIndex} is ${state.kind}, not ${kind}`);return state}endBlock(contentIndex,kind){this.block(contentIndex,kind),this.blocks.delete(contentIndex)}encodeTextDelta(contentIndex,delta,kind){let state=this.block(contentIndex,kind);if(state.kind==="toolCall")throw new Error("Unreachable text encoder state");let deltaStart=state.deltaChars;state.deltaChars+=delta.length;let covered=Math.max(0,state.coveredChars-deltaStart);if(covered>=delta.length)return;let uncovered=covered===0?delta:delta.slice(covered);return kind==="text"?{type:"text_delta",contentIndex,delta:uncovered}:{type:"thinking_delta",contentIndex,delta:uncovered}}};function appendBlock(message,states,contentIndex,block,state){if(assertContentIndex(contentIndex),contentIndex!==message.content.length){let reason=contentIndex<message.content.length?"already exists":"would leave a gap";throw new Error(`Cannot start assistant message block at index ${contentIndex}: ${reason}`)}message.content.push(structuredClone(block)),states.set(contentIndex,state)}function activeBlock(message,states,contentIndex,expectedKind,frameType){assertContentIndex(contentIndex);let state=states.get(contentIndex),block=message.content[contentIndex];if(!state||!block)throw new Error(`${frameType} frame has no started block at index ${contentIndex}`);if(state.kind!==expectedKind||block.type!==expectedKind)throw new Error(`${frameType} frame expected ${expectedKind} block at index ${contentIndex}, found ${block.type}`);if(state.ended)throw new Error(`${frameType} frame follows the end of block at index ${contentIndex}`);return{block,state}}function reduceAssistantMessageFrames(frames){let message,frameBeforeStart,states=new Map;for(let frame of frames){if(frame.type==="start"){if(message)throw new Error("Assistant message frame sequence contains more than one start frame");if(frameBeforeStart!==void 0)throw new Error(`${frameBeforeStart} frame appears before the start frame`);message=structuredClone(frame.partial);continue}if(!message){frameBeforeStart??=frame.type;continue}switch(frame.type){case"text_start":if(frame.content.type!=="text")throw new Error(`text_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"text",ended:!1});break;case"text_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text+=frame.delta;break}case"text_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"text",frame.type);if(block.type!=="text")throw new Error("Unreachable text frame state");block.text=frame.content,delete block.textSignature,frame.textSignature!==void 0&&(block.textSignature=frame.textSignature),state.ended=!0;break}case"thinking_start":if(frame.content.type!=="thinking")throw new Error(`thinking_start frame contains ${frame.content.type} content`);appendBlock(message,states,frame.contentIndex,frame.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking+=frame.delta;break}case"thinking_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"thinking",frame.type);if(block.type!=="thinking")throw new Error("Unreachable thinking frame state");block.thinking=frame.content,delete block.thinkingSignature,delete block.redacted,frame.thinkingSignature!==void 0&&(block.thinkingSignature=frame.thinkingSignature),frame.redacted!==void 0&&(block.redacted=frame.redacted),state.ended=!0;break}case"toolcall_start":if(frame.toolCall.type!=="toolCall")throw new Error(`toolcall_start frame contains ${frame.toolCall.type} content`);appendBlock(message,states,frame.contentIndex,frame.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call checkpoint state");state.json=frame.json,block.arguments=parseStreamingJson(frame.json);break}case"toolcall_delta":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall"||state.kind!=="toolCall")throw new Error("Unreachable tool-call frame state");state.json+=frame.delta;break}case"toolcall_end":{let{block,state}=activeBlock(message,states,frame.contentIndex,"toolCall",frame.type);if(block.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.id=frame.id,block.name=frame.name,block.arguments=structuredClone(frame.arguments),delete block.thoughtSignature,delete block.namespace,frame.thoughtSignature!==void 0&&(block.thoughtSignature=frame.thoughtSignature),frame.namespace!==void 0&&(block.namespace=frame.namespace),state.ended=!0;break}}}if(message){for(let[contentIndex,state]of states){if(state.kind!=="toolCall"||state.ended||state.json.length===0)continue;let block=message.content[contentIndex];if(block?.type!=="toolCall")throw new Error("Unreachable tool-call frame state");block.arguments=parseStreamingJson(state.json)}return message}}var kCursorExecResolved=Symbol.for("provider.block.cursorExecResolved");function isCursorExecResolved(block){return block?.[kCursorExecResolved]===!0}function copyCursorExecResolved(target,source){source[kCursorExecResolved]===!0&&(target[kCursorExecResolved]=!0)}function dropFailedAssistantTurns(messages){let callIdsByKeptAssistants=new Set,callIdsByFailedAssistants=new Set;for(let message of messages){let assistant=asAssistantTurn(message);if(!assistant)continue;let declared=isFailedStop(assistant.stopReason)?callIdsByFailedAssistants:callIdsByKeptAssistants;for(let block of assistant.content)block.type==="toolCall"&&typeof block.id=="string"&&declared.add(block.id)}for(let id of callIdsByKeptAssistants)callIdsByFailedAssistants.delete(id);return messages.filter(message=>{let assistant=asAssistantTurn(message);return assistant?!isFailedStop(assistant.stopReason):message.role==="toolResult"&&"toolCallId"in message&&typeof message.toolCallId=="string"?!callIdsByFailedAssistants.has(message.toolCallId):!0})}function asAssistantTurn(message){if(message.role==="assistant"&&!(!("content"in message)||!Array.isArray(message.content)))return{stopReason:"stopReason"in message?message.stopReason:void 0,content:message.content}}function isFailedStop(stopReason){return stopReason==="error"||stopReason==="aborted"}var OVERFLOW_PATTERNS=[/^Context window exhausted: /,/^The conversation is too long to resend \(about \d+ tokens, limit \d+\)/,/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds (?:(?:the|this) )?(?:model'?s )?context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/model_max_prompt_tokens_exceeded|exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./,/Model context limit reached\. Conversation size exceeds model capacity\./],CEREBRAS_BODYLESS_OVERFLOW_PATTERN=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,NON_OVERFLOW_PATTERNS=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i,/tokens per (?:min|minute|hour|day)/i,/\bTPM\b/i,/\bRPM\b/i,/quota exceeded/i,/retry (?:after|in) \d/i,/^429\b/,/status code 429/i,/overloaded/i],RESOURCE_EXHAUSTED_PATTERN=/resource.?exhausted/i;function isContextOverflow(message,contextWindow){if(message.stopReason==="error"&&message.errorMessage){let isNonOverflow=NON_OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage));if(!isNonOverflow&&(OVERFLOW_PATTERNS.some(p=>p.test(message.errorMessage))||message.provider==="cerebras"&&CEREBRAS_BODYLESS_OVERFLOW_PATTERN.test(message.errorMessage)))return!0;let usage=message.usage,hasTokenEvidence=(usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite)>0;if(!isNonOverflow&&hasTokenEvidence&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)&&(contextWindow===void 0||contextWindow<=0||cursorZeroTokenCount(message)>=contextWindow*.5))return!0}return!!(contextWindow&&message.stopReason==="stop"&&message.usage.input+message.usage.cacheRead>contextWindow||contextWindow&&message.stopReason==="length"&&message.usage.output===0&&message.usage.input+message.usage.cacheRead>=contextWindow*.99)}function isRecoverableLength(message,desiredMaxOutput){return message.stopReason==="length"&&desiredMaxOutput>0&&message.usage.output<desiredMaxOutput}function getOverflowPatterns(){return[...OVERFLOW_PATTERNS]}var CURSOR_PROVIDERS=new Set(["cursor","cursor-cli-oauth"]);function isCursorProviderMessage(message){return message.provider===void 0||CURSOR_PROVIDERS.has(message.provider)}function cursorZeroTokenCount(message){let usage=message.usage;return usage?usage.totalTokens||(usage.input??0)+(usage.output??0)+(usage.cacheRead??0)+(usage.cacheWrite??0):0}function isCursorPayloadResourceExhausted(message,_estimateTokens){return!isCursorProviderMessage(message)||message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function isCursorQuotaResourceExhausted(message,contextWindow){let tokens=cursorZeroTokenCount(message);return isCursorProviderMessage(message)&&message.stopReason==="error"&&RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage||"")&&contextWindow>0&&tokens>0&&tokens<contextWindow*.5}function isCursorZeroTokenResourceExhausted(message){return!isCursorProviderMessage(message)||message.stopReason!=="error"||!/resource.?exhausted/i.test(message.errorMessage||"")?!1:!(cursorZeroTokenCount(message)>0)}function shouldSkipProviderFallbackForCursorZeroRe(options){return options?.sameModelRemint===!0}function shouldRetryOverflowWithoutCompact(compacted,errorMessage){return compacted?!1:/Nothing to compact/i.test(errorMessage||"")}function cursorOverflowCompactionSettings(settings,provider,reason){return reason!=="overflow"||provider!=="cursor"&&provider!=="cursor-cli-oauth"?settings:{...settings,keepRecentTokens:0,restorationEnabled:!1}}var ANTHROPIC_POLICY_REFUSAL_PATTERN=/This request triggered restrictions on [\s\S]+? and was blocked under Anthropic's Usage Policy\b/i;function isClassifierRefusal(message){return message.stopReason!=="error"&&message.stopReason!=="toolUse"?!1:message.stopDetails?.type==="refusal"||message.stopDetails?.type==="sensitive"?!0:message.errorMessage?ANTHROPIC_POLICY_REFUSAL_PATTERN.test(message.errorMessage):!1}var TOOL_RESULT_PLACEHOLDER="Tool output unavailable (context compacted)";function incompleteToolCallRetryText(name,errorMessage){return errorMessage!==void 0?`${errorMessage}${errorMessage.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${name}" was not executed: the response ended before the tool call was complete. Re-issue the tool call with complete arguments.`}function repairOrphanedToolResults(messages){let toolCallIds=new Set,toolResultIds=new Set;for(let message of messages){if(message.role==="assistant")for(let block of message.content)block.type==="toolCall"&&toolCallIds.add(block.id);message.role==="toolResult"&&toolResultIds.add(message.toolCallId)}let output=[],dangling=new Set([...toolCallIds].filter(id=>!toolResultIds.has(id)));for(let message of messages){if(message.role==="toolResult"){if(!toolCallIds.has(message.toolCallId)){output.push({...message,content:[{type:"text",text:TOOL_RESULT_PLACEHOLDER}]});continue}output.push(message);continue}if(output.push(message),message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted")continue;for(let block of message.content){if(block.type!=="toolCall"||!dangling.has(block.id))continue;let incomplete=block.incomplete===!0,text=incomplete?incompleteToolCallRetryText(block.name,block.errorMessage):TOOL_RESULT_PLACEHOLDER;output.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text}],isError:incomplete,timestamp:message.timestamp?message.timestamp+1:Date.now()}),dangling.delete(block.id)}}}return output}function StringEnum(values,options){return typebox_exports.Unsafe({type:"string",enum:values,...options?.description&&{description:options.description},...options?.default&&{default:options.default}})}var INVISIBLE_FORMAT_CHARS=new RegExp("\\p{Cf}","gu");function hasVisibleText(text){return text.replace(INVISIBLE_FORMAT_CHARS,"").trim().length>0}function hasVisibleAssistantContent(message){return message.content.some(block=>block.type==="toolCall"||block.type==="text"&&hasVisibleText(block.text))}export{create,messageDesc,fromBinary,fileDesc,toBinary,measureCursorModelInputSerializedBytes,measureCursorHistorySerializedBytes,piReadArgs,piLsPath,piLimit,piTimeout,composeShellCommand,omitUndefinedArgs,registerPromptCacheWarmer,warmPromptCache,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,getRegisteredFauxProvider,fauxOverflowError,fauxProvider,installProviderScopeAccessor,registerApiProvider,registerBuiltinApiProvider,getApiProvider,getApiProviders,unregisterApiProviders,clearApiProviders,envApiKeyAuth,lazyOAuth,CURSOR_MODEL_CAPABILITIES,parseCursorVariantId,getCursorVariantAlias,getCursorBaseIdForVariant,getCursorCapabilityForBase,deriveCursorVariantAliases,normalizeCursorCatalog,resolveCursorSelectionDescriptor,renderCursorCliModelString,parseEndpointReasoningEfforts,modelSupportsAssistantPrefill,supportsAllowedToolChoice,createXtmlRecoveryStreamParser,wrapStreamWithInvokeRecovery,Compile,compile_exports,validateToolCall,validateToolArguments,require_dist,getProtocol,transformContext,wrapStreamWithToolCallMiddleware,getToolCallFormat,shouldRecoverTextToolCalls,hasKimiTextToolCallRecovery,wrapStreamWithModelRecovery,AssistantMessageFrameEncoder,reduceAssistantMessageFrames,kCursorExecResolved,isCursorExecResolved,copyCursorExecResolved,dropFailedAssistantTurns,isContextOverflow,isRecoverableLength,getOverflowPatterns,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,shouldSkipProviderFallbackForCursorZeroRe,shouldRetryOverflowWithoutCompact,cursorOverflowCompactionSettings,isClassifierRefusal,TOOL_RESULT_PLACEHOLDER,repairOrphanedToolResults,StringEnum,hasVisibleText,hasVisibleAssistantContent};
|