blade-code 0.10.42 → 0.10.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-dx7xefys.js → chunk-0qsssahq.js} +1 -1
- package/dist/{chunk-xkg84094.js → chunk-1vydfzvy.js} +2 -2
- package/dist/{chunk-ecw74d2s.js → chunk-26wse17p.js} +2 -2
- package/dist/{chunk-3xx2ebr7.js → chunk-2eddqgnh.js} +1 -1
- package/dist/{chunk-hypq4t4z.js → chunk-2yvte5a7.js} +1 -1
- package/dist/chunk-3nfse1ps.js +1 -0
- package/dist/chunk-3y784b9c.js +1 -0
- package/dist/{chunk-7gjb405q.js → chunk-50a5xx45.js} +1 -1
- package/dist/{chunk-1yjzj2d0.js → chunk-56qew7w0.js} +2 -2
- package/dist/{chunk-jz2gkqdt.js → chunk-583kv07t.js} +7 -7
- package/dist/chunk-619q1w65.js +1 -0
- package/dist/{chunk-qb49rm5q.js → chunk-63p5mj97.js} +1 -1
- package/dist/chunk-6cx4t8r6.js +1 -0
- package/dist/{chunk-mt7fn8cv.js → chunk-706zda55.js} +3 -3
- package/dist/{chunk-d2fce0vk.js → chunk-74hcqcn7.js} +2 -2
- package/dist/{chunk-kfv4mdcm.js → chunk-7fqsgdee.js} +2 -2
- package/dist/{chunk-5zr3w30g.js → chunk-7sna3js9.js} +1 -1
- package/dist/chunk-7z5t63ke.js +10 -0
- package/dist/chunk-86tba7p4.js +1 -0
- package/dist/{chunk-020hgyg7.js → chunk-8vtyatd6.js} +1 -1
- package/dist/chunk-99nka030.js +1 -0
- package/dist/{chunk-f90ybvrs.js → chunk-9rrced3b.js} +1 -1
- package/dist/chunk-a68fws4p.js +1 -0
- package/dist/chunk-agbyfdvw.js +1 -0
- package/dist/{chunk-sw3p1ygn.js → chunk-aw7w91f0.js} +68 -68
- package/dist/{chunk-0qf7h4n2.js → chunk-bvf9syb2.js} +2 -2
- package/dist/{chunk-dr4et3gj.js → chunk-c9s4n31b.js} +1 -1
- package/dist/{chunk-q6n6rqzs.js → chunk-cf2541w5.js} +2 -2
- package/dist/{chunk-4rmdfme3.js → chunk-ckqj0pxz.js} +1 -1
- package/dist/{chunk-f542fh7g.js → chunk-cxzx7j0p.js} +1 -1
- package/dist/chunk-d18mw6d1.js +2 -0
- package/dist/{chunk-1e9866ye.js → chunk-egczvfsv.js} +2 -2
- package/dist/{chunk-anwm8rp3.js → chunk-f4sp074f.js} +1 -1
- package/dist/chunk-fer18bbe.js +1 -0
- package/dist/{chunk-t2mc97k7.js → chunk-fhnkyqfb.js} +2 -2
- package/dist/chunk-fk0q25dp.js +8 -0
- package/dist/{chunk-3v2sgvzt.js → chunk-fk4wbmv6.js} +2 -2
- package/dist/{chunk-wm944thh.js → chunk-g96t2yrz.js} +22 -22
- package/dist/{chunk-pm9kt54d.js → chunk-hcm55r3d.js} +1 -1
- package/dist/{chunk-m8s208g3.js → chunk-hfrcwkc8.js} +1 -1
- package/dist/{chunk-yqxyy3w2.js → chunk-j0k3mbkd.js} +2 -2
- package/dist/chunk-j7edwwg1.js +2 -0
- package/dist/{chunk-jv9zg1fw.js → chunk-kfpzrmq7.js} +1 -1
- package/dist/{chunk-8csfb83y.js → chunk-m1b6v1zn.js} +2 -2
- package/dist/{chunk-18wnstzp.js → chunk-m8ss9rmx.js} +1 -1
- package/dist/{chunk-te95z52n.js → chunk-mrsc4a55.js} +1 -1
- package/dist/{chunk-fye8eghq.js → chunk-mzq3ps9j.js} +2 -2
- package/dist/chunk-n4ywszmn.js +6 -0
- package/dist/chunk-p4egmgt6.js +2 -0
- package/dist/chunk-pk9peyzp.js +1 -0
- package/dist/{chunk-mpymjr7j.js → chunk-q78s028m.js} +1 -1
- package/dist/{chunk-m3dvta6k.js → chunk-qb0sqh29.js} +2 -2
- package/dist/{chunk-0jsy9eav.js → chunk-qp2z1r7y.js} +1 -1
- package/dist/chunk-qzd9d0p8.js +22 -0
- package/dist/{chunk-mp637mb6.js → chunk-r085zhqr.js} +2 -2
- package/dist/{chunk-1whfdz08.js → chunk-s4denzh4.js} +1 -1
- package/dist/{chunk-6d0hphtd.js → chunk-sqd5ge5s.js} +1 -1
- package/dist/{chunk-brwdd5kp.js → chunk-svj24r6g.js} +2 -2
- package/dist/{chunk-jf6mkx0j.js → chunk-synjj8b3.js} +1 -1
- package/dist/chunk-t33njg4e.js +1 -0
- package/dist/{chunk-vc32qrmq.js → chunk-tpa75y39.js} +1 -1
- package/dist/chunk-tzp486wc.js +1 -0
- package/dist/{chunk-y75y911b.js → chunk-v9tzhe90.js} +2 -2
- package/dist/{chunk-ex21hxqf.js → chunk-vx5tjahq.js} +1 -1
- package/dist/chunk-wr2rkg9t.js +1 -0
- package/dist/{chunk-7pmpm5yq.js → chunk-wwvb6znp.js} +1 -1
- package/dist/chunk-wx5nj2s2.js +44 -0
- package/dist/{chunk-8b2bpfnt.js → chunk-x3cyg9pe.js} +3 -3
- package/dist/chunk-y6tkxqjx.js +2 -0
- package/dist/{chunk-4k37vmxh.js → chunk-yk9pxkc1.js} +1 -1
- package/dist/chunk-z1aqe7ms.js +1 -0
- package/dist/{chunk-z60w7p8a.js → chunk-z9absgab.js} +1 -1
- package/dist/web/assets/{ChatView-DBgMoUrW.js → ChatView-CyxiCTbL.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-DLFQUVD6.js → CodeBlockHighlighter-Bb3gIeQv.js} +1 -1
- package/dist/web/assets/{FilePreview--1qHdJP_.js → FilePreview-BXg9VaTv.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DcVHyjtl.js → MarkdownRenderer-vxpqGt4L.js} +3 -3
- package/dist/web/assets/{SettingsModal-BM6SPUXW.js → SettingsModal-4L1nPkh0.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-B5VYY_QG.js → TaskSwitcher-DKSqTLK1.js} +1 -1
- package/dist/web/assets/{TerminalPanel-XWA1jGs8.js → TerminalPanel-Bv9PDclr.js} +1 -1
- package/dist/web/assets/{index-B8y5_J0i.js → index-Bz4W1-8a.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-5hbm5e24.js +0 -44
- package/dist/chunk-74sxsd1h.js +0 -1
- package/dist/chunk-78jy2kby.js +0 -1
- package/dist/chunk-7qd6xqjs.js +0 -1
- package/dist/chunk-8wg7g98v.js +0 -10
- package/dist/chunk-c53hc8ze.js +0 -1
- package/dist/chunk-dgs04r04.js +0 -2
- package/dist/chunk-h9fkttf1.js +0 -2
- package/dist/chunk-hkmgrdxc.js +0 -1
- package/dist/chunk-katrmbxc.js +0 -1
- package/dist/chunk-m4ya7qqd.js +0 -1
- package/dist/chunk-n6c6k87j.js +0 -1
- package/dist/chunk-ppxn94za.js +0 -1
- package/dist/chunk-rf7hdke7.js +0 -1
- package/dist/chunk-rjjjgcw4.js +0 -1
- package/dist/chunk-vsaqjbm2.js +0 -6
- package/dist/chunk-wcxsm922.js +0 -2
- package/dist/chunk-wn23bvs0.js +0 -1
- package/dist/chunk-wtczk025.js +0 -22
- package/dist/chunk-yatvtpft.js +0 -1
- package/dist/chunk-za6zyd82.js +0 -8
- package/dist/chunk-zhrc510s.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
|
|
2
|
-
export{i as
|
|
2
|
+
export{i as we,E as xe,e as ye,t as ze,o as Ae};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ac as g,uc as a,vc as b,wc as c,xc as d,yc as e,zc as f}from"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-qp2z1r7y.js";import"./chunk-2yvte5a7.js";import"./chunk-cxzx7j0p.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-fhnkyqfb.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{Ge as Q}from"./chunk-sqd5ge5s.js";import{Tf as F,Vf as k,Yf as G}from"./chunk-m8ss9rmx.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as ad};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-1whfdz08.js";import{t as AH,u as t,v as e,w as HH,x as d,y as JH}from"./chunk-wcxsm922.js";import{L as jH,N as xH,O as UH,Q as VH,T as _H}from"./chunk-sw3p1ygn.js";import"./chunk-jz2gkqdt.js";import"./chunk-h9fkttf1.js";import{Wa as s,jb as LH,sb as WH}from"./chunk-8b2bpfnt.js";import"./chunk-te95z52n.js";import{_b as QH,cc as DH,nc as O,yc as a}from"./chunk-wm944thh.js";import"./chunk-dx7xefys.js";import"./chunk-1yjzj2d0.js";import{Vc as PH}from"./chunk-xkg84094.js";import{Xc as FH,Yc as EH,Zc as zH}from"./chunk-vsaqjbm2.js";import{_c as GH}from"./chunk-y75y911b.js";import"./chunk-3v2sgvzt.js";import{yd as NH}from"./chunk-mp637mb6.js";import"./chunk-v508x7cg.js";import"./chunk-7pmpm5yq.js";import"./chunk-1e9866ye.js";import"./chunk-kfv4mdcm.js";import"./chunk-0jsy9eav.js";import"./chunk-d2fce0vk.js";import"./chunk-8csfb83y.js";import"./chunk-vc32qrmq.js";import"./chunk-hypq4t4z.js";import"./chunk-6d0hphtd.js";import"./chunk-mt7fn8cv.js";import"./chunk-f542fh7g.js";import"./chunk-5hbm5e24.js";import{Hf as YH}from"./chunk-5zr3w30g.js";import{If as BH,Kf as H,Lf as KH,Nf as N}from"./chunk-18wnstzp.js";import"./chunk-dgs04r04.js";import{Uf as g}from"./chunk-jv9zg1fw.js";import"./chunk-4k37vmxh.js";import"./chunk-t2mc97k7.js";import"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import"./chunk-yqxyy3w2.js";import"./chunk-0qf7h4n2.js";import"./chunk-mpymjr7j.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),aH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(aH)}),oH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),rH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(oH)}),nH=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),tH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),JJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),KJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),VJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),YJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"}))}),DJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),LJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),cost_usd:H.Optional(H.Number())}),WJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),xJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),UJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),GJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),EJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function SJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var TJ=N(["text","jsonl"]),bJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(YH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-s4denzh4.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-d18mw6d1.js";import{N as jH,P as xH,Q as UH,S as VH,V as _H}from"./chunk-aw7w91f0.js";import"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import{Ya as s,lb as LH,ub as WH}from"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import{Ac as a,ac as QH,ec as DH,pc as O}from"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{Xc as PH}from"./chunk-1vydfzvy.js";import{$c as zH,Zc as FH,_c as EH}from"./chunk-n4ywszmn.js";import{ad as GH}from"./chunk-v9tzhe90.js";import"./chunk-fk4wbmv6.js";import{Ad as NH}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import{Sf as YH}from"./chunk-7sna3js9.js";import{Tf as BH,Vf as H,Wf as KH,Yf as N}from"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as g}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),aH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(aH)}),oH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),rH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(oH)}),nH=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),tH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),JJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),KJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),VJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),YJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"}))}),DJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),LJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),cost_usd:H.Optional(H.Number())}),WJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),xJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),UJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),GJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),EJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function SJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var TJ=N(["text","jsonl"]),bJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(YH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function CJ(K){return`[task] [${K.status}] ${K.subject}`}function kJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function hJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function OJ(K){return K==="jsonl"?"jsonl":"text"}function qH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function wJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function XH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify($H(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f}from"./chunk-j0k3mbkd.js";import"./chunk-hfrcwkc8.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
|
|
2
|
-
export{B as
|
|
2
|
+
export{B as Jd};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{Tf as mn,Uf as j,Vf as o}from"./chunk-m8ss9rmx.js";import{Zf as bt,_f as ct}from"./chunk-j7edwwg1.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Ag as Gt,eg as Zn,fg as Xt,gg as gt,kg as pt,lg as On,mg as it,ng as Rt,og as Ct,pg as Jn,qg as zt,rg as Bt,sg as kn,tg as Kt,ug as Ut,vg as yn,wg as Ht,xg as Yt,yg as qt,zg as Vt}from"./chunk-yk9pxkc1.js";import{Eg as hn}from"./chunk-fhnkyqfb.js";import{Hg as $t,Kg as Z}from"./chunk-26wse17p.js";import{Sg as wn,Tg as an}from"./chunk-j0k3mbkd.js";import{Xg as d}from"./chunk-bvf9syb2.js";import{fh as En}from"./chunk-qb0sqh29.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as l}from"node:crypto";import MM from"node:http";import{auth as sn}from"@modelcontextprotocol/sdk/client/auth.js";import eM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as J,promises as P}from"node:fs";import k from"node:path";import{Mutex as Ot}from"async-mutex";import Jt from"write-file-atomic";var Tn=1,kt=1048576,yt=5000,jt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),Sn=o.Object({version:o.Literal(Tn),credentials:o.Record(o.String(),on)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function un(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:Y(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class N{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=En()){this.stateRoot=k.join(n,"mcp"),this.tokenFilePath=k.join(this.stateRoot,"oauth-credentials.json");let t=N.mutexes.get(this.tokenFilePath);if(!t)t=new Ot,N.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?y(e):null);if(r)M.credentials[n]=j(on,r);else delete M.credentials[n];return r?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>kt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=mn(Sn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return un(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:Tn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(Sn,n);un(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=k.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+yt;while(Date.now()<M)try{let e=await P.open(n,J.O_CREAT|J.O_EXCL|J.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
|
+
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,jt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await P.unlink(n)}}var An="127.0.0.1",bn=7777,cn="/oauth/callback",rM=300000;class v extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function _M(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
8
|
+
<title>${t}</title>
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<main>
|
|
12
|
+
<h1>${t}</h1>
|
|
13
|
+
<p>${n?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
|
|
14
|
+
</main>
|
|
15
|
+
</body>
|
|
16
|
+
</html>`}function C(n,t,M){n.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),n.end(_M(M))}class ${serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,M,e={}){this.serverName=n;this.config=M;this.serverUrl=Y(t),this.identity=F(this.serverUrl,M.clientId,M.scopes),this.tokenStorage=e.tokenStorage??new N;let r=M.callbackPort??bn;this.callbackUrl=`http://${An}:${r}${cn}`,this.openAuthorizationUrl=e.openAuthorizationUrl??(async(S)=>{await eM(S,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${an()} ${wn()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??l()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(n){await this.updateCredential((t)=>({...this.baseCredential(t),clientInformation:n}))}async tokens(){let n=await this.readCredential();if(!n?.tokens)return;if(n.tokenExpiresAt!==void 0&&n.tokenExpiresAt<=Date.now()&&!n.tokens.refresh_token)return;return structuredClone(n.tokens)}async saveTokens(n){let t=n.expires_in===void 0?void 0:Date.now()+n.expires_in*1000;await this.updateCredential((M)=>({...this.baseCredential(M),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new v(this.serverName);t.authorizationUrl=R(n,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(n){this.codeVerifierValue=n}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(n){await this.updateCredential((t)=>({...this.baseCredential(t),discoveryState:structuredClone(n)}))}async discoveryState(){let n=(await this.readCredential())?.discoveryState;return n?structuredClone(n):void 0}async invalidateCredentials(n){if(n==="verifier"){this.codeVerifierValue=void 0;return}if(n==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((t)=>{if(!t)return null;let M={...t};if(n==="client")delete M.clientInformation,delete M.tokens,delete M.tokenExpiresAt;else if(n==="tokens")delete M.tokens,delete M.tokenExpiresAt;else if(n==="discovery")delete M.discoveryState;return{...M,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let n=await this.readCredential();if(!n?.tokens?.access_token)return!1;if(n.tokenExpiresAt===void 0||n.tokenExpiresAt>Date.now())return!0;return Boolean(n.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if($.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");$.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await sn(this,{serverUrl:this.serverUrl,fetchFn:U})!=="REDIRECT"||!n.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(n)}catch(n){let t=n instanceof Error?n:Error(String(n));throw await this.failActiveFlow(t),t}}async openAuthorization(){let n=await this.beginAuthorization();return await this.openAuthorizationUrl(n.authorizationUrl),n}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let n,t,M=new Promise((_,u)=>{n=_,t=u});M.catch(()=>{return});let e=l(),r=MM.createServer((_,u)=>{this.handleCallback(_,u)});r.on("clientError",(_,u)=>{u.end(`HTTP/1.1 400 Bad Request\r
|
|
17
|
+
Connection: close\r
|
|
18
|
+
\r
|
|
19
|
+
`)}),await new Promise((_,u)=>{let E=(T)=>u(T);r.once("error",E),r.listen(this.config.callbackPort??bn,An,()=>{r.off("error",E),_()})});let S={flowId:l(),state:e,callbackUrl:this.callbackUrl,server:r,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},rM),completion:M,resolve:n,reject:t,settled:!1};return S.timeout.unref(),S}async handleCallback(n,t){let M=this.activeFlow;if(!M){C(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),C(t,405,!1);return}let e=new URL(n.url??"/",M.callbackUrl);if(e.pathname!==cn){C(t,404,!1);return}let r=e.searchParams.get("state"),S=e.searchParams.get("code");if(e.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!r||r!==M.state)throw Error("MCP OAuth state mismatch");if(!S)throw Error("MCP OAuth callback is missing the authorization code");if(await sn(this,{serverUrl:this.serverUrl,authorizationCode:S,fetchFn:U})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");C(t,200,!0),await this.completeActiveFlow()}catch(e){C(t,400,!1),await this.failActiveFlow(e instanceof Error?e:Error(String(e)))}}async completeActiveFlow(){let n=this.activeFlow;if(!n||n.settled)return;n.settled=!0,clearTimeout(n.timeout),await new Promise((t)=>n.server.close(()=>t())),this.activeFlow=void 0,$.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,n.resolve()}async failActiveFlow(n){let t=this.activeFlow;if(this.lastError=n,this.codeVerifierValue=void 0,$.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((M)=>t.server.close(()=>M())),this.activeFlow=void 0,t.reject(n)}toHandle(n){if(!n.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:n.flowId,authorizationUrl:n.authorizationUrl,callbackUrl:n.callbackUrl,completion:n.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(n){return this.tokenStorage.updateCredential(this.identity,n)}baseCredential(n){return{...n??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}import{promises as q}from"node:fs";import Pn from"node:os";import I from"node:path";import{Mutex as xn}from"async-mutex";import{merge as SM}from"lodash-es";import uM from"write-file-atomic";var dn=hn("Service"),X={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},modelProviders:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},bashForegroundHandoffMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerForegroundRecoveryMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerCircuitBreakerOpenMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestAdmissionMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestPendingBytes:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},codeTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},communicationStyle:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},enabledPlugins:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},pluginSourcePolicy:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxConcurrentTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTaskBytes:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxResidentSessionRuntimes:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},sessionRuntimeIdleMs:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},lspServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},oe=new Set(Object.entries(X).filter(([n,t])=>t.persistable).map(([n])=>n)),se=new Set(Object.entries(X).filter(([n,t])=>!t.persistable).map(([n])=>n));class x{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){if(x.instance)for(let n of x.instance.timers.values())clearTimeout(n);x.instance=null}async save(n,t={}){this.validatePersistableFields(n);let M=this.groupUpdatesByTarget(n,t.scope,t.projectDir);if(t.immediate)await Promise.all(Array.from(M.entries()).map(([e,r])=>this.flushTarget(e,r)));else for(let[e,r]of M)this.scheduleSave(e,r)}async flush(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear();let n=Array.from(this.pendingUpdates.entries()).map(([t,M])=>this.flushTarget(t,M));this.pendingUpdates.clear(),await Promise.all(n)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(n,t={}){await this.appendPermissionRuleForDecision(n,"allow",t)}async appendPermissionDenyRule(n,t={}){await this.appendPermissionRuleForDecision(n,"deny",t)}async appendPermissionRuleForDecision(n,t,M){let e=M.scope??"local",r=this.resolveFilePath("settings",e,M.projectDir);await this.flushTargetWithModifier(r,(S)=>{let _=S.permissions??{allow:[],ask:[],deny:[]},u={allow:t==="allow"?this.dedupeArray([..._.allow||[],n]):_.allow||[],ask:_.ask||[],deny:t==="deny"?this.dedupeArray([..._.deny||[],n]):_.deny||[]};return{...S,permissions:u}})}async appendLocalPermissionRule(n,t={}){await this.appendPermissionRule(n,{...t,scope:"local"})}async appendLocalPermissionDenyRule(n,t={}){await this.appendPermissionDenyRule(n,{...t,scope:"local"})}async removePluginSetting(n,t={}){let M=t.scope??"local",e=this.resolveFilePath("settings",M,t.projectDir);await this.flushTargetWithModifier(e,(r)=>{let S={...r.enabledPlugins??{}};delete S[n];let _={...r};if(Object.keys(S).length>0)_.enabledPlugins=S;else delete _.enabledPlugins;return _})}validatePersistableFields(n){for(let t of Object.keys(n)){let M=X[t];if(!M)throw Error(`Unknown config field: ${t}`);if(!M.persistable)throw Error(`Field "${t}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(n,t,M){let e=new Map;for(let[r,S]of Object.entries(n)){let _=X[r];if(!_)continue;let u=t??_.defaultScope,E=this.resolveFilePath(_.target,u,M);if(!e.has(E))e.set(E,{});e.get(E)[r]=S}return e}resolveFilePath(n,t,M){let e=M??a();if(n==="config")return t==="global"?I.join(Pn.homedir(),".blade","config.json"):I.join(e,".blade","config.json");switch(t){case"local":return I.join(e,".blade","settings.local.json");case"project":return I.join(e,".blade","settings.json");case"global":return I.join(Pn.homedir(),".blade","settings.json");default:return I.join(e,".blade","settings.local.json")}}scheduleSave(n,t){let M=this.pendingUpdates.get(n)??{},e=this.mergePendingUpdates(M,t);this.pendingUpdates.set(n,e);let r=this.timers.get(n);if(r)clearTimeout(r);let S=setTimeout(async()=>{let _=this.pendingUpdates.get(n);if(_){this.pendingUpdates.delete(n),this.timers.delete(n);try{await this.flushTarget(n,_),this.lastSaveError=null}catch(u){let E=u instanceof Error?u:Error(String(u));this.lastSaveError=E,dn.error(`Failed to save config to ${n}:`,E.message),dn.error("Stack trace:",E.stack)}}},this.debounceDelay);this.timers.set(n,S)}mergePendingUpdates(n,t){let M={...n};for(let[e,r]of Object.entries(t)){let S=X[e];if(!S){M[e]=r;continue}switch(S.mergeStrategy){case"replace":M[e]=r;break;case"append-dedupe":this.applyAppendDedupe(M,e,r);break;case"deep-merge":this.applyDeepMerge(M,e,r);break}}return M}async flushTarget(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await this.performWrite(n,t)})}async flushTargetWithModifier(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await q.mkdir(I.dirname(n),{recursive:!0,mode:493});let e={};try{let S=await q.readFile(n,"utf-8");e=JSON.parse(S)}catch{e={}}let r=t(e);await this.atomicWrite(n,r)})}async performWrite(n,t){await q.mkdir(I.dirname(n),{recursive:!0,mode:493});let M={};try{let r=await q.readFile(n,"utf-8");M=JSON.parse(r)}catch{M={}}let e={...M};if(typeof e.theme==="string"&&e.codeTheme===void 0)e.codeTheme=e.theme;delete e.theme;for(let[r,S]of Object.entries(t)){let _=X[r];if(!_){e[r]=S;continue}switch(_.mergeStrategy){case"replace":e[r]=S;break;case"append-dedupe":this.applyAppendDedupe(e,r,S);break;case"deep-merge":this.applyDeepMerge(e,r,S);break}}await this.atomicWrite(n,e)}applyAppendDedupe(n,t,M){if(t==="permissions"&&typeof M==="object"&&M!==null){let e=n[t]??{allow:[],ask:[],deny:[]},r=M;n[t]={allow:this.dedupeArray([...e.allow||[],...r.allow||[]]),ask:this.dedupeArray([...e.ask||[],...r.ask||[]]),deny:this.dedupeArray([...e.deny||[],...r.deny||[]])}}else if(Array.isArray(M)){let e=Array.isArray(n[t])?n[t]:[];n[t]=this.dedupeArray([...e,...M])}else n[t]=M}applyDeepMerge(n,t,M){if(typeof M==="object"&&M!==null&&!Array.isArray(M)){let e=typeof n[t]==="object"&&n[t]!==null?n[t]:{};n[t]=SM({},e,M)}else n[t]=M}dedupeArray(n){return Array.from(new Set(n))}async atomicWrite(n,t){await uM(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}}function Ae(){return x.getInstance()}var In=15000,fn=1000,Nn=300000;function nn(n){return n===0||typeof n==="number"&&Number.isSafeInteger(n)&&n>=1000&&n<=300000}function ce(n,t=15000){return nn(n)?n:t}var $n=1,Xn=32,gn=256,pn=30000,Rn=300000,Cn=3600000,ae=30000;function zn(n){return Number.isSafeInteger(n)&&n>=1&&n<=256}function Bn(n){return Number.isSafeInteger(n)&&n>=30000&&n<=3600000}var Kn=1,Un=64,Hn=1,Yn=1e4,qn=67108864,Vn=65536,Gn=134217728;function Qn(n){return Number.isInteger(n)&&n>=1&&n<=64}function Dn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}function Wn(n){return Number.isSafeInteger(n)&&n>=65536&&n<=134217728}var s={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,bashForegroundHandoffMs:In,providerForegroundRecoveryMs:Zn,providerCircuitBreakerOpenMs:On,providerRequestConcurrency:Jn,providerRequestAdmissionMs:kn,providerRequestPendingBytes:yn,codeTheme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100,maxQueuedTaskBytes:qn,maxResidentSessionRuntimes:Xn,sessionRuntimeIdleMs:Rn};var jn=/^[A-Za-z0-9_-]{21}$/;function Fn(n){return n.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function mM(n,t){let M=new Set(t.map((_)=>_.id)),e=Fn(n.model);if(!M.has(e))return e;let r=`${Fn(n.provider)}-${e}`.slice(0,120);if(!M.has(r))return r;let S=2;while(M.has(`${r}-${S}`))S++;return`${r}-${S}`}function ln(n,t){let M=n.filter((S)=>!jn.test(S.id)).map((S)=>({id:S.id})),e=new Map;return{models:n.map((S)=>{if(!jn.test(S.id))return{...S};let{id:_,...u}=S,E=mM(u,M);return M.push({id:E}),e.set(_,E),{...S,id:E}}),currentModelId:e.get(t)??t,changed:e.size>0}}import{promises as Nt}from"fs";import{merge as K}from"lodash-es";import c from"os";import m from"path";function nt(n){let t=vn(n.timeout??300000,"MCP timeout"),M=vn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(M>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:M,maxProgressEvents:128}}function ie(n,t,M){if(t.count>=M.maxProgressEvents)return;if(!Number.isFinite(n.progress)||n.progress<0)return;if(n.total!==void 0&&(!Number.isFinite(n.total)||n.total<=0))return;if(t.lastProgress!==void 0&&n.progress<t.lastProgress)return;t.count++,t.lastProgress=n.progress;let e=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:e||TM(n.progress,n.total)}}function vn(n,t){if(!Number.isSafeInteger(n)||n<1000||n>1800000)throw Error(`${t} must be an integer between 1000 and 1800000 milliseconds`);return n}function TM(n,t){if(t!==void 0)return`MCP progress ${Math.max(0,Math.min(100,n/t*100)).toFixed(0)}%`;return`MCP progress ${n}`}import{createHash as oM}from"node:crypto";var V=["debug","info","notice","warning","error","critical","alert","emergency"],ze=64,Be=64,Ke=256,sM=8192,rt=16384,AM=256,bM=6,cM=128,tt=64,Mt=64,wM=128,aM=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function _t(n){let t=n.logging;if(t!==void 0&&(t===null||typeof t!=="object"||Array.isArray(t)))throw Error("MCP logging configuration must be an object");let M=t?.enabled??!0;if(typeof M!=="boolean")throw Error("MCP logging enabled must be a boolean");let e=t?.level??"warning";if(!LM(e))throw Error(`MCP logging level must be one of: ${V.join(", ")}`);return{enabled:M,level:e}}function LM(n){return typeof n==="string"&&V.includes(n)}function Ue(n,t){return V.indexOf(n)>=V.indexOf(t)}function PM(n,t={}){let M=xM(n.data),e=typeof M.value==="string"?M.value:JSON.stringify(M.value),r=et(e,rt),S=r.value,_=Buffer.byteLength(S),u=oM("sha256").update(S).digest("hex"),E=t.exposeDetails!==!1,T=E?et(S,sM):{value:`[MCP log details omitted; sha256=${u}]`,truncated:!1},A=E&&n.logger?G(Mn(n.logger),AM):void 0;return{level:n.level,...A?{logger:A}:{},message:T.value||"[empty MCP log message]",projectedBytes:_,dataSha256:u,truncated:M.truncated||r.truncated||T.truncated,detailsOmitted:!E,timestamp:t.now??Date.now()}}function He(n,t={}){return{...PM({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function xM(n){let t={nodes:0,remainingStringBytes:rt,truncated:!1,seen:new WeakSet};return{value:tn(n,0,t),truncated:t.truncated}}function tn(n,t,M){if(M.nodes++,M.nodes>cM)return M.truncated=!0,"[node limit reached]";if(n===null||typeof n==="boolean")return n;if(typeof n==="number")return Number.isFinite(n)?n:String(n);if(typeof n==="bigint")return n.toString();if(typeof n==="string"){let e=Mn(n),r=Math.max(0,M.remainingStringBytes),S=G(e,r),_=Buffer.byteLength(S);if(M.remainingStringBytes-=_,_<Buffer.byteLength(e))M.truncated=!0;return S}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=bM)return M.truncated=!0,"[depth limit reached]";if(M.seen.has(n))return M.truncated=!0,"[circular]";M.seen.add(n);try{if(Array.isArray(n)){if(n.length>tt)M.truncated=!0;return n.slice(0,tt).map((S)=>tn(S,t+1,M))}let e=Object.create(null),r=Object.entries(n);if(r.length>Mt)M.truncated=!0;for(let[S,_]of r.slice(0,Mt)){let u=G(Mn(S),wM)||"[empty-key]";if(S==="_meta"||aM.test(S))e[u]="[redacted]";else e[u]=tn(_,t+1,M)}return e}finally{M.seen.delete(n)}}function Mn(n){return[...n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((M)=>{let e=M.charCodeAt(0);return(e===9||e===10||e===13||e>=32)&&e!==127}).join("")}function G(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let M=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(M)>t)M=M.slice(0,-1);return M}function et(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let M=`
|
|
20
|
+
...[MCP log truncated]`;return{value:G(n,t-Buffer.byteLength(M))+M,truncated:!0}}var St=1024,dM=4096,ut=2,hM=8,Et=65536,IM=1048576,mt=50,Tt=16000,ot=4,fM=100,st=1048576,NM=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function wt(n){if(!n)return{enabled:!1,maxTokens:St,maxRequestsPerToolCall:ut,maxInputBytes:Et};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:Q(n.maxTokens??St,1,dM,"MCP sampling.maxTokens"),maxRequestsPerToolCall:Q(n.maxRequestsPerToolCall??ut,1,hM,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:Q(n.maxInputBytes??Et,1,IM,"MCP sampling.maxInputBytes")}}function Ve(n,t){if(!t.enabled)throw Error("MCP sampling is disabled");if(n.task)throw Error("Task-based MCP sampling is not supported");if(n.tools?.length)throw Error("MCP sampling tools were not negotiated");if(n.includeContext&&n.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(n.messages.length===0||n.messages.length>mt)throw Error(`MCP sampling messages must contain 1-${mt} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Tt)throw Error(`MCP sampling system prompt exceeds ${Tt} characters`);if(n.temperature!==void 0&&(!Number.isFinite(n.temperature)||n.temperature<0||n.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let M=n.stopSequences??[];if(M.length>ot||M.some((T)=>!T||T.length>fM||T.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${ot} non-empty bounded values`);let e=[],r=0,S=0,_=0,u=[];if(n.systemPrompt)r+=Buffer.byteLength(n.systemPrompt,"utf8"),e.push({role:"system",content:n.systemPrompt}),u.push(`System: ${At(n.systemPrompt)}`);for(let T of n.messages){let A=Array.isArray(T.content)?T.content:[T.content],L=[],w=[];for(let b of A){if(b.type==="text"){r+=Buffer.byteLength(b.text,"utf8"),L.push({type:"text",text:b.text}),w.push(At(b.text));continue}if(b.type==="image"){if(T.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!NM.has(b.mimeType))throw Error(`Unsupported MCP sampling image type: ${b.mimeType}`);let i=$M(b.data);S+=i,_++,L.push({type:"image_url",image_url:{url:`data:${b.mimeType};base64,${b.data}`}}),w.push(`[${b.mimeType} image, ${i} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${b.type}`)}if(L.length===0)throw Error("MCP sampling message has no supported content");e.push({role:T.role,content:L.length===1&&L[0]?.type==="text"?L[0].text:L}),u.push(`${T.role==="user"?"User":"Assistant"}: ${w.join(" ")}`)}if(r+S>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(_>bt||S>ct)throw Error("MCP sampling image input exceeds the shared attachment budget");let E=Q(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:e,maxTokens:Math.min(E,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...M],preview:u.join(`
|
|
21
|
+
`).slice(0,8000)}}function Ge(n,t,M){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let e=n.content,r=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",S=-1;for(let _ of M.stopSequences){let u=e.indexOf(_);if(u>=0&&(S===-1||u<S))S=u}if(S>=0)e=e.slice(0,S),r="stopSequence";if(Buffer.byteLength(e,"utf8")>st)throw Error(`MCP sampling response exceeds ${st} bytes`);return{model:t,role:"assistant",content:{type:"text",text:e},stopReason:r}}function Q(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function $M(n){if(!n||n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(n))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(n,"base64").byteLength}function At(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var De=256,We=1e4,Ze=86400000;var XM=/[\p{Cf}\p{Co}\p{Cn}]/u;function Lt(n){if(!n)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof n.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let t=f(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),M=f(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>M)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:f(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:f(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:M}}function Oe(n,t){return f(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function Je(n,t,M){let e=pM(n.taskId,"task ID",512),r=at(n.createdAt,"createdAt"),S=at(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(S)<Date.parse(r))throw Error("MCP task lastUpdatedAt precedes createdAt");if(M&&(e!==M.taskId||r!==M.createdAt))throw Error("MCP task identity changed across connection generation");let _=n.ttl===null?null:f(n.ttl,0,86400000,"MCP task ttl"),u=n.pollInterval===void 0?t.pollIntervalMs:f(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),E=Math.min(1e4,Math.max(100,u)),T=n.statusMessage?gM(n.statusMessage,e):void 0;return{taskId:e,status:n.status,createdAt:r,lastUpdatedAt:S,ttl:_,pollIntervalMs:E,...T?{statusMessage:T}:{}}}function ke(n){return["completed","failed","cancelled"].includes(n)}function ye(n){let t=n instanceof Error?n.message:String(n);return Pt(en(t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function gM(n,t){return Pt(en(n.replaceAll(t,"[redacted-task-id]")),1024)}function en(n){return[...n.normalize("NFKC")].filter((t)=>{let M=t.codePointAt(0)??0;if(M===0||M>=1&&M<=8||M===11||M===12||M>=14&&M<=31||M===127)return!1;return!XM.test(t)}).join("").trim()}function at(n,t){let M=Date.parse(n);if(!Number.isFinite(M))throw Error(`MCP task ${t} is invalid`);return new Date(M).toISOString()}function pM(n,t,M){if(!n||Buffer.byteLength(n)>M||en(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function f(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function Pt(n,t){let M=Buffer.from(n);if(M.length<=t)return n;let e=M.subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}var iM={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function rn(n){let t=n.toLowerCase().trim();return iM[t]??n}var RM=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,CM=/^\.[A-Za-z0-9_+-]{1,32}$/;function D(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function g(n,t,M,e,r){if(n===void 0)return r;if(!Number.isInteger(n)||Number(n)<M||Number(n)>e)throw Error(`${t} must be an integer between ${M} and ${e}`);return Number(n)}function xt(n,t){if(n===void 0)return;let M;try{M=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(M===void 0||Buffer.byteLength(M)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function zM(n,t){if(n===void 0)return{};if(!D(n))throw Error(`${t} must be an object`);let M={};for(let[e,r]of Object.entries(n)){if(!e||typeof r!=="string"||r.includes("\x00"))throw Error(`${t} must contain non-empty string values`);M[e]=r}return M}function h(n){if(n===void 0)return{};if(!D(n))throw Error("lspServers must be an object");let t=Object.entries(n);if(t.length>32)throw Error("lspServers exceeds the 32-server limit");let M={};for(let[e,r]of t){if(!RM.test(e))throw Error(`Invalid LSP server name: ${e}`);if(!D(r))throw Error(`lspServers.${e} must be an object`);let S=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),_=Object.keys(r).filter((w)=>!S.has(w));if(_.length>0)throw Error(`Unknown LSP server field: ${e}.${_[0]}`);if(typeof r.command!=="string"||!r.command.trim()||r.command.includes("\x00")||r.command.includes(`
|
|
22
|
+
`))throw Error(`lspServers.${e}.command must be a non-empty command`);if(r.args!==void 0&&!Array.isArray(r.args))throw Error(`lspServers.${e}.args must be an array`);let u=(r.args??[]).map((w,b)=>{if(typeof w!=="string"||w.includes("\x00"))throw Error(`lspServers.${e}.args.${b} must be a string`);return w});if(u.length>128)throw Error(`lspServers.${e}.args exceeds the 128-item limit`);if(!D(r.extensionToLanguage))throw Error(`lspServers.${e}.extensionToLanguage must be an object`);let E=Object.entries(r.extensionToLanguage);if(E.length===0||E.length>64)throw Error(`lspServers.${e}.extensionToLanguage must contain 1-64 entries`);let T={};for(let[w,b]of E){let i=w.startsWith(".")?w.toLowerCase():`.${w.toLowerCase()}`;if(!CM.test(i)||typeof b!=="string"||!b.trim())throw Error(`Invalid lspServers.${e}.extensionToLanguage entry: ${w}`);T[i]=b.trim()}if(r.enabled!==void 0&&typeof r.enabled!=="boolean")throw Error(`lspServers.${e}.enabled must be a boolean`);let A=xt(r.initializationOptions,`lspServers.${e}.initializationOptions`),L=xt(r.settings,`lspServers.${e}.settings`);M[e]={command:r.command.trim(),...u.length>0?{args:u}:{},extensionToLanguage:T,...r.env!==void 0?{env:zM(r.env,`lspServers.${e}.env`)}:{},...A!==void 0?{initializationOptions:A}:{},...L!==void 0?{settings:L}:{},...r.enabled!==void 0?{enabled:r.enabled}:{},priority:g(r.priority,`lspServers.${e}.priority`,-1000,1000,0),startupTimeout:g(r.startupTimeout,`lspServers.${e}.startupTimeout`,100,60000,1e4),shutdownTimeout:g(r.shutdownTimeout,`lspServers.${e}.shutdownTimeout`,100,1e4,2000),requestTimeout:g(r.requestTimeout,`lspServers.${e}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:g(r.diagnosticWaitTimeout,`lspServers.${e}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:g(r.maxRestarts,`lspServers.${e}.maxRestarts`,0,10,3)}}return M}function dt(n){return Number.isInteger(n)&&(n===-1||n>=0)}function ht(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import It from"node:path";var ft=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,BM=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function z(n){let t=[];for(let[M,e]of Object.entries(n)){if(!ft.test(M))throw Error(`Invalid plugin name in enabledPlugins: ${M}`);if(typeof e!=="boolean")throw Error(`Invalid enabledPlugins value for ${M}`);t.push([M,e])}return Object.fromEntries(t)}function _n(n,t,M){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((e,r)=>{if(typeof e!=="string"||!e.trim())throw Error(`${t}[${r}] must be a non-empty string`);return M(e.trim())}))].sort()}function B(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),M=Object.keys(n).filter((r)=>!t.has(r));if(M.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${M.join(", ")}`);let e={};for(let r of["restrictToAllowedSources","requireGitCommitSha"]){if(n[r]===void 0)continue;if(typeof n[r]!=="boolean")throw Error(`pluginSourcePolicy.${r} must be boolean`);e[r]=n[r]}if(n.allowedGitHosts!==void 0)e.allowedGitHosts=_n(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(r)=>{let S=r.toLowerCase();if(!BM.test(S))throw Error(`Invalid plugin Git host pattern: ${r}`);return S});if(n.allowedMarketplaces!==void 0)e.allowedMarketplaces=_n(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(r)=>{if(!ft.test(r))throw Error(`Invalid allowed Marketplace name: ${r}`);return r});if(n.allowedLocalRoots!==void 0)e.allowedLocalRoots=_n(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(r)=>{if(!It.isAbsolute(r))throw Error(`Plugin local allowlist root must be absolute: ${r}`);return It.resolve(r)});return e}function W(n){let t=[];for(let[M,e]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(M))throw Error(`Invalid environment variable name: ${M}`);if(typeof e!=="string"||e.includes("\x00"))throw Error(`Invalid environment variable value: ${M}`);t.push([M,e])}return Object.fromEntries(t)}class p{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!p.instance)p.instance=new p;return p.instance}static resetInstance(){p.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let M=(await d.getInstance().getStatus(a())).state==="trusted",e=await this.loadConfigFiles(M),r=await this.loadSettingsFiles(M),S={...e,...r,enabledPlugins:{...e.enabledPlugins||{},...r.enabledPlugins||{}}};if(n)S=this.mergeSettings(S,n);let _=this.normalizeConfig(S),u={...s,..._};if(u.enabledPlugins=z(u.enabledPlugins),u.lspServers=h(u.lspServers),u.pluginSourcePolicy={...s.pluginSourcePolicy,...B(u.pluginSourcePolicy)},this.resolveEnvInterpolation(u),process.env.BLADE_MODEL&&u.models?.length>0){let E=rn(process.env.BLADE_MODEL),T=u.models.find((A)=>A.id===E||A.model===E||A.id===process.env.BLADE_MODEL||A.model===process.env.BLADE_MODEL);if(T)u.currentModelId=T.id}if(process.env.BLADE_DEBUG)u.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(Z().configureModelProviders(u.modelProviders,u.models),u.models.length>0)this.validateConfig(u);if(u.debug)console.log("[ConfigManager] Configuration loaded successfully");return u}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),Z().configureModelProviders({},[]),s}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=m.join(c.homedir(),".blade","config.json"),M=m.join(a(),".blade","config.json"),e={},r=await this.loadJsonFile(t),S=r?await this.migrateLegacyUserConfig(r):null;if(S)e={...e,...S};let _=await this.loadJsonFile(M);if(_&&n){let u={...e.mcpServers||{},..._.mcpServers||{}},E={...e.lspServers||{},..._.lspServers||{}},T={...e.modelProviders||{},..._.modelProviders||{}},A={...e.enabledPlugins||{},..._.enabledPlugins||{}};if(e={...e,..._},Object.keys(u).length>0)e.mcpServers=u;if(Object.keys(E).length>0)e.lspServers=h(E);if(Object.keys(T).length>0)e.modelProviders=T;if(Object.keys(A).length>0)e.enabledPlugins=z(A)}else if(_?.hooks)e.hooks=_.hooks;return e}async migrateLegacyUserConfig(n){let t=n,M={...n},e={};if(M.codeTheme===void 0&&typeof t.theme==="string")M.codeTheme=t.theme,e.codeTheme=t.theme;if(Array.isArray(M.models)){let r=ln(M.models,M.currentModelId??"");if(r.changed)M.models=r.models,M.currentModelId=r.currentModelId,e.models=r.models,e.currentModelId=r.currentModelId}if(delete M.theme,Object.keys(e).length>0)try{await x.getInstance().save(e,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return M}async loadSettingsFiles(n){let t=m.join(c.homedir(),".blade","settings.json"),M=m.join(a(),".blade","settings.json"),e=m.join(a(),".blade","settings.local.json"),r={},S=await this.loadJsonFile(t);if(S)r=this.mergeSettings(r,S);let _=await this.loadJsonFile(M);if(_&&n)r=this.mergeSettings(r,_);else if(_?.hooks)r=this.mergeSettings(r,{hooks:_.hooks});let u=await this.loadJsonFile(e);if(u&&n)r=this.mergeSettings(r,u);else if(u?.hooks)r=this.mergeSettings(r,{hooks:u.hooks});return r}async loadWorkspacePermissions(n,t){let M={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(m.resolve(n)!==m.resolve(a())){let r=await this.loadWorkspacePermissionOverrides(a(),{includeUntrusted:!0}),S=await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),_={allow:Array.from(new Set([...s.permissions.allow,...S?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...s.permissions.ask,...S?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...s.permissions.deny,...S?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let u of["allow","ask","deny"]){let E=new Set(r[u].filter((T)=>!_[u].includes(T)));M[u]=M[u].filter((T)=>!E.has(T))}}let e=await this.loadWorkspacePermissionOverrides(n);for(let r of["allow","ask","deny"])M[r]=Array.from(new Set([...M[r],...e[r]]));return M}async loadWorkspaceMcpServers(n,t){if(m.resolve(n)===m.resolve(a()))return{...t};let M=await d.getInstance().getStatus(n),e=M.state==="trusted",r=M.projectPath,S={},_=async(E)=>{let T=await this.loadJsonFile(E);if(T?.mcpServers)S={...S,...T.mcpServers}};if(await _(m.join(c.homedir(),".blade","config.json")),await _(m.join(c.homedir(),".blade","settings.json")),e)await _(m.join(r,".blade","config.json")),await _(m.join(r,".blade","settings.json")),await _(m.join(r,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)S={...S,...this.lastAdditionalSettings.mcpServers};let u={mcpServers:S};return this.resolveEnvInterpolation(u),u.mcpServers}async loadWorkspaceLspServers(n,t){if(m.resolve(n)===m.resolve(a()))return h(t);let M=await d.getInstance().getStatus(n),e={},r=async(_)=>{let u=await this.loadJsonFile(_);if(u?.lspServers)e={...e,...h(u.lspServers)}};if(await r(m.join(c.homedir(),".blade","config.json")),await r(m.join(c.homedir(),".blade","settings.json")),M.state==="trusted")for(let _ of["config.json","settings.json","settings.local.json"])await r(m.join(M.projectPath,".blade",_));if(this.lastAdditionalSettings?.lspServers)e={...e,...h(this.lastAdditionalSettings.lspServers)};let S={lspServers:e};return this.resolveEnvInterpolation(S),h(S.lspServers)}async loadWorkspaceModelConfig(n,t){if(m.resolve(n)===m.resolve(a()))return{currentModelId:t.currentModelId,models:t.models.map((_)=>structuredClone(_)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout,...t.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:t.providerCircuitBreakerOpenMs}:{},...t.providerRequestConcurrency!==void 0?{providerRequestConcurrency:t.providerRequestConcurrency}:{},...t.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:t.providerRequestAdmissionMs}:{},...t.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:t.providerRequestPendingBytes}:{}};let M=await d.getInstance().getStatus(n),e=M.projectPath,r={currentModelId:s.currentModelId,models:s.models.map((_)=>structuredClone(_)),modelProviders:structuredClone(s.modelProviders),temperature:s.temperature,...s.maxOutputTokens!==void 0?{maxOutputTokens:s.maxOutputTokens}:{},timeout:s.timeout,...s.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:s.providerCircuitBreakerOpenMs}:{},...s.providerRequestConcurrency!==void 0?{providerRequestConcurrency:s.providerRequestConcurrency}:{},...s.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:s.providerRequestAdmissionMs}:{},...s.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:s.providerRequestPendingBytes}:{}},S=(_)=>{if(!_)return;if(_.modelProviders)r.modelProviders={...r.modelProviders,...structuredClone(_.modelProviders)};if(_.models)r.models=_.models.map((u)=>structuredClone(u));if(_.currentModelId!==void 0)r.currentModelId=_.currentModelId;if(_.temperature!==void 0)r.temperature=_.temperature;if(_.maxOutputTokens!==void 0)r.maxOutputTokens=_.maxOutputTokens;if(_.timeout!==void 0)r.timeout=_.timeout;if(_.providerCircuitBreakerOpenMs!==void 0)r.providerCircuitBreakerOpenMs=_.providerCircuitBreakerOpenMs;if(_.providerRequestConcurrency!==void 0)r.providerRequestConcurrency=_.providerRequestConcurrency;if(_.providerRequestAdmissionMs!==void 0)r.providerRequestAdmissionMs=_.providerRequestAdmissionMs;if(_.providerRequestPendingBytes!==void 0)r.providerRequestPendingBytes=_.providerRequestPendingBytes};if(S(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json"))),S(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json"))),M.state==="trusted")S(await this.loadJsonFile(m.join(e,".blade","config.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.local.json")));if(S(this.lastAdditionalSettings),r=this.normalizeConfig(r),this.resolveEnvInterpolation(r),process.env.BLADE_MODEL&&r.models.length>0){let _=process.env.BLADE_MODEL,u=rn(_),E=r.models.find((T)=>T.id===u||T.model===u||T.id===_||T.model===_);if(E)r.currentModelId=E.id}if(!r.models.some((_)=>_.id===r.currentModelId))r.currentModelId=r.models[0]?.id??"";return r}async loadWorkspaceRuntimeSettings(n,t){if(m.resolve(n)===m.resolve(a()))return{env:W(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let M=await d.getInstance().getStatus(n),e=M.projectPath,r={env:{},disableAllHooks:s.disableAllHooks,maxTurns:s.maxTurns,permissionMode:s.permissionMode},S=(E,T)=>{if(!E)return;if(T.allowExecutionSettings){if(E.env)r.env={...r.env,...W(E.env)};if(E.maxTurns!==void 0)r.maxTurns=E.maxTurns;if(E.permissionMode!==void 0)r.permissionMode=E.permissionMode;if(E.disableAllHooks!==void 0)r.disableAllHooks=E.disableAllHooks}else if(E.disableAllHooks===!0)r.disableAllHooks=!0};S(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),S(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let _=await Promise.all([this.loadJsonFile(m.join(e,".blade","config.json")),this.loadJsonFile(m.join(e,".blade","settings.json")),this.loadJsonFile(m.join(e,".blade","settings.local.json"))]);for(let E of _)S(E,{allowExecutionSettings:M.state==="trusted"});S(this.lastAdditionalSettings,{allowExecutionSettings:!0});let u={env:r.env};return this.resolveEnvInterpolation(u),r.env=W(u.env),r}async loadWorkspacePluginSettings(n){return(await this.loadWorkspacePluginSettingsResolution(n)).effective}async loadWorkspacePluginSettingsResolution(n){let t=await d.getInstance().getStatus(n),M={},e={},r=(S,_,u)=>{if(!S?.enabledPlugins)return;let E=z(S.enabledPlugins);for(let[T,A]of Object.entries(E)){if(!u&&A!==!1)continue;let L=e[T];M[T]=A,e[T]={effective:A,effectiveScope:_,layers:{...L?.layers??{},[_]:A}}}};r(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json")),"global",!0),r(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")),"global",!0);for(let S of["config.json","settings.json"])r(await this.loadJsonFile(m.join(t.projectPath,".blade",S)),"project",t.state==="trusted");return r(await this.loadJsonFile(m.join(t.projectPath,".blade","settings.local.json")),"local",t.state==="trusted"),r(this.lastAdditionalSettings,"invocation",!0),{effective:M,settings:e,workspaceTrusted:t.state==="trusted"}}async loadWorkspacePluginSourcePolicy(n){let t=await d.getInstance().getStatus(n),M={...s.pluginSourcePolicy,allowedGitHosts:[...s.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...s.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...s.pluginSourcePolicy.allowedLocalRoots]},e=(_)=>{if(!_?.pluginSourcePolicy)return;Object.assign(M,B(_.pluginSourcePolicy))},r=(_,u)=>{if(!u)return _;if(_.length===0&&!M.restrictToAllowedSources)return u;let E=new Set(u);return _.filter((T)=>E.has(T))},S=(_)=>{if(!_?.pluginSourcePolicy)return;let u=B(_.pluginSourcePolicy);M.allowedGitHosts=r(M.allowedGitHosts,u.allowedGitHosts),M.allowedMarketplaces=r(M.allowedMarketplaces,u.allowedMarketplaces),M.allowedLocalRoots=r(M.allowedLocalRoots,u.allowedLocalRoots),M.restrictToAllowedSources=M.restrictToAllowedSources||u.restrictToAllowedSources===!0,M.requireGitCommitSha=M.requireGitCommitSha||u.requireGitCommitSha===!0};e(await this.loadJsonFile(m.join(c.homedir(),".blade","config.json"))),e(await this.loadJsonFile(m.join(c.homedir(),".blade","settings.json")));for(let _ of["config.json","settings.json","settings.local.json"])S(await this.loadJsonFile(m.join(t.projectPath,".blade",_)));if(S(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")M.requireGitCommitSha=!0;return M}async loadWorkspaceHooks(n,t,M={}){if(m.resolve(n)===m.resolve(a())&&M.includeBaseForCurrentWorkspace!==!1)return K({},t);let e=K({},s.hooks),r=[m.join(c.homedir(),".blade","settings.json"),m.join(n,".blade","settings.json"),m.join(n,".blade","settings.local.json")];for(let S of r){let _=await this.loadJsonFile(S);if(_?.hooks)e=K({},e,_.hooks)}return e}async loadWorkspacePermissionOverrides(n,t={}){let M={allow:[],ask:[],deny:[]},e=(await d.getInstance().getStatus(n)).state==="trusted",r=[...e||t.includeUntrusted?[m.join(n,".blade","settings.json")]:[],...e||t.includeUntrusted?[m.join(n,".blade","settings.local.json")]:[]];for(let S of r){let _=await this.loadJsonFile(S);if(!_?.permissions)continue;for(let u of["allow","ask","deny"])M[u]=Array.from(new Set([...M[u],..._.permissions[u]||[]]))}return M}mergeSettings(n,t){let M={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)M.permissions={allow:Array.from(new Set([...n.permissions?.allow||[],...t.permissions.allow||[]])),ask:Array.from(new Set([...n.permissions?.ask||[],...t.permissions.ask||[]])),deny:Array.from(new Set([...n.permissions?.deny||[],...t.permissions.deny||[]]))};if(t.hooks)M.hooks=K({},M.hooks,t.hooks);if(t.enabledPlugins)M.enabledPlugins={...n.enabledPlugins||{},...z(t.enabledPlugins)};if(t.pluginSourcePolicy)M.pluginSourcePolicy={...n.pluginSourcePolicy??s.pluginSourcePolicy,...B(t.pluginSourcePolicy)};if(t.env)M.env=K({},M.env,t.env);if(t.mcpServers)M.mcpServers={...M.mcpServers||{},...t.mcpServers};if(t.lspServers)M.lspServers={...M.lspServers||{},...h(t.lspServers)};if(t.disableAllHooks!==void 0)M.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;return M}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,M=(r)=>{if(typeof r==="string")return r.replace(t,(S,_,u,E)=>{return process.env[_]||E||S});if(Array.isArray(r))return r.map(M);if(typeof r==="object"&&r!==null){let S=r;for(let[_,u]of Object.entries(S))S[_]=M(u);return S}return r},e=n;for(let[r,S]of Object.entries(e))e[r]=M(S)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Nt.readFile(n,"utf-8");return JSON.parse(t)}}catch(t){console.warn(`[ConfigManager] Failed to load ${n}:`,t)}return null}async fileExists(n){try{return await Nt.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n));if(t.codeTheme===void 0&&typeof t.theme==="string")t.codeTheme=t.theme;delete t.theme;let M=(r)=>r.trim().replace(/^`|`$/g,""),e=(r)=>{for(let[S,_]of Object.entries(r))if(typeof _==="string")r[S]=M(_);else if(Array.isArray(_))_.forEach((u,E)=>{if(typeof u==="string")_[E]=M(u);else if(typeof u==="object"&&u!==null)e(u)});else if(typeof _==="object"&&_!==null)e(_)};return e(t),t}validateConfig(n,t=Z()){let M=[];try{n.lspServers=h(n.lspServers)}catch(e){M.push(e instanceof Error?e.message:"Invalid LSP server configuration")}for(let[e,r]of Object.entries(n.mcpServers||{}))try{nt(r),r.oauth=O(r);let S=_t(r);if(r.logging!==void 0)r.logging=S;if(r.sampling)r.sampling=wt(r.sampling);if(r.tasks)r.tasks=Lt(r.tasks)}catch(S){M.push(`MCP server "${e}": ${S instanceof Error?S.message:"invalid sampling policy"}`)}for(let[e,r]of Object.entries(n.modelProviders||{}))if(M.push(...$t(e,r)),t.isReservedProviderId(e))M.push(`modelProviders.${e}: built-in provider ids cannot be overridden`);if(M.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(e){M.push(e instanceof Error?e.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)M.push("没有可用的模型配置");if(!dt(n.maxTurns))M.push(`maxTurns 必须是 ${ht()}`);if(!Qn(n.maxConcurrentTasks))M.push(`maxConcurrentTasks 必须是 ${Kn}-${Un} 之间的整数`);if(!Dn(n.maxQueuedTasks))M.push(`maxQueuedTasks 必须是 ${Hn}-${Yn} 之间的整数`);if(!Wn(n.maxQueuedTaskBytes))M.push(`maxQueuedTaskBytes 必须是 ${Vn}-${Gn} 之间的整数`);if(!zn(n.maxResidentSessionRuntimes))M.push(`maxResidentSessionRuntimes 必须是 ${$n}-${gn} 之间的整数`);if(!Bn(n.sessionRuntimeIdleMs))M.push(`sessionRuntimeIdleMs 必须是 ${pn}-${Cn} 之间的整数`);if(n.bashForegroundHandoffMs!==void 0&&!nn(n.bashForegroundHandoffMs))M.push("bashForegroundHandoffMs 必须是 0,或 "+`${fn}-${Nn} 之间的整数`);if(n.providerForegroundRecoveryMs!==void 0&&!pt(n.providerForegroundRecoveryMs))M.push("providerForegroundRecoveryMs 必须是 0,或 "+`${Xt}-${gt} 之间的整数`);if(n.providerCircuitBreakerOpenMs!==void 0&&!Ct(n.providerCircuitBreakerOpenMs))M.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${it}-${Rt} 之间的整数`);if(n.providerRequestConcurrency!==void 0&&!qt(n.providerRequestConcurrency))M.push("providerRequestConcurrency 必须是 "+`${zt}-${Bt} 之间的整数`);if(n.providerRequestAdmissionMs!==void 0&&!Vt(n.providerRequestAdmissionMs))M.push("providerRequestAdmissionMs 必须是 0,或 "+`${Kt}-${Ut} 之间的整数`);if(n.providerRequestPendingBytes!==void 0&&!Gt(n.providerRequestPendingBytes))M.push("providerRequestPendingBytes 必须是 "+`${Ht}-${Yt} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)M.push("未设置当前模型 ID");else if(!n.models.find((r)=>r.id===n.currentModelId))M.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let e of n.models){let r=`模型 "${e.displayName||e.id}"`,S=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((u)=>(u in e));if(S.length>0)M.push(`${r}: 不再支持旧字段 ${S.join(", ")};请重新配置模型`);if(!e.model)M.push(`${r}: model 字段必填`);if(!e.provider)M.push(`${r}: provider 字段必填`);if(e.overrides?.baseUrl&&!e.overrides.baseUrl.startsWith("http"))M.push(`${r}: overrides.baseUrl "${e.overrides.baseUrl}" 不是有效的 HTTP URL`);let _=e.overrides?.streamIdleTimeout;if(_!==void 0&&(!Number.isFinite(_)||_<1000))M.push(`${r}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(e.provider,e.model)}catch{M.push(`${r}: 内置 catalog 中不存在 ${e.provider}/${e.model}`)}}}if(M.length>0)throw Error(`配置验证失败:
|
|
23
|
+
${M.map((e)=>` - ${e}`).join(`
|
|
24
|
+
`)}
|
|
25
|
+
|
|
26
|
+
`+`请通过以下方式之一提供配置:
|
|
27
|
+
`+` 1. 首次启动: 运行 blade,系统会自动引导配置
|
|
28
|
+
`+` 2. 添加模型: blade 后输入 /model add
|
|
29
|
+
`+` 3. 初始化向导: 输入 /init
|
|
30
|
+
|
|
31
|
+
`+`配置文件示例 (~/.blade/config.json):
|
|
32
|
+
`+`{
|
|
33
|
+
"currentModelId": "model-id-123",
|
|
34
|
+
"models": [
|
|
35
|
+
{
|
|
36
|
+
"id": "model-id-123",
|
|
37
|
+
`+` "displayName": "默认模型",
|
|
38
|
+
`+` "provider": "deepseek",
|
|
39
|
+
"model": "deepseek-v4-pro"
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
`)}}function zr(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((r)=>r.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)M.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)M.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)M.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
|
|
44
|
+
export{U as Oe,O as Pe,N as Qe,v as Re,Ln as Se,$ as Te,nt as Ue,ie as Ve,V as We,ze as Xe,Be as Ye,Ke as Ze,_t as _e,LM as $e,Ue as af,PM as bf,He as cf,wt as df,Ve as ef,Ge as ff,De as gf,We as hf,Ze as if,Lt as jf,Oe as kf,Je as lf,ke as mf,ye as nf,Ae as of,fn as pf,Nn as qf,ce as rf,$n as sf,Xn as tf,gn as uf,pn as vf,Rn as wf,Cn as xf,ae as yf,zn as zf,Bn as Af,Kn as Bf,Un as Cf,Hn as Df,Yn as Ef,qn as Ff,Vn as Gf,Gn as Hf,Qn as If,Dn as Jf,Wn as Kf,s as Lf,h as Mf,mM as Nf,B as Of,W as Pf,p as Qf,zr as Rf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Fb as HJ}from"./chunk-te95z52n.js";import{Gb as l0,Nb as O6,Ob as U6,Pb as $2,Qb as J2,Xb as H6,dc as C$,nc as y0,pc as G2,qc as X1,rc as O2,yc as f$}from"./chunk-wm944thh.js";import{Dc as t,Gc as D6,Hc as O0}from"./chunk-1yjzj2d0.js";import{Hd as T6}from"./chunk-7pmpm5yq.js";import{Id as ZJ,Jd as C0,Kd as a6,Nd as WJ,Od as q2,Qd as Y6}from"./chunk-1e9866ye.js";import{ue as v0,ve as A0,ye as YJ}from"./chunk-vc32qrmq.js";import{He as Z$}from"./chunk-mt7fn8cv.js";import{Uf as a}from"./chunk-jv9zg1fw.js";import{tg as G0}from"./chunk-t2mc97k7.js";import{Hg as G6}from"./chunk-yqxyy3w2.js";import{Pg as H$,Rg as a2,Sg as z0,Tg as K1,Vg as L6,Xg as q6}from"./chunk-m3dvta6k.js";import{Yg as _8}from"./chunk-m8s208g3.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
|
|
1
|
+
import{Hb as HJ}from"./chunk-mrsc4a55.js";import{Ac as f$,Ib as l0,Pb as O6,Qb as U6,Rb as $2,Sb as J2,Zb as H6,fc as C$,pc as y0,rc as G2,sc as X1,tc as O2}from"./chunk-g96t2yrz.js";import{Fc as t,Ic as D6,Jc as O0}from"./chunk-56qew7w0.js";import{Jd as T6}from"./chunk-wwvb6znp.js";import{Kd as ZJ,Ld as C0,Md as a6,Pd as WJ,Qd as q2,Sd as Y6}from"./chunk-egczvfsv.js";import{Ae as YJ,we as v0,xe as A0}from"./chunk-tpa75y39.js";import{Je as Z$}from"./chunk-706zda55.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Eg as G0}from"./chunk-fhnkyqfb.js";import{Sg as G6}from"./chunk-j0k3mbkd.js";import{_g as H$,ah as a2,bh as z0,ch as K1,eh as L6,gh as q6}from"./chunk-qb0sqh29.js";import{hh as _8}from"./chunk-hfrcwkc8.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,r0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class Y$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function n0($){return $.executionEngine?.getContextManager()}async function K0($,J,Z,W=null,Y,H={}){let K=H.required??$.executionEngine!==void 0;try{let X=n0($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)aJ(J,Z);return z}if(K&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(M0.warn("[Loop] 保存用户消息失败:",X),K)throw new Y$("user_message",{cause:X})}return null}async function g($,J,Z,W,Y,H,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=n0($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let j=await Q.saveMessage(J.sessionId,"assistant",Z,W,H,J.subagentInfo,Y);if(X&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(M0.warn("[Loop] 保存助手消息失败:",Q),X)throw new Y$("assistant_message",{cause:Q})}return null}async function t2($,J,Z){try{let W=n0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",c1,Z,void 0,J.subagentInfo)}catch(W){M0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let H=n0($);if(!H||!J.sessionId||Z.length===0)return null;return await H.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(H){M0.warn("[Loop] 保存 contextual project rules provenance 失败:",H)}return null}async function i1($,J,Z,W,Y,H={}){try{let K=n0($);if(K&&J.sessionId){let X=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(H.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(H.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(M0.warn("[Loop] 保存工具调用失败:",K),H.required)throw K}return null}async function Z1($,J,Z,W,Y,H,K,X,Q,z={}){try{let j=n0($);if(j&&J.sessionId){let q=await j.saveToolResult(J.sessionId,Z,W,Y,H,K,J.subagentInfo,X,Q);if(z.required&&!q)throw Error("Durable tool-result commit returned no identity");return q}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(M0.warn("[Loop] 保存工具结果失败:",j),z.required)throw j}return null}async function T$($,J,Z,W,Y={}){try{let H=n0($);if(H&&J.sessionId){let K=await H.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(H){if(M0.warn("[Loop] 保存压缩数据失败:",H),Y.required)throw H}return null}import{createHash as y4}from"node:crypto";import{promises as K8}from"node:fs";import X8 from"node:path";import{nanoid as R0}from"nanoid";import*as i from"node:fs/promises";import*as o0 from"node:path";var $6={enabled:!0,maxIndexLines:200};var sJ="memory",J6="MEMORY.md";class l1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=H$($);this.memoryDir=o0.join(W,sJ)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await i.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=o0.join(this.memoryDir,J6);try{let J=await i.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -118,7 +118,7 @@ Full output saved to: ${X}`}catch{return`${J}
|
|
|
118
118
|
|
|
119
119
|
${Y}`}}import{Mutex as M8}from"async-mutex";import{nanoid as h8}from"nanoid";import*as w0 from"node:fs/promises";import*as j6 from"node:path";import{Mutex as G8}from"async-mutex";import O8 from"write-file-atomic";var H1=1,M$=8388608;function V6($,J){let Z={version:H1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
120
120
|
`}function s1($,J){return $ instanceof Error&&"code"in $&&$.code===J}function U8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function y8($,J,Z){let W;try{W=JSON.parse($)}catch(H){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:H})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==H1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((H)=>{if(!H||typeof H!=="object"||!("id"in H)||typeof H.id!=="string"||!("content"in H)||!U8(H.content)||!("queuedAt"in H)||typeof H.queuedAt!=="number"||"persisted"in H&&typeof H.persisted!=="boolean"||"origin"in H&&H.origin!=="user"&&H.origin!=="background_subagent"||"metadata"in H&&(H.metadata===null||typeof H.metadata!=="object"||Array.isArray(H.metadata))||"outputSchema"in H&&H.outputSchema!==void 0&&(!H.outputSchema||typeof H.outputSchema!=="object"||Array.isArray(H.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in H&&H.outputSchema!==void 0?X1(H.outputSchema).schema:void 0;return{id:H.id,content:H.content,queuedAt:H.queuedAt,..."persisted"in H&&H.persisted===!0?{persisted:!0}:{},..."origin"in H&&H.origin?{origin:H.origin}:{},..."metadata"in H&&H.metadata?{metadata:JSON.parse(JSON.stringify(H.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:H1,sessionId:Z,messages:Y}}function F8($){return new Set($.flatMap((J)=>J.type==="inbox_acknowledged"?J.data.messageIds:[]))}class Q1{workspaceRoot;sessionId;filePath;mutex=new G8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new Q1($,J,K1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=V6(this.sessionId,Z);if(Buffer.byteLength(W)>M$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:H1,sessionId:this.sessionId,messages:[]};try{if((await w0.stat(this.filePath)).size>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await w0.chmod(this.filePath,384),$=y8(await w0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let J=z0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F8(D6(await w0.readFile(J,"utf8"),J))}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await w0.mkdir(j6.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await w0.unlink(this.filePath).catch((W)=>{if(!s1(W,"ENOENT"))throw W});return}let Z=J??V6(this.sessionId,$);if(Buffer.byteLength(Z)>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await O8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as U0 from"node:fs/promises";import*as y6 from"node:path";import{nanoid as s}from"nanoid";class a0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new O0(z0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=a0.instances.get(Z);if(!W)W=new a0($,J),a0.instances.set(Z,W);return W}static release($,J){a0.instances.delete(`${J}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z)await $.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function Q$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class S0 extends Error{}var b8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",N8=20,P8=1e4,S8=1e5,A8=2592000000,w6=128,E8=1e6;function f8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>w6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>E8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>w6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function F6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,H=Y.turnId,K=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,z=Y.durationMs,j=Array.isArray(K)?K.filter((V)=>typeof V==="string"&&V.length>0&&V.length<=128):[];if(typeof H!=="string"||H.length===0||H.length>128||J!==void 0&&H!==J||!Array.isArray(K)||K.length>N8||j.length!==K.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>P8||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>A8)return;let q;if("goalFinalization"in Y){if(q=f8(Y.goalFinalization),!q)return}return{turnId:H,inputMessageIds:[...new Set(j)],turnsCount:X,toolCallsCount:Q,durationMs:z,...q?{goalFinalization:q}:{}}}function T8($,J){let Z=t($),W=Z.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(W<0)return;for(let Y=Z.length-1;Y>W;Y--){let H=Z[Y];if(H?.type!=="message_created")continue;let K=F6(H,J);if(K)return K}return}function k8($){let J=t($);for(let Z=J.length-1;Z>=0;Z--){let W=J[Z];if(W?.type!=="message_created")continue;let Y=F6(W);if(!Y?.goalFinalization)continue;if(!J.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===Y.turnId))continue;return{turnId:Y.turnId,finalization:Y}}return}function t1($,J){let Z=t($),W=J?Z.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&W<0)return{all:[],orphaned:[]};let Y=new Map,H=new Set,K=new Set;for(let Q of Z.slice(W+1)){if(Q.type==="interaction_requested"){K.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let z=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},j=typeof z.toolCallId==="string"?z.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")Y.set(j,{toolCallId:j,messageId:Q.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(Q.data.partType==="tool_result")H.add(j),H.add(Q.data.partId),H.add(Q.data.messageId)}let X=[...Y.values()];return{all:X,orphaned:X.filter((Q)=>!H.has(Q.toolCallId)&&!K.has(Q.toolCallId))}}class I0{projectPath;maxSessions;version;constructor($=a(),J=100,Z=G6()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:s(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:L6(this.projectPath),version:this.version,data:Z}}log($){return a0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=z0(this.projectPath,$);if((await new O0(Z).readAll()).length>0)return;let H=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:H,updatedAt:H},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=O6;return J}async initialize(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,H,K){try{await this.ensureSessionCreated($,H);let X=new Date().toISOString(),Q=s(),z={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},j=this.createEvent("message_created",$,z),q=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"reasoning",payload:{text:K},createdAt:X})]:[],V=typeof Z==="string"?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((D)=>this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:D.type==="text"?"text":"image",payload:D.type==="text"?{text:D.text}:{mimeType:x8(D.image_url.url)??"image/png",dataUrl:D.image_url.url},createdAt:X}));return await this.log($).commitBatch([j,...q,...V]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Y.some((V)=>V.type==="inbox_acknowledged"&&V.data.messageIds.includes(J.inboxMessageId)),K=Y.find((V)=>V.type==="message_created"&&V.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((V)=>{if(V.type!=="part_created"||V.data.partType!=="tool_call"||!V.data.payload||typeof V.data.payload!=="object"||Array.isArray(V.data.payload))return!1;let D=V.data.payload;if(D.toolName!=="Task"||!D.input||typeof D.input!=="object"||Array.isArray(D.input))return!1;let b=D.input,T=b.resume_from??b.resume;return b.run_in_background===!0&&b.subagent_session_id===J.childSessionId&&b.description===J.subagentRef.subagentDescription&&(b.subagent_type===void 0||b.subagent_type===J.subagentRef.subagentType)&&(b.resume_from===void 0||b.resume===void 0||b.resume_from===b.resume)&&(T===void 0?J.subagentRef.subagentResumedFrom===void 0:T===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:H,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(H)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let Q=Y.find((V)=>V.type==="part_created"&&V.data.partType==="subtask_ref"&&V.data.payload!==null&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)&&V.data.payload.childSessionId===J.childSessionId&&V.data.payload.status===J.subagentRef.subagentStatus);if(K&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let z=new Date().toISOString(),j=K?.data.messageId??s(),q=[];if(!K){let V={messageId:j,role:"user",inboxMessageId:J.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(J.metadata))};q.push(this.createEvent("message_created",$,V)),q.push(this.createEvent("part_created",$,{partId:s(),messageId:j,partType:"text",payload:{text:J.content},createdAt:z}))}if(!Q){let V=Y.findLast((b)=>b.type==="part_created"&&b.data.partType==="subtask_ref"&&b.data.messageId===X.data.messageId&&b.data.payload!==null&&typeof b.data.payload==="object"&&!Array.isArray(b.data.payload)&&b.data.payload.childSessionId===J.childSessionId),D=V?.data.payload&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)?V.data.payload:void 0;q.push(this.createEvent("part_created",$,{partId:s(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof D?.startedAt==="string"?D.startedAt:z,finishedAt:z},createdAt:z}))}return Z={eligible:!0,acknowledged:!1,persisted:q.length>0,messageId:j},q}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=t(Z);if(W.some((H)=>H.type==="turn_started"&&H.data.turnId===J.turnId))throw new S0;let Y=Q$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof S0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),K=[...new Set(Z)].filter((z)=>!H.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||K.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let Q=Q$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof S0))throw W}}async saveTurnAbort($,J){await this.saveTurnTerminal($,"turn_aborted",J)}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=t(J),W=Q$(Z).active;return W?t1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=t(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let H=Y.input;return H.run_in_background===!0&&typeof H.subagent_session_id==="string"?[H.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Q$(Y).active,K=t1(Y);if(!H&&K.orphaned.length===0)throw new S0;let X=H?T8(Y,H.turnId):void 0;if(H&&X&&K.orphaned.length===0){Z={turnId:H.turnId,outcome:"completed",finalization:X};let V=new Set(Y.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),D=X.inputMessageIds.filter((T)=>!V.has(T)),b=new Date().toISOString();return[...D.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:D,acknowledgedAt:b})]:[],this.createEvent("turn_completed",$,{turnId:H.turnId,completedAt:b,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=H?{turnId:H.turnId,outcome:"aborted"}:void 0;let Q=H?t1(Y,H.turnId).all.length:0,z=new Date().toISOString(),j=H?Date.parse(H.startedAt):Number.NaN,q=K.orphaned.flatMap((V)=>{let D=J.adoptedToolResults?.get(V.toolCallId),b=D?.toolCallId===V.toolCallId&&D.toolName===V.toolName?D:void 0,T=this.createEvent("part_created",$,{partId:V.toolCallId,messageId:b?V.messageId:V.toolCallId,partType:"tool_result",payload:b?{toolCallId:V.toolCallId,toolName:V.toolName,output:b.output,error:b.error??null,...b.metadata===void 0?{}:{metadata:b.metadata}}:{toolCallId:V.toolCallId,toolName:V.toolName,output:null,error:b8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:z});if(!b?.subagentRef)return[T];let A=b.subagentRef;return[T,this.createEvent("part_created",$,{partId:s(),messageId:V.messageId,partType:"subtask_ref",payload:{childSessionId:A.subagentSessionId,agentType:A.subagentType,description:A.subagentDescription??"",status:A.subagentStatus,summary:A.subagentSummary??"",resumedFrom:A.subagentResumedFrom??null,rootAgentId:A.subagentRootId??A.subagentSessionId,resumeDepth:A.subagentResumeDepth??0,verificationVerdict:A.verificationVerdict??null,startedAt:z,finishedAt:z},createdAt:z})]});return H?[...q,this.createEvent("turn_aborted",$,{turnId:H.turnId,cause:"process_restart",abortedAt:z,turnsCount:0,toolCallsCount:Q,durationMs:Number.isFinite(j)?Math.max(0,Date.now()-j):0})]:q})}catch(W){if(!(W instanceof S0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?k8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_requested"&&H.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_recovered"&&H.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===H.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y){try{await this.ensureSessionCreated($,Y);let H=new Date().toISOString(),K=W??s(),X=[];if(!W){let j={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:H};X.push(this.createEvent("message_created",$,j))}let Q=s(),z={partId:Q,messageId:K,partType:"tool_call",payload:{toolCallId:Q,toolName:J,input:Z},createdAt:H};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,q=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,V=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(q&&V){let D={partId:s(),messageId:K,partType:"subtask_ref",payload:{childSessionId:q,agentType:V,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:H},createdAt:H};X.push(this.createEvent("part_created",$,D))}}return await this.log($).commitBatch(X),Q}catch(H){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,H),H}}async saveToolResult($,J,Z,W,Y=null,H,K,X,Q){try{await this.ensureSessionCreated($,K);let z=new Date().toISOString(),j=Y??s();return await this.log($).commitValidatedBatch((q)=>{let V=X?.subagentStatus==="running"?t(q).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===X.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,D=V?.data.payload,b=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},T=D?{...b,subagentSessionId:D.childSessionId,subagentType:D.agentType,description:D.description,subagentStatus:D.status,subagentSummary:D.summary,subagentResumedFrom:D.resumedFrom,subagentRootId:D.rootAgentId,subagentResumeDepth:D.resumeDepth,verificationVerdict:D.verificationVerdict}:Q,A=[];if(!Y){let k={messageId:j,role:"assistant",parentMessageId:void 0,createdAt:z};A.push(this.createEvent("message_created",$,k))}let x={partId:J,messageId:j,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:H??null,...T===void 0?{}:{metadata:T}},createdAt:z};if(A.push(this.createEvent("part_created",$,x)),X&&!V){let k=X.subagentStatus==="running"?null:z,W0={partId:s(),messageId:j,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:k},createdAt:z};A.push(this.createEvent("part_created",$,W0))}return A}),J}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),H=s(),K={messageId:H,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:s(),messageId:H,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:U6(Z.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(z),H}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=z0(this.projectPath,$),W=await new O0(J).readAll();return W.length>0?t(W):null}catch{return null}}async loadSession($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=W.find((H)=>H.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let z=Y.get(Q.data.messageId);if(z){let j=Q.data.payload;z.content=j.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let z=Y.get(Q.data.messageId);if(z)z.content=z.content?`${z.content}
|
|
121
|
-
[Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
121
|
+
[Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-z1aqe7ms.js"),H=await W();if(H)Y(H,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,H)=>H.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new S0;let K=Q$(Y).active;if(!K||K.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof S0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),H=await new O0(W).getStats();J+=H.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493});let J=y6.join($,".health-check");return await U0.writeFile(J,"test","utf-8"),await U0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return q6()}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var _6=131072,b6=new Map;function e1($,J){let Z=`${$}\x00${J}`,W=b6.get(Z);if(!W)W=new M8,b6.set(Z,W);return W}function Z2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>_6)throw Error(`${J} exceeds ${_6} bytes`);return JSON.parse(Z)}function N6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function C8($,J){if($.request.interactionType!=="elicitation")return Z2(J,"Interaction response");return Z2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function P6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function I8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function v8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
122
122
|
`)}function p8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=v8(J);return{toolOutput:`User answers:
|
|
123
123
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
124
124
|
${K}
|
|
@@ -201,4 +201,4 @@ ${E}`}if(typeof M==="object"&&M!==null)M=JSON.stringify(M,null,2);if(typeof M===
|
|
|
201
201
|
${f6(c0)}
|
|
202
202
|
</system-reminder>`,metadata:C$};G.appendControl("user",L);let B=await K0($,Z,L.content,Q,C$);if(B)Q=B}}if(W?.signal?.aborted)return j(K,X.length,W.signal);if(K>=j$&&(XJ||R)){if(I.info(`Warning: 达到轮次上限 ${j$} 轮`),W?.onTurnLimitReached){let L=await W.onTurnLimitReached({turnsCount:K});if(L?.continue){G.writeback();let B="failed",P,_,c;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let N=$.chatService.getConfig(),y=await K$.compact(Z.messages,{trigger:"auto",modelName:N.model,modelProvider:N.provider,maxContextTokens:N.maxContextTokens??0,apiKey:N.apiKey,baseURL:N.baseUrl,actualPreTokens:O1,signal:W?.signal,activeTask:j0,workspaceRoot:Z.workspaceRoot||a(),sessionId:Z.sessionId});if(y.usage)yield{kind:"token_usage",usage:G1(y.usage,N.maxContextTokens??0)};let S={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
203
203
|
|
|
204
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as
|
|
204
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as Pa,S$ as Qa,m4 as Ra,I1 as Sa,s$ as Ta,Q$ as Ua,d1 as Va,o2 as Wa,Y5 as Xa,E$ as Ya,a0 as Za,I0 as _a,yJ as $a,J$ as ab,l4 as bb,p1 as cb,g1 as db,m2 as eb,u1 as fb,c6 as gb,i6 as hb,r6 as ib,$$ as jb,a$ as kb,iJ as lb,K0 as mb,g as nb,i1 as ob,Z1 as pb,T$ as qb,h0 as rb,K$ as sb,Q1 as tb,e as ub,q1 as vb,s6 as wb,t6 as xb,e6 as yb,U4 as zb,w2 as Ab,KJ as Bb,C4 as Cb};
|