blade-code 0.10.120 → 0.10.122
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-40pzrpjc.js → chunk-0axgw6c3.js} +1 -1
- package/dist/{chunk-kzzw1kwk.js → chunk-0gyv0ws4.js} +1 -1
- package/dist/{chunk-6h0kgpgv.js → chunk-1dscrttm.js} +1 -1
- package/dist/{chunk-exv1nb2x.js → chunk-2cdnsdx2.js} +1 -1
- package/dist/{chunk-sefdw1mm.js → chunk-2kgp4h99.js} +1 -1
- package/dist/{chunk-1qbq7x98.js → chunk-4jt2gxzt.js} +1 -1
- package/dist/{chunk-0fyy97rq.js → chunk-5h1x1a11.js} +1 -1
- package/dist/{chunk-5hmeb6yk.js → chunk-5n1ymw0p.js} +1 -1
- package/dist/{chunk-j8hzgacj.js → chunk-6xmz6mn0.js} +1 -1
- package/dist/{chunk-4de6e3am.js → chunk-7k4ehjfj.js} +1 -1
- package/dist/{chunk-56fb0ece.js → chunk-7w1z4hdy.js} +1 -1
- package/dist/{chunk-36k5c6wy.js → chunk-9byspsen.js} +1 -1
- package/dist/{chunk-2w10er3y.js → chunk-9vrsygd9.js} +1 -1
- package/dist/{chunk-8mqbaptr.js → chunk-b62w3ceq.js} +1 -1
- package/dist/chunk-bn6g1g8k.js +169 -0
- package/dist/{chunk-2v8fyvmh.js → chunk-cqg8xkmd.js} +1 -1
- package/dist/{chunk-jn25d5qv.js → chunk-d1gnxqpg.js} +1 -1
- package/dist/{chunk-y1n8nf5w.js → chunk-d59y2wwj.js} +1 -1
- package/dist/{chunk-zp8d0ma8.js → chunk-dwqqvn2w.js} +1 -1
- package/dist/{chunk-gjw3g2jd.js → chunk-edqe893j.js} +1 -1
- package/dist/chunk-gades6fm.js +1 -0
- package/dist/{chunk-150w9kq4.js → chunk-gqfa43gv.js} +1 -1
- package/dist/{chunk-4jaqzjtw.js → chunk-j0efq6yy.js} +1 -1
- package/dist/{chunk-t169d8dc.js → chunk-j19j9ypt.js} +1 -1
- package/dist/{chunk-dfcc8q87.js → chunk-j8ae2jpv.js} +2 -2
- package/dist/{chunk-7k72dxwe.js → chunk-jg81tz55.js} +1 -1
- package/dist/{chunk-6k7s3c7y.js → chunk-jhcxqhj9.js} +1 -1
- package/dist/{chunk-j2pgrrkb.js → chunk-khewsbnt.js} +1 -1
- package/dist/{chunk-v95hk3fw.js → chunk-mzjw10nw.js} +1 -1
- package/dist/{chunk-kvf61fb1.js → chunk-n8xv0whr.js} +1 -1
- package/dist/chunk-nm7cm174.js +1 -0
- package/dist/{chunk-ne40tv38.js → chunk-p6spv3yg.js} +1 -1
- package/dist/{chunk-x4t1v4rb.js → chunk-qk0yyvgk.js} +3 -3
- package/dist/{chunk-c5291k2x.js → chunk-tyvzbbwd.js} +1 -1
- package/dist/chunk-xb5g8q82.js +8 -0
- package/dist/{chunk-dspjxf4c.js → chunk-yyp7awr7.js} +1 -1
- package/dist/{chunk-m9vhf4dg.js → chunk-zqt0f9hc.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-49javhkx.js +0 -169
- package/dist/chunk-cmcgqa1d.js +0 -1
- package/dist/chunk-qp8qcmx0.js +0 -1
- package/dist/chunk-scgq3g37.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as Xt,ac as En,bc as yn,cc as bn}from"./chunk-sca5q3tt.js";import{ug as Bt}from"./chunk-
|
|
1
|
+
import{$b as Xt,ac as En,bc as yn,cc as bn}from"./chunk-sca5q3tt.js";import{ug as Bt}from"./chunk-j19j9ypt.js";import{Ag as vi,Bg as sn,Cg as zt,Dg as U,Eg as en,Fg as gt,Gg as mt,Ig as rn,Jg as Tn,Kg as B,Lg as dn,Mg as on,Ng as pn,Og as lt,Pg as un,Qg as cn,Rg as Mn,Tg as S,Wg as wn,Xg as Gt,Yg as Ut,Zg as h,_g as Ht,zg as xt}from"./chunk-jg81tz55.js";import{Fh as X,Hh as x}from"./chunk-9fgkg1vr.js";import{Th as It}from"./chunk-kzzty3v5.js";import{Hi as tn,Ii as nn}from"./chunk-5n1ymw0p.js";import{$i as ns}from"./chunk-m7b779kd.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-0fyy97rq.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-40pzrpjc.js";import{$ as PH,E as XH,Z as GH,aa as FH,ea as EH}from"./chunk-x4t1v4rb.js";import"./chunk-dabq8kdx.js";import"./chunk-2v8fyvmh.js";import"./chunk-fpjhg6ce.js";import{Hb as UH,Qb as _H,vb as r}from"./chunk-150w9kq4.js";import"./chunk-sca5q3tt.js";import{Jd as m,Ud as s,ud as jH,yd as xH}from"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{se as zH}from"./chunk-kzzw1kwk.js";import{ue as fH,ve as AH,we as SH}from"./chunk-4de6e3am.js";import{xe as MH}from"./chunk-3jqd18d8.js";import"./chunk-twdfyk78.js";import{Xe as WH}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-6h0kgpgv.js";import"./chunk-j2pgrrkb.js";import{ig as qH}from"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import"./chunk-7k72dxwe.js";import{Dh as DH}from"./chunk-kz15jy62.js";import{Fh as LH,Hh as H,Ih as $H,Kh as N}from"./chunk-9fgkg1vr.js";import{Oh as i,Ph as o}from"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(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,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],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 p("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))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=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(rH)}),eH=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"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=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())}),KJ=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())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=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())}),$J=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())}),qJ=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())}),XJ=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())}),YJ=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()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=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()}),DJ=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())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=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}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=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}))}),_J=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()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=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})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=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"]))}),FJ=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}))}),EJ=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}))}),MJ=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()}),zJ=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()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=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())}),TJ=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})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(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 kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>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",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=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(DH)),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(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{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 OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(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 lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-5h1x1a11.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-0axgw6c3.js";import{$ as PH,E as XH,Z as GH,aa as FH,ea as EH}from"./chunk-qk0yyvgk.js";import"./chunk-dabq8kdx.js";import"./chunk-cqg8xkmd.js";import"./chunk-fpjhg6ce.js";import{Hb as UH,Qb as _H,vb as r}from"./chunk-gqfa43gv.js";import"./chunk-sca5q3tt.js";import{Jd as m,Ud as s,ud as jH,yd as xH}from"./chunk-2kgp4h99.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{se as zH}from"./chunk-0gyv0ws4.js";import{ue as fH,ve as AH,we as SH}from"./chunk-7k4ehjfj.js";import{xe as MH}from"./chunk-3jqd18d8.js";import"./chunk-twdfyk78.js";import{Xe as WH}from"./chunk-4jt2gxzt.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-1dscrttm.js";import"./chunk-khewsbnt.js";import{ig as qH}from"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-jg81tz55.js";import{Dh as DH}from"./chunk-kz15jy62.js";import{Fh as LH,Hh as H,Ih as $H,Kh as N}from"./chunk-9fgkg1vr.js";import{Oh as i,Ph as o}from"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(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,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],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 p("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))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=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(rH)}),eH=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"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=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())}),KJ=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())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=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())}),$J=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())}),qJ=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())}),XJ=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())}),YJ=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()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=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()}),DJ=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())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=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}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=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}))}),_J=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()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=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})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=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"]))}),FJ=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}))}),EJ=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}))}),MJ=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()}),zJ=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()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=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())}),TJ=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})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(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 kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>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",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=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(DH)),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(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{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 OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(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 lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function cJ(K){return`[task] [${K.status}] ${K.subject}`}function uJ(){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 dJ(K){if(!(K instanceof Error))return"Unknown error";let X=K.lastError??K;if(X.responseBody)try{let W=JSON.parse(X.responseBody)?.error?.message;if(W)return X.statusCode?`${W} (HTTP ${X.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function pJ(K){return K==="jsonl"?"jsonl":"text"}function NH(K,V){let Q=(...X)=>{for(let J of X){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 vJ(K,V,Q,X){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)&&!X.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(X.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:X.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function QH(K,V,Q=!1){let X=(J,Z)=>{K.stdout.write(`${JSON.stringify(BH(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){X("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return X("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){X("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){X("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qe as N}from"./chunk-
|
|
1
|
+
import{Qe as N}from"./chunk-4jt2gxzt.js";import{ug as $}from"./chunk-j19j9ypt.js";import{Th as _}from"./chunk-kzzty3v5.js";import{ri as Y,ti as Z}from"./chunk-w4xqaw4h.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as ye,y as ze,j as Ae,C as Be};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ue as a,ve as b,we as c}from"./chunk-
|
|
1
|
+
import{ue as a,ve as b,we as c}from"./chunk-7k4ehjfj.js";import"./chunk-3jqd18d8.js";import"./chunk-4jt2gxzt.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-85bamng3.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-xb5g8q82.js";import"./chunk-anjpwev3.js";import"./chunk-nq0w1j1a.js";import"./chunk-7w1z4hdy.js";import"./chunk-9vrsygd9.js";import"./chunk-0axgw6c3.js";import"./chunk-qk0yyvgk.js";import"./chunk-dabq8kdx.js";import"./chunk-cqg8xkmd.js";import"./chunk-fpjhg6ce.js";import"./chunk-gqfa43gv.js";import"./chunk-sca5q3tt.js";import"./chunk-2kgp4h99.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as n}from"./chunk-d59y2wwj.js";import"./chunk-twdfyk78.js";import{Ve as s}from"./chunk-4jt2gxzt.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-1dscrttm.js";import"./chunk-khewsbnt.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{se as a,te as b}from"./chunk-0gyv0ws4.js";import"./chunk-5n1ymw0p.js";import"./chunk-m7b779kd.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{dc as M4}from"./chunk-sca5q3tt.js";import{$c as m2,Jd as g0,Ld as Q6,Md as h1,Nd as X6,Ud as o$,Xc as IJ,Zc as uJ,_c as gJ,ad as l2,fc as X$,gd as pJ,hd as R4,id as h4,jd as u2,kd as v1,ld as x4,md as k4,nd as S1,rd as wJ,zd as K1}from"./chunk-sefdw1mm.js";import{Zd as T4}from"./chunk-q265drks.js";import{$d as B0,ce as EJ,de as I0}from"./chunk-7dykmcjj.js";import{ef as $4}from"./chunk-ye4wyq1k.js";import{ff as E4,gf as i0,hf as y4,if as jJ,lf as E1,mf as K6,nf as BJ,of as UJ,qf as DJ}from"./chunk-kpqdfn9z.js";import{$f as J$,ag as r0,dg as S4,hg as z4}from"./chunk-0zzh482s.js";import{ug as P$}from"./chunk-t169d8dc.js";import{Eh as oJ}from"./chunk-kz15jy62.js";import{Th as j0}from"./chunk-kzzty3v5.js";import{ti as v0}from"./chunk-w4xqaw4h.js";import{Hi as CJ}from"./chunk-5hmeb6yk.js";import{Si as b$,Ui as n6,Vi as _0,Wi as R1,Yi as xJ,Zi as kJ,_i as vJ}from"./chunk-spxb931p.js";import{$i as O8}from"./chunk-m7b779kd.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function R6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function $5($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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 V of Y)if(typeof V==="string"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<turn_aborted>
|
|
1
|
+
import{dc as M4}from"./chunk-sca5q3tt.js";import{$c as m2,Jd as g0,Ld as Q6,Md as h1,Nd as X6,Ud as o$,Xc as IJ,Zc as uJ,_c as gJ,ad as l2,fc as X$,gd as pJ,hd as R4,id as h4,jd as u2,kd as v1,ld as x4,md as k4,nd as S1,rd as wJ,zd as K1}from"./chunk-2kgp4h99.js";import{Zd as T4}from"./chunk-q265drks.js";import{$d as B0,ce as EJ,de as I0}from"./chunk-7dykmcjj.js";import{ef as $4}from"./chunk-ye4wyq1k.js";import{ff as E4,gf as i0,hf as y4,if as jJ,lf as E1,mf as K6,nf as BJ,of as UJ,qf as DJ}from"./chunk-kpqdfn9z.js";import{$f as J$,ag as r0,dg as S4,hg as z4}from"./chunk-0zzh482s.js";import{ug as P$}from"./chunk-j19j9ypt.js";import{Eh as oJ}from"./chunk-kz15jy62.js";import{Th as j0}from"./chunk-kzzty3v5.js";import{ti as v0}from"./chunk-w4xqaw4h.js";import{Hi as CJ}from"./chunk-5n1ymw0p.js";import{Si as b$,Ui as n6,Vi as _0,Wi as R1,Yi as xJ,Zi as kJ,_i as vJ}from"./chunk-spxb931p.js";import{$i as O8}from"./chunk-m7b779kd.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function R6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function $5($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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 V of Y)if(typeof V==="string"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",o6="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 _$ 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 z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)T5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let j=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function a6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",y2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function s6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.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(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let j=z$($);if(j&&J.sessionId){let B=await j.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(t0.warn("[Loop] 保存工具结果失败:",j),H.required)throw j}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.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(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,j=await C0(J,Z,Y,H,V);if(j)H=j;if(Q!==void 0){let B={role:"user",content:Q};if(X)B.metadata=X;W.appendControl("user",B);let z=await l0(J,Z,B.content,H,X);if(z)H=z}return H}import{createHash as H6}from"node:crypto";import{promises as i5}from"node:fs";import r5 from"node:path";import{nanoid as e0}from"nanoid";import*as Y0 from"node:fs/promises";import*as j$ from"node:path";var t6={enabled:!0,maxIndexLines:200};var M5="memory",e6="MEMORY.md";class P2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=j$.join(W,M5)}this.config={...t6,...J}}async initialize(){if(this.initialized)return;await Y0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=j$.join(this.memoryDir,e6);try{let J=await Y0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-
|
|
1
|
+
import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-khewsbnt.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -25,7 +25,7 @@ import{yg as YO}from"./chunk-2t6b962t.js";import{Fh as qO,Hh as S,Kh as y}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-9byspsen.js"),{createChatServiceAsync:W}=await import("./chunk-p7k7hqtb.js"),{resolveModelConfig:J}=await import("./chunk-v6sfs4qf.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-jhcxqhj9.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{Bh as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-v1cmz2bw.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{Bh as Q}from"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as L}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import{$i as F}from"./chunk-m7b779kd.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-v1cmz2bw.js"),{SessionService:B}=await import("./chunk-tyvzbbwd.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Eh as Y}from"./chunk-kz15jy62.js";import{Fh as on,Gh as F,Hh as o}from"./chunk-9fgkg1vr.js";import{Lh as ct,Mh as bt}from"./chunk-pykxe413.js";import{Th as x}from"./chunk-kzzty3v5.js";import{$h as kn,Uh as Jn,Vh as Xt,Wh as pt,_h as gt,ai as it,bi as Rt,ci as Ct,di as un,ei as zt,fi as Bt,gi as On,hi as Kt,ii as Ut,ji as jn,ki as Ht,li as Yt,mi as qt,ni as Vt,oi as Qt,pi as Gt}from"./chunk-9jtjq50j.js";import{ti as fn}from"./chunk-w4xqaw4h.js";import{wi as $t,zi as J}from"./chunk-r6svhe3w.js";import{Hi as Pn,Ii as Ln}from"./chunk-
|
|
1
|
+
import{Eh as Y}from"./chunk-kz15jy62.js";import{Fh as on,Gh as F,Hh as o}from"./chunk-9fgkg1vr.js";import{Lh as ct,Mh as bt}from"./chunk-pykxe413.js";import{Th as x}from"./chunk-kzzty3v5.js";import{$h as kn,Uh as Jn,Vh as Xt,Wh as pt,_h as gt,ai as it,bi as Rt,ci as Ct,di as un,ei as zt,fi as Bt,gi as On,hi as Kt,ii as Ut,ji as jn,ki as Ht,li as Yt,mi as qt,ni as Vt,oi as Qt,pi as Gt}from"./chunk-9jtjq50j.js";import{ti as fn}from"./chunk-w4xqaw4h.js";import{wi as $t,zi as J}from"./chunk-r6svhe3w.js";import{Hi as Pn,Ii as Ln}from"./chunk-5n1ymw0p.js";import{Oi as h}from"./chunk-ncqagb27.js";import{Zi as Tn}from"./chunk-spxb931p.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(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:"&&Zt(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 k(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 _=t.clientId?.trim();if(_&&_.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||!Wt.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 r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=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}),sn=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}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{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 mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,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],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,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 L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.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 L.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>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.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 L.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 L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn 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 an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{wf as a,xf as b,yf as c}from"./chunk-
|
|
1
|
+
import{wf as a,xf as b,yf as c}from"./chunk-1dscrttm.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$f as b1,ag as L0,bg as z1,gg as N0}from"./chunk-0zzh482s.js";import{ng as jO,og as wO}from"./chunk-adkpwx6c.js";import{rg as A1}from"./chunk-85bamng3.js";import{sg as b0,ug as J0}from"./chunk-
|
|
1
|
+
import{$f as b1,ag as L0,bg as z1,gg as N0}from"./chunk-0zzh482s.js";import{ng as jO,og as wO}from"./chunk-adkpwx6c.js";import{rg as A1}from"./chunk-85bamng3.js";import{sg as b0,ug as J0}from"./chunk-j19j9ypt.js";import{Bh as I0,wh as S0,xh as GO}from"./chunk-jg81tz55.js";import{Fh as u,Hh as L,Kh as c1}from"./chunk-9fgkg1vr.js";import{Th as M}from"./chunk-kzzty3v5.js";import{ti as k,ui as S}from"./chunk-w4xqaw4h.js";import{Hi as u0}from"./chunk-5n1ymw0p.js";import{Oi as N}from"./chunk-ncqagb27.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Hi as S}from"./chunk-
|
|
1
|
+
import{Hi as S}from"./chunk-5n1ymw0p.js";import{$i as f}from"./chunk-m7b779kd.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as h,u as i,g as j,C as k,V as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-mzjw10nw.js";import"./chunk-5n1ymw0p.js";import"./chunk-m7b779kd.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-mzjw10nw.js";import"./chunk-5n1ymw0p.js";import"./chunk-m7b779kd.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-xb5g8q82.js";import"./chunk-anjpwev3.js";import"./chunk-nq0w1j1a.js";import"./chunk-7w1z4hdy.js";import"./chunk-9vrsygd9.js";import"./chunk-0axgw6c3.js";import"./chunk-qk0yyvgk.js";import"./chunk-dabq8kdx.js";import"./chunk-cqg8xkmd.js";import"./chunk-fpjhg6ce.js";import"./chunk-gqfa43gv.js";import"./chunk-sca5q3tt.js";import"./chunk-2kgp4h99.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as R}from"./chunk-d59y2wwj.js";import"./chunk-twdfyk78.js";import{Ve as Q}from"./chunk-4jt2gxzt.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-1dscrttm.js";import"./chunk-khewsbnt.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import{Hi as M}from"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|