blade-code 0.10.141 → 0.10.144

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.
Files changed (127) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-tya95jej.js → chunk-0tzecdv3.js} +1 -1
  4. package/dist/{chunk-be1fyzb3.js → chunk-10947adv.js} +5 -5
  5. package/dist/{chunk-fx4xr1g6.js → chunk-1xa8z2h3.js} +360 -357
  6. package/dist/{chunk-jsv3e4k6.js → chunk-2f8d0km4.js} +1 -1
  7. package/dist/{chunk-5q4z0sfr.js → chunk-2mk914vk.js} +2 -2
  8. package/dist/{chunk-4dtshx9v.js → chunk-2n97dt2h.js} +1 -1
  9. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  10. package/dist/chunk-4bgsnpg0.js +1 -0
  11. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  12. package/dist/chunk-4jqvrgpm.js +1 -0
  13. package/dist/{chunk-7xtxvrh8.js → chunk-4wx5sya5.js} +1 -1
  14. package/dist/chunk-5v0jcyea.js +2 -0
  15. package/dist/chunk-5y4btx3c.js +1 -0
  16. package/dist/{chunk-ae0fws1f.js → chunk-65cxn7bb.js} +2 -2
  17. package/dist/chunk-66wk3exc.js +1 -0
  18. package/dist/{chunk-v67st2xb.js → chunk-6a16zba3.js} +1 -1
  19. package/dist/chunk-6c972n1p.js +6 -0
  20. package/dist/{chunk-yjbpfd3b.js → chunk-6vcqajdc.js} +1 -1
  21. package/dist/chunk-8vd9y7ar.js +10 -0
  22. package/dist/chunk-96t1d492.js +1 -0
  23. package/dist/{chunk-j1pptwsq.js → chunk-99t5b3qh.js} +1 -1
  24. package/dist/chunk-9p0zyba2.js +1 -0
  25. package/dist/{chunk-4pexd8a7.js → chunk-a9h3xfdj.js} +1 -1
  26. package/dist/{chunk-h5xad96g.js → chunk-atcpkhxt.js} +1 -1
  27. package/dist/chunk-b5qxype0.js +1 -0
  28. package/dist/{chunk-frvdjy8y.js → chunk-b7b1h83p.js} +1 -1
  29. package/dist/{chunk-ryyzbd76.js → chunk-bwm0jt16.js} +1 -1
  30. package/dist/chunk-c1qjdcf9.js +1 -0
  31. package/dist/{chunk-cbgsjzdw.js → chunk-cd150xf2.js} +1 -1
  32. package/dist/chunk-cr6d4zxs.js +1 -0
  33. package/dist/{chunk-n34qsnks.js → chunk-ddvdc2p0.js} +1 -1
  34. package/dist/chunk-e12xrg41.js +2 -0
  35. package/dist/{chunk-sdapqhj0.js → chunk-eg3ms291.js} +1 -1
  36. package/dist/{chunk-kf9j9z9k.js → chunk-ehwn05np.js} +1 -1
  37. package/dist/chunk-ekjaa3h2.js +1 -0
  38. package/dist/{chunk-rv80nkve.js → chunk-fd7ez529.js} +1 -1
  39. package/dist/{chunk-0b67y4j1.js → chunk-j8hbddjp.js} +2 -2
  40. package/dist/{chunk-9tk6wq70.js → chunk-jq5bhnrd.js} +1 -1
  41. package/dist/{chunk-sd9bze9x.js → chunk-kv458q06.js} +1 -1
  42. package/dist/{chunk-4w8v677q.js → chunk-m7j6mq32.js} +1 -1
  43. package/dist/{chunk-tqg9y2p6.js → chunk-m9srdfa1.js} +1 -1
  44. package/dist/{chunk-fx9vm1n5.js → chunk-mh9nqbwa.js} +1 -1
  45. package/dist/{chunk-tp4yy3a6.js → chunk-mw3e5scz.js} +3 -3
  46. package/dist/chunk-n14kcb52.js +1 -0
  47. package/dist/{chunk-r5dmdsjb.js → chunk-ny2g84m0.js} +1 -1
  48. package/dist/{chunk-5v3eng7c.js → chunk-p102vt6w.js} +1 -1
  49. package/dist/{chunk-f2jm4x5q.js → chunk-pe6kcmvn.js} +2 -2
  50. package/dist/chunk-qdxk9rcw.js +1 -0
  51. package/dist/{chunk-7azws27d.js → chunk-qhr61n4y.js} +45 -45
  52. package/dist/{chunk-zrgfvc4k.js → chunk-qm0j4szw.js} +1 -1
  53. package/dist/{chunk-zj32chp7.js → chunk-rqz0589c.js} +1 -1
  54. package/dist/{chunk-pzxg2sdv.js → chunk-rrb49j43.js} +1 -1
  55. package/dist/{chunk-gm2yfq3r.js → chunk-rvs364rz.js} +2 -2
  56. package/dist/{chunk-0chvj0qt.js → chunk-s32yz7eq.js} +1 -1
  57. package/dist/{chunk-6w8p6c0g.js → chunk-s6x7fme7.js} +1 -1
  58. package/dist/{chunk-k3ne93k8.js → chunk-shb7g2vr.js} +1 -1
  59. package/dist/{chunk-34fmx68h.js → chunk-srd0aqsm.js} +1 -1
  60. package/dist/{chunk-3da7sqx6.js → chunk-sy59x1ts.js} +1 -1
  61. package/dist/chunk-v67t8jmc.js +1 -0
  62. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  63. package/dist/{chunk-83je3g6c.js → chunk-vgxzpvyb.js} +3 -3
  64. package/dist/{chunk-n9819k4p.js → chunk-vw9paban.js} +1 -1
  65. package/dist/{chunk-f2y0gxyq.js → chunk-w6qfbea8.js} +1 -1
  66. package/dist/chunk-wcps5gjm.js +2 -0
  67. package/dist/{chunk-v1mamd1x.js → chunk-wzqcea6x.js} +1 -1
  68. package/dist/{chunk-ppp4gpy4.js → chunk-x7gcmasv.js} +1 -1
  69. package/dist/{chunk-jbpasjg9.js → chunk-xmymx75h.js} +1 -1
  70. package/dist/{chunk-ze1ra6f9.js → chunk-ypfe8j02.js} +2 -2
  71. package/dist/{chunk-k1tfry97.js → chunk-z2k08r1h.js} +1 -1
  72. package/dist/{chunk-pv6cgfv1.js → chunk-zj1g4nbq.js} +1 -1
  73. package/dist/web/assets/ChatView-DuCQPnTY.js +63 -0
  74. package/dist/web/assets/{CodeBlockHighlighter-BC17_i4m.js → CodeBlockHighlighter-QAgXsft7.js} +1 -1
  75. package/dist/web/assets/{FilePreview-DuvfuHLi.js → FilePreview-4CWWDjOH.js} +1 -1
  76. package/dist/web/assets/{KanbanBoard-B-Z7lSaC.js → KanbanBoard-Ck-cWvPd.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-DF-nYnJu.js → MarkdownRenderer-BT_XxFwe.js} +3 -3
  78. package/dist/web/assets/{ScrollArea-dipnxnqf.js → ScrollArea-pHWxoYad.js} +1 -1
  79. package/dist/web/assets/{SessionHistorySurface-CnMBkiZW.js → SessionHistorySurface-ot9S7y0a.js} +1 -1
  80. package/dist/web/assets/{SettingsModal-DLA1WQ6g.js → SettingsModal-CadB2Ewl.js} +1 -1
  81. package/dist/web/assets/{Sidebar-tu4OcImk.js → Sidebar-Ch8ljTll.js} +1 -1
  82. package/dist/web/assets/{TaskSwitcher-D2TIUyr3.js → TaskSwitcher-DKMYqwyA.js} +1 -1
  83. package/dist/web/assets/{TerminalPanel-CcJVvSnz.js → TerminalPanel-DiibeBVa.js} +1 -1
  84. package/dist/web/assets/{archive-EoUobrxu.js → archive-RtNeCZxZ.js} +1 -1
  85. package/dist/web/assets/{arrow-left-Y8E5lnQ1.js → arrow-left-ozhIfGE6.js} +1 -1
  86. package/dist/web/assets/{calendar-clock-Cl0Spu99.js → calendar-clock-HYACxDy_.js} +1 -1
  87. package/dist/web/assets/{chevron-right-DmM1dl1s.js → chevron-right-DzAXXFGA.js} +1 -1
  88. package/dist/web/assets/{chevrons-up-down-DFQNAYac.js → chevrons-up-down-DABp_klC.js} +1 -1
  89. package/dist/web/assets/{clock-3-D3dzsSrc.js → clock-3-DTi7hWra.js} +1 -1
  90. package/dist/web/assets/{copy-BwNmbccC.js → copy-DTdeEIqL.js} +1 -1
  91. package/dist/web/assets/{download-DHzGZhJT.js → download-BmAUw5eK.js} +1 -1
  92. package/dist/web/assets/{external-link-Dr_8T3Ah.js → external-link-Bgh_DKjS.js} +1 -1
  93. package/dist/web/assets/{folder-DcgRdL_P.js → folder-CcFAxEz0.js} +1 -1
  94. package/dist/web/assets/{index-BZZUIkal.js → index-B0JUjEnb.js} +4 -4
  95. package/dist/web/assets/index-RGoMvYl5.css +1 -0
  96. package/dist/web/assets/{pause-DXzNhd_w.js → pause-Ch9b-6bD.js} +1 -1
  97. package/dist/web/assets/{pencil-CYRCKPnu.js → pencil-Dplt4XbT.js} +1 -1
  98. package/dist/web/assets/{play-CfNxuNSd.js → play-BfcPlDek.js} +1 -1
  99. package/dist/web/assets/{plus-DBUPwsji.js → plus-99fbVJwp.js} +1 -1
  100. package/dist/web/assets/session-events-CGQa6VXb.js +29 -0
  101. package/dist/web/assets/{settings-K2UJIIf_.js → settings-DNDRXm8y.js} +1 -1
  102. package/dist/web/assets/{team-BoulGGnJ.js → team-Cw3NxMX6.js} +1 -1
  103. package/dist/web/assets/{teamService-Cfm0Cd6e.js → teamService-a7uKjSKx.js} +1 -1
  104. package/dist/web/assets/{terminal-C9ZyLrcq.js → terminal-IkGhZXro.js} +1 -1
  105. package/dist/web/index.html +2 -2
  106. package/package.json +1 -1
  107. package/dist/chunk-0s0er9wr.js +0 -1
  108. package/dist/chunk-2b3j2egw.js +0 -1
  109. package/dist/chunk-44edbaa1.js +0 -1
  110. package/dist/chunk-514va7ce.js +0 -2
  111. package/dist/chunk-5vxhttdq.js +0 -10
  112. package/dist/chunk-7g76xzzg.js +0 -2
  113. package/dist/chunk-8tvf39jm.js +0 -1
  114. package/dist/chunk-enf0egke.js +0 -1
  115. package/dist/chunk-f5t7a64t.js +0 -1
  116. package/dist/chunk-h273dnvq.js +0 -1
  117. package/dist/chunk-j7784bxm.js +0 -1
  118. package/dist/chunk-jr402gf8.js +0 -1
  119. package/dist/chunk-s56t6kzj.js +0 -2
  120. package/dist/chunk-se0q0p3v.js +0 -1
  121. package/dist/chunk-sz5g7eh5.js +0 -1
  122. package/dist/chunk-wemdt9n6.js +0 -6
  123. package/dist/chunk-znrafpad.js +0 -1
  124. package/dist/chunk-zqjm9yd8.js +0 -1
  125. package/dist/web/assets/ChatView-BBYsaZIk.js +0 -63
  126. package/dist/web/assets/index-DC2p1vGD.css +0 -1
  127. package/dist/web/assets/session-events-DTVYDdaH.js +0 -29
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as Zi,D as _i,P as $i,V as aj};
2
+ export{N as _i,D as $i,P as aj,V as bj};
@@ -1,3 +1,3 @@
1
- import{ek as K}from"./chunk-7xtxvrh8.js";import{appendFileSync as Y,existsSync as Z,mkdirSync as _,readdirSync as f,statSync as M,unlinkSync as p}from"node:fs";import x from"node:path";var E;((T)=>{T[T.DEBUG=0]="DEBUG";T[T.INFO=1]="INFO";T[T.WARN=2]="WARN";T[T.ERROR=3]="ERROR"})(E||={});var t=null,G=null,H=!1;function S(n){if(t!==n)t=n}async function b(){}function z(){if(H)return G;H=!0;try{let n=x.join(K(),"logs");if(!Z(n))_(n,{recursive:!0,mode:493});if(M(n).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return B(n,30),G=n,n}catch(n){return console.error("[Logger] 无法创建日志目录:",n),null}}function B(n,u){try{let c=f(n),w=Date.now(),T=u*24*60*60*1000;for(let $ of c){if(!$.startsWith("blade-")||!$.endsWith(".log")&&!$.endsWith(".jsonl"))continue;let m=x.join(n,$);try{let q=M(m);if(w-q.mtimeMs>T)p(m)}catch(q){}}}catch(c){}}function J(){let n=z();if(!n)return null;let u=t||"default";return x.join(n,`blade-${u}.jsonl`)}function U(n,u,c){let w=J();if(!w)return;try{let T={timestamp:new Date().toISOString(),level:E[u],category:n,message:c};Y(w,JSON.stringify(T)+`
1
+ import{fk as K}from"./chunk-4wx5sya5.js";import{appendFileSync as Y,existsSync as Z,mkdirSync as _,readdirSync as f,statSync as M,unlinkSync as p}from"node:fs";import x from"node:path";var E;((T)=>{T[T.DEBUG=0]="DEBUG";T[T.INFO=1]="INFO";T[T.WARN=2]="WARN";T[T.ERROR=3]="ERROR"})(E||={});var t=null,G=null,H=!1;function S(n){if(t!==n)t=n}async function b(){}function z(){if(H)return G;H=!0;try{let n=x.join(K(),"logs");if(!Z(n))_(n,{recursive:!0,mode:493});if(M(n).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return B(n,30),G=n,n}catch(n){return console.error("[Logger] 无法创建日志目录:",n),null}}function B(n,u){try{let c=f(n),w=Date.now(),T=u*24*60*60*1000;for(let $ of c){if(!$.startsWith("blade-")||!$.endsWith(".log")&&!$.endsWith(".jsonl"))continue;let m=x.join(n,$);try{let q=M(m);if(w-q.mtimeMs>T)p(m)}catch(q){}}}catch(c){}}function J(){let n=z();if(!n)return null;let u=t||"default";return x.join(n,`blade-${u}.jsonl`)}function U(n,u,c){let w=J();if(!w)return;try{let T={timestamp:new Date().toISOString(),level:E[u],category:n,message:c};Y(w,JSON.stringify(T)+`
2
2
  `)}catch(T){}}class k{static globalDebugConfig=null;enabled;minLevel;category;constructor(n={}){if(n.enabled!==void 0)this.enabled=n.enabled;else if(k.globalDebugConfig!==null)this.enabled=Boolean(k.globalDebugConfig);else this.enabled=!1;this.minLevel=n.minLevel??0,this.category=n.category??"General"}static setGlobalDebug(n){k.globalDebugConfig=n}static clearGlobalDebug(){k.globalDebugConfig=null}setEnabled(n){this.enabled=n}parseDebugFilter(n){if(!n)return{enabled:!1};if(n===!0||n==="true"||n==="1")return{enabled:!0};let u=String(n).trim();if(!u)return{enabled:!0};if(u.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:u.split(",").map((T)=>T.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:u.split(",").map((w)=>w.trim()).filter(Boolean)}}}shouldLogCategory(n){if(!n)return!0;let u=this.category.toLowerCase();if(n.mode==="include")return n.categories.some((c)=>u.includes(c.toLowerCase()));return!n.categories.some((c)=>u.includes(c.toLowerCase()))}shouldLogToConsole(n){if(k.globalDebugConfig!==null){let{enabled:u,filter:c}=this.parseDebugFilter(k.globalDebugConfig);if(!u)return!1;if(n<this.minLevel)return!1;return this.shouldLogCategory(c)}return this.enabled&&n>=this.minLevel}log(n,...u){let c=u.map((w)=>typeof w==="object"?JSON.stringify(w):String(w)).join(" ");if(U(this.category,n,c),this.shouldLogToConsole(n)){let w=E[n],T=`[${this.category}] [${w}]`;console.error(T,...u)}}debug(...n){this.log(0,...n)}info(...n){this.log(1,...n)}warn(...n){this.log(2,...n)}error(...n){this.log(3,...n)}}function h(n,u){return new k({...u,category:n})}var s=new k({category:"General"});import F from"typebox/schema";import R from"typebox/value";class A extends Error{issues;constructor(n){super(n.map((u)=>{return`${u.path.length>0?u.path.join("."):"root"}: ${u.message}`}).join("; "));this.issues=n;this.name="SchemaValidationError"}}function O(n){if(!n)return[];return n.split("/").slice(1).map((u)=>u.replace(/~1/g,"/").replace(/~0/g,"~")).map((u)=>/^(0|[1-9]\d*)$/.test(u)?Number(u):u)}function P(n,u){let c=n;for(let w of u){if(c===null||typeof c!=="object")return;c=c[w]}return c}function Q(n,u){let[,c]=F.Errors(n,u);return c.map((w)=>{let T=O(w.instancePath);return{code:w.keyword,path:T,message:w.message,value:P(u,T)}})}function j(n,u){let c=R.Default(n,R.Clone(u)),w=Q(n,c);if(w.length>0)return{success:!1,error:new A(w)};let T=R.Clean(n,c),$=Q(n,T);if($.length>0)return{success:!1,error:new A($)};return{success:!0,data:T}}function W(n,u){let c=j(n,u);if(!c.success)throw c.error;return c.data}import X from"typebox";function i(n){return Object.defineProperties(n,{parse:{value:(u)=>W(n,u),enumerable:!1},safeParse:{value:(u)=>j(n,u),enumerable:!1}}),n}function a(n,u){return X.Optional({...n,default:u})}function L(n,u={}){return X.Unsafe({type:"string",enum:[...n],...u})}
3
- export{S as zj,b as Aj,k as Bj,h as Cj,s as Dj,j as Ej,W as Fj,X as Gj,i as Hj,a as Ij,L as Jj};
3
+ export{S as Aj,b as Bj,k as Cj,h as Dj,s as Ej,j as Fj,W as Gj,X as Hj,i as Ij,a as Jj,L as Kj};
@@ -1,4 +1,4 @@
1
- import{vf as v}from"./chunk-v67st2xb.js";import{Of as e}from"./chunk-r5dmdsjb.js";import{Bi as S,Ci as m,Di as c,Ei as p,Gi as u,Hi as d,Li as l,Qi as i,Ri as t,di as y,fi as D,gi as h,ii as A,pi as P,qi as T,si as E,ui as _,vi as f,xi as C}from"./chunk-ae0fws1f.js";import{Si as Y}from"./chunk-sd9bze9x.js";import{_i as X}from"./chunk-jsv3e4k6.js";import{cj as U,dj as L,jj as M,kj as O,mj as $,nj as I,oj as G,qj as N,rj as j,tj as F,uj as R}from"./chunk-n34qsnks.js";import{Cj as s,Ej as x,Gj as k,Jj as Z}from"./chunk-5q4z0sfr.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{vf as v}from"./chunk-6a16zba3.js";import{Of as e}from"./chunk-ny2g84m0.js";import{Ci as S,Di as m,Ei as c,Fi as p,Hi as u,Ii as d,Mi as l,Ri as i,Si as t,ei as y,gi as D,hi as h,ji as A,qi as P,ri as T,ti as E,vi as _,wi as f,yi as C}from"./chunk-65cxn7bb.js";import{Ti as Y}from"./chunk-kv458q06.js";import{$i as X}from"./chunk-2f8d0km4.js";import{dj as U,ej as L,kj as M,lj as O,nj as $,oj as I,pj as G,rj as N,sj as j,uj as F,vj as R}from"./chunk-ddvdc2p0.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-2mk914vk.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,2 +1,2 @@
1
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as zh,F as Ah,R as Bh,v as Ch};
2
+ export{G as Ah,F as Bh,R as Ch,v as Dh};
@@ -0,0 +1 @@
1
+ import{a,b as i,c as l,d as m}from"./chunk-x7gcmasv.js";import"./chunk-rrb49j43.js";import"./chunk-zj1g4nbq.js";import"./chunk-m7j6mq32.js";import"./chunk-srd0aqsm.js";import"./chunk-rqz0589c.js";import"./chunk-1xa8z2h3.js";import"./chunk-qm0j4szw.js";import"./chunk-atcpkhxt.js";import"./chunk-e12xrg41.js";import"./chunk-10947adv.js";import"./chunk-wm896gnx.js";import"./chunk-bwm0jt16.js";import"./chunk-9xbwtjac.js";import"./chunk-fd7ez529.js";import"./chunk-mh9nqbwa.js";import{xf as n}from"./chunk-cd150xf2.js";import"./chunk-wzqcea6x.js";import{Tf as s}from"./chunk-ny2g84m0.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-s32yz7eq.js";import"./chunk-s6x7fme7.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-mw3e5scz.js";import"./chunk-3y2x6fb6.js";import"./chunk-65cxn7bb.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as Pj,p as Qj,u as Rj,S as Sj,c as Tj,l as Uj};
2
+ export{f as Qj,p as Rj,u as Sj,S as Tj,c as Uj,l as Vj};
@@ -0,0 +1 @@
1
+ import{sf as a,tf as b,uf as c}from"./chunk-2n97dt2h.js";import"./chunk-6a16zba3.js";import"./chunk-ny2g84m0.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-06hkf59s.js";import"./chunk-65cxn7bb.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,2 +1,2 @@
1
1
  import*as z from"node:os";import*as x from"node:path";function F(){return process.env.BLADE_STORAGE_ROOT||x.join(z.homedir(),".blade")}import{AsyncLocalStorage as Lq}from"node:async_hooks";import{createHash as Vq}from"node:crypto";import{lstat as L,mkdir as Cq,readdir as bq,realpath as N}from"node:fs/promises";import Z from"node:path";import{createHash as Gq}from"node:crypto";var E=new WeakSet,j=new WeakSet,Jq={"not-absolute":"ACP remote file path must be absolute","style-mismatch":"ACP remote file path does not match the expected style","drive-relative":"ACP remote file path cannot be drive-relative","root-relative":"ACP remote file path cannot be root-relative","unc-not-supported":"ACP remote file path must be absolute; UNC paths are not supported","device-namespace-not-supported":"ACP remote file path device namespaces are not supported","trailing-dot-or-space":"ACP remote file path components cannot end with a dot or space","alternate-data-stream":"ACP remote file path alternate data streams are not supported","reserved-device-name":"ACP remote file path reserved device names are not supported","short-name-alias":"ACP remote file path short-name aliases are not supported","invalid-character":"ACP remote file path contains characters that are not supported"},Oq=new Set(["CON","PRN","AUX","NUL","CONIN$","CONOUT$","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9","COM¹","COM²","COM³","LPT¹","LPT²","LPT³"]);class _ extends Error{reason;style;name="AcpRemotePathError";code="acp_remote_path_invalid";constructor(q,G){super(Jq[q]);this.reason=q;this.style=G;Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,reason:this.reason,style:this.style,message:this.message}}}class V extends Error{name="AcpRemotePathIdentityError";code="acp_remote_path_identity_invalid";constructor(){super("ACP remote path identity is invalid");Object.setPrototypeOf(this,new.target.prototype)}}function Qq(q){if(!E.has(q))throw new V}function Uq(q){if(!j.has(q))throw new V;if(Qq(q.workspace),q.style!==q.workspace.style)throw new V}function gq(q){Uq(q);let G=Object.freeze({style:q.style,workspace:q.workspace});return j.add(G),G}function Rq(q){let G=C(q),J=Object.freeze({style:G.style,workspace:G});return j.add(J),J}function C(q,G){let J=W(q,G);if(J.kind==="error")throw new _(J.reason,J.style);let O=J.style==="win32"?Yq(q):Xq(q);return k(J.style,O)}function Sq(q,G){let J=C(q),O=J.style==="win32"?Fq(J.wirePath,G):_q(J.wirePath,G);return k(J.style,O)}function W(q,G){if(R(q))return{kind:"error",reason:"device-namespace-not-supported",style:"win32"};if(g(q))return{kind:"error",reason:"unc-not-supported",style:G==="posix"?"posix":"win32"};if(S(q))return{kind:"error",reason:"unc-not-supported",style:"win32"};if(P(q)){if(G==="posix")return{kind:"error",reason:"style-mismatch",style:"posix"};return{kind:"absolute",style:"win32"}}if(Mq(q))return{kind:"error",reason:"drive-relative",style:"win32"};if(q.startsWith("\\"))return{kind:"error",reason:"root-relative",style:"win32"};if(q.startsWith("/")){if(G==="win32")return{kind:"error",reason:"style-mismatch",style:"win32"};return{kind:"absolute",style:"posix"}}return{kind:"error",reason:"not-absolute",style:"unknown"}}function k(q,G){let J=q==="win32"?G.toUpperCase():G,O=Object.freeze({style:q,wirePath:G,exactIdentity:I("acp-remote-exact-path",q,G),collisionIdentity:I("acp-remote-collision-path",q,J)});return E.add(O),O}function I(q,G,J){return`${q}:${Gq("sha256").update(`${G}\x00${J}`).digest("hex")}`}function Xq(q){let G=q.split("/"),J=[];for(let O of G.slice(1)){if(O.length===0||O===".")continue;if(O===".."){if(J.length>0)J.pop();continue}A(O),J.push(O)}return J.length===0?"/":`/${J.join("/")}`}function Yq(q){let G=q[0].toUpperCase(),J=Bq(q),O=[],Q="";for(let U of q.slice(2)){if(m(U)){if(Q.length>0)v(O,Q),Q="";continue}Q+=U}if(Q.length>0)v(O,Q);if(J&&O.length>0)throw new _("trailing-dot-or-space","win32");if(O.length===0)return`${G}:\\`;return`${G}:\\${O.join("\\")}`}function Zq(q,G){let J=q==="/"?[]:q.slice(1).split("/"),O=[...J];for(let Q of G.split("/")){if(Q.length===0||Q===".")continue;if(Q===".."){if(O.length===J.length)throw new _("not-absolute","posix");O.pop();continue}A(Q),O.push(Q)}return O.length===0?"/":`/${O.join("/")}`}function _q(q,G){if(R(G))throw new _("device-namespace-not-supported","win32");if(g(G))throw new _("unc-not-supported","posix");if(S(G))throw new _("unc-not-supported","win32");if(P(G)||G.startsWith("/"))throw new _("style-mismatch","posix");return Zq(q,G)}function $q(q,G){let J=q.indexOf("\\"),O=J===q.length-1?[]:q.slice(J+1).split("\\"),Q=[...O],U="";for(let K of G){if(m(K)){if(U.length>0)y(O.length,Q,U),U="";continue}U+=K}if(U.length>0)y(O.length,Q,U);let $=q.slice(0,J+1);if(Q.length===0)return $;return`${$}${Q.join("\\")}`}function Fq(q,G){let J=W(G,"win32");if(J.kind==="absolute")throw new _("style-mismatch","win32");if(J.reason!=="not-absolute")throw new _(J.reason,J.style);return $q(q,G)}function y(q,G,J){if(J===".")return;if(J===".."){if(G.length===q)throw new _("not-absolute","win32");G.pop();return}f(J),G.push(J)}function v(q,G){if(G===".")return;if(G===".."){if(q.length>0)q.pop();return}f(G),q.push(G)}function A(q){if(q.includes("\x00"))throw new _("invalid-character","posix")}function f(q){let G=Hq(q),J=Kq(G);if(J!==void 0&&Oq.has(J.toUpperCase()))throw new _("reserved-device-name","win32");if(G!==q)throw new _("trailing-dot-or-space","win32");if(q.includes(":"))throw new _("alternate-data-stream","win32");if(/~\d/u.test(q))throw new _("short-name-alias","win32");for(let O of q){let Q=O.codePointAt(0);if(Q===void 0||Q===0||Q>=1&&Q<=31||'<>"|?*'.includes(O))throw new _("invalid-character","win32")}}function Hq(q){let G=q.length;while(G>0){let J=q[G-1];if(J!=="."&&J!==" ")break;G-=1}return q.slice(0,G)}function Kq(q){if(q.length===0)return;let G=q.indexOf(".");return G===-1?q:q.slice(0,G)}function g(q){return q.startsWith("//")||q.startsWith("/\\")}function R(q){return/^([\\/]){2}[?.][\\/]/u.test(q)}function S(q){return/^[\\/]{2}/u.test(q)}function P(q){return/^[A-Za-z]:[\\/]/u.test(q)}function Mq(q){return/^[A-Za-z]:(?![\\/])/u.test(q)}function m(q){return q==="\\"||q==="/"}function Bq(q){if(q.length<=3)return!1;let G=q[q.length-1];return G==="\\"||G==="/"}var H="acp-remote-workspaces",d=/^[a-f0-9]{64}$/,b=new Map,h=new Lq,Nq;class X extends Error{name="AcpRemoteWorkspaceStateError";code="acp_remote_workspace_state_invalid";constructor(q){super(`ACP remote workspace durable state is invalid (${q})`);Object.setPrototypeOf(this,new.target.prototype)}}function iq(q){return{version:1,kind:"acp-remote",style:q.style,wirePath:q.workspace.wirePath,exactIdentity:q.workspace.exactIdentity,collisionIdentity:q.workspace.collisionIdentity}}function Tq(q){if(!q||typeof q!=="object"||Array.isArray(q))throw new X("descriptor-shape");let G=q;if(G.version!==1)throw new X("descriptor-version");if(G.kind!=="acp-remote")throw new X("descriptor-kind");if(G.style!=="posix"&&G.style!=="win32")throw new X("descriptor-style");if(typeof G.wirePath!=="string"||typeof G.exactIdentity!=="string"||typeof G.collisionIdentity!=="string")throw new X("descriptor-shape");let J;try{J=C(G.wirePath,G.style)}catch{throw new X("descriptor-wire-path")}if(J.exactIdentity!==G.exactIdentity||J.collisionIdentity!==G.collisionIdentity)throw new X("descriptor-identity");return{version:1,kind:"acp-remote",style:G.style,wirePath:J.wirePath,exactIdentity:J.exactIdentity,collisionIdentity:J.collisionIdentity}}function cq(q,G=F()){if(typeof q!=="string"||!/^acp-remote-collision-path:[a-f0-9]{64}$/.test(q))throw new X("descriptor-collision-identity");let J=Z.resolve(G),O=Vq("sha256").update(`acp-remote-host-state\x00${q}`).digest("hex");return Z.join(J,H,O)}async function sq(q){let G=Z.resolve(F());await jq(q,G)}async function rq(q,G){let J=Z.resolve(F());return s(q,J,G)}async function oq(q,G){let J=String(q);if(Z.dirname(G)!==J)throw new X("state-file-path");let O=await L(G);if(O.isSymbolicLink()||!O.isFile())throw new X("state-file-type");if(typeof process.getuid==="function"&&O.uid!==process.getuid())throw new X("state-file-owner");let Q=typeof O.mode==="bigint"?Number(O.mode&BigInt(511)):O.mode&511;if(process.platform!=="win32"&&Q!==384)throw new X("state-file-mode");await M(G,J,Z.basename(G))}async function aq(q,G,J){let O=String(q);if(Z.dirname(G)!==O)throw new X("state-file-path");let[Q,U]=await Promise.all([J.stat({bigint:!0}),L(G,{bigint:!0})]);if(U.isSymbolicLink()||!U.isFile()||!Q.isFile()||U.dev!==Q.dev||U.ino!==Q.ino)throw new X("state-file-replaced");if(typeof process.getuid==="function"&&(Number(U.uid)!==process.getuid()||Number(Q.uid)!==process.getuid()))throw new X("state-file-owner");let $=Number(U.mode&BigInt(511)),K=Number(Q.mode&BigInt(511));if(process.platform!=="win32"&&($!==384||K!==384))throw new X("state-file-mode");await M(G,O,Z.basename(G))}function tq(q,G,J,O){let Q=q[0];if(Q?.type!=="session_created"||Q.sessionId!==G||Q.data.sessionId!==G||Q.cwd!==J||Q.projectPath!==J)throw new X("remote-session-identity");if(O){let U=Tq(Q.data.remoteWorkspace);if(U.version!==O.version||U.kind!==O.kind||U.style!==O.style||U.wirePath!==O.wirePath||U.exactIdentity!==O.exactIdentity||U.collisionIdentity!==O.collisionIdentity)throw new X("remote-session-workspace")}for(let U of q)if(U.sessionId!==G||U.cwd!==J||U.projectPath!==J)throw new X("remote-session-event-identity");return Q}function n(q){return d.test(q)}async function p(q=F()){let G=Z.resolve(q);return u(`${G}\x00${H}`,async()=>{let J=Z.join(G,H),O;try{O=await c(G,(U)=>bq(U,{withFileTypes:!0}))}catch(U){if(U.code==="ENOENT")return[];throw U}await Nq?.();let Q=[];for(let U of O){if(!n(U.name))continue;let $=Z.join(J,U.name);try{let K=await s($,G,async(qq)=>qq);Q.push(K)}catch(K){if(K.code==="ENOENT")throw new X("protected-root-missing");throw K}}return Q.sort((U,$)=>U.localeCompare($))})}function i(q,G){if(typeof q!=="string"||!Z.isAbsolute(q))throw new X("protected-root-shape");let J=Z.resolve(q);if(J!==q)throw new X("protected-root-shape");let O=Z.relative(G,J),Q=`${H}${Z.sep}`;if(O===""||O===H||!O.startsWith(Q)||O.includes(`${Z.sep}..`)||O.startsWith(`..${Z.sep}`)||Z.isAbsolute(O))throw new X("protected-root-shape");let U=O.split(Z.sep);if(U.length!==2||U[0]!==H)throw new X("protected-root-shape");if(!d.test(U[1]??""))throw new X("protected-root-digest");return{storageRoot:G,digest:U[1]}}async function c(q,G){await r(q,q);let J=Z.join(q,H);try{await D(J,q),await M(J,q,H)}catch(O){if(O.code==="ENOENT")throw O;throw O}return G(J)}async function jq(q,G){await u(q,async()=>{let J=i(q,G);if(J.storageRoot!==G)throw new X("storage-root-mismatch");await r(J.storageRoot,G);let O=Z.join(J.storageRoot,H);await l(O,J.storageRoot),await M(O,G,H);let Q=Z.join(O,J.digest);await l(Q,O),await M(Q,O,J.digest)})}async function s(q,G,J){return u(q,async()=>{let O=i(q,G);if(O.storageRoot!==G)throw new X("storage-root-mismatch");let Q=Z.join(O.storageRoot,H);await c(G,async($)=>{if($!==Q)throw new X("protected-root-shape")});let U=Z.join(Q,O.digest);return await D(U,Q),await M(U,Q,O.digest),J(U)})}async function l(q,G){try{let J=await L(q);o(J,q)}catch(J){if(J.code!=="ENOENT")throw J;await Cq(q,{recursive:!1,mode:448})}await D(q,G)}async function D(q,G){let J=await L(q);o(J,q),await M(q,G,Z.basename(q))}async function r(q,G){let J=await L(q);Dq(J,q),await uq(q,G)}function Dq(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&((J&448)!==448||(J&18)!==0))throw new X("protected-root-mode")}function o(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&J!==448)throw new X("protected-root-mode")}function a(q,G){if(q.isSymbolicLink()||!q.isDirectory())throw new X("protected-root-symlink");if(typeof process.getuid==="function"&&q.uid!==process.getuid())throw new X("protected-root-owner");if(G.includes(`..${Z.sep}`))throw new X("protected-root-shape")}function t(q){return typeof q.mode==="bigint"?Number(q.mode&BigInt(511)):q.mode&511}async function M(q,G,J){let O=await N(q),Q=await N(G),U=Z.join(Q,J);if(O!==U)throw new X("protected-root-realpath")}async function uq(q,G){let J=await N(q),O=await N(G);if(J!==O)throw new X("protected-root-realpath")}async function u(q,G){let J=h.getStore();if(J?.has(q))throw new X("state-root-reentry");let O=b.get(q)??Promise.resolve(),Q=new Set(J??[]);Q.add(q);let U=O.catch(()=>{return}).then(()=>h.run(Q,G)),$=U.then(()=>{return},()=>{return});b.set(q,$);try{return await U}finally{if(b.get(q)===$)b.delete(q)}}import{execSync as wq}from"node:child_process";import{createHash as zq}from"node:crypto";import{realpathSync as xq}from"node:fs";import{readdir as Iq}from"node:fs/promises";import*as Y from"node:path";function yq(q){return Y.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function vq(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function Eq(q){let G=yq(q);return Y.join(F(),"projects",G)}function e(q){let G=Y.resolve(q),J=[];while(!0)try{return Y.resolve(xq.native(G),...J.reverse())}catch(O){let Q=O.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw O;let U=Y.dirname(G);if(U===G)return Y.resolve(q);J.push(Y.basename(G)),G=U}}function XG(q,G="projectPath"){if(!Y.isAbsolute(q))throw Error(`${G} must be absolute`);let J=Y.resolve(q),O=e(J),Q=Y.join(e(F()),"acp-remote-workspaces"),U=Y.relative(Q,O),$=U.split(Y.sep)[0];if(U===""||U!==".."&&!Y.isAbsolute(U)&&!U.startsWith(`..${Y.sep}`)&&$!==void 0&&/^[a-f0-9]{64}$/i.test($))throw Error(`${G} must reference a local workspace`);return J}function w(q){return Eq(q)}function T(q){return String(q)}function Wq(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function B(q){if(!Wq(q))throw Error(`Invalid session ID: ${q}`)}function YG(q,G){return B(G),Y.join(w(q),`${G}.jsonl`)}function ZG(q,G){return B(G),Y.join(T(q),`${G}.jsonl`)}function _G(q,G){return B(G),Y.join(w(q),`${G}.inbox.json`)}function $G(q,G){return B(G),Y.join(T(q),`${G}.inbox.json`)}function FG(q,G){return B(G),Y.join(w(q),`${G}.goal.json`)}function HG(q,G){return B(G),Y.join(T(q),`${G}.goal.json`)}function KG(q,G){B(G);let J=zq("sha256").update(G).digest("hex");return Y.join(T(q),`.session-lease-${J}.lock`)}function MG(q){try{return wq("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}async function kq(){try{let q=Y.join(F(),"projects");return(await Iq(q,{withFileTypes:!0})).filter((J)=>J.isDirectory()).map((J)=>J.name)}catch{return[]}}async function BG(){let q=Y.resolve(F()),G=await kq().then((O)=>O.map((Q)=>({storagePath:Y.join(q,"projects",Q),projectPath:vq(Q),kind:"local"}))).catch(()=>[]),J=await p().then((O)=>O.map((Q)=>({storagePath:String(Q),projectPath:String(Q),kind:"acp-remote"})));return[...G,...J]}
2
- export{F as ek,_ as fk,Qq as gk,Uq as hk,gq as ik,Rq as jk,C as kk,Sq as lk,X as mk,iq as nk,Tq as ok,cq as pk,sq as qk,rq as rk,oq as sk,aq as tk,tq as uk,p as vk,vq as wk,Eq as xk,XG as yk,Wq as zk,B as Ak,YG as Bk,ZG as Ck,_G as Dk,$G as Ek,FG as Fk,HG as Gk,KG as Hk,MG as Ik,kq as Jk,BG as Kk};
2
+ export{F as fk,_ as gk,Qq as hk,Uq as ik,gq as jk,Rq as kk,C as lk,Sq as mk,X as nk,iq as ok,Tq as pk,cq as qk,sq as rk,rq as sk,oq as tk,aq as uk,tq as vk,p as wk,vq as xk,Eq as yk,XG as zk,Wq as Ak,B as Bk,YG as Ck,ZG as Dk,_G as Ek,$G as Fk,FG as Gk,HG as Hk,KG as Ik,MG as Jk,kq as Kk,BG as Lk};
@@ -0,0 +1,2 @@
1
+ var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
+ export{_ as Vi,E as Wi,T as Xi,A as Yi,S as Zi};
@@ -0,0 +1 @@
1
+ import{rg as a,sg as b,tg as c}from"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,4 +1,4 @@
1
- import{Ti as K}from"./chunk-sd9bze9x.js";import{Ui as wt,Vi as ft}from"./chunk-514va7ce.js";import{aj as I}from"./chunk-jsv3e4k6.js";import{bj as tt,cj as Dt,dj as Bt,hj as Gt,ij as et,jj as Kt,kj as Ht,lj as Yt,mj as cn,nj as Ft,oj as qt,pj as Mt,qj as Vt,rj as Jt,sj as _t,tj as Qt,uj as jt,vj as Wt,wj as Zt,xj as kt,yj as yt}from"./chunk-n34qsnks.js";import{Cj as Un,Ej as bn,Fj as _n,Gj as T}from"./chunk-5q4z0sfr.js";import{Lj as zt,Oj as v}from"./chunk-0b67y4j1.js";import{Wj as xn,Xj as Cn}from"./chunk-f2jm4x5q.js";import{bk as a}from"./chunk-gm2yfq3r.js";import{ek as Ln}from"./chunk-7xtxvrh8.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" 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(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.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((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))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 Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.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 b.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>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{Ui as K}from"./chunk-kv458q06.js";import{Vi as wt,Wi as ft}from"./chunk-5v0jcyea.js";import{bj as I}from"./chunk-2f8d0km4.js";import{cj as tt,dj as Dt,ej as Bt,ij as Gt,jj as et,kj as Kt,lj as Ht,mj as Yt,nj as cn,oj as Ft,pj as qt,qj as Mt,rj as Vt,sj as Jt,tj as _t,uj as Qt,vj as jt,wj as Wt,xj as Zt,yj as kt,zj as yt}from"./chunk-ddvdc2p0.js";import{Dj as Un,Fj as bn,Gj as _n,Hj as T}from"./chunk-2mk914vk.js";import{Mj as zt,Pj as v}from"./chunk-j8hbddjp.js";import{Xj as xn,Yj as Cn}from"./chunk-pe6kcmvn.js";import{ck as a}from"./chunk-rvs364rz.js";import{fk as Ln}from"./chunk-4wx5sya5.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" 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(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.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((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))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 Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.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 b.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>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.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 e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En 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 hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${e.map((M)=>` - ${M}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
44
- export{B as Dh,nn as Eh,f as Fh,En as Gh,hn as Hh,C as Ih,ot as Jh,VM as Kh,W as Lh,jM as Mh,WM as Nh,ZM as Oh,ct as Ph,Ce as Qh,kM as Rh,he as Sh,yM as Th,Pt as Uh,n_ as Vh,t_ as Wh,M_ as Xh,__ as Yh,r_ as Zh,Ct as _h,S_ as $h,E_ as ai,u_ as bi,o_ as ci,Y as di,Rn as ei,F as fi,q as gi,Xn as hi,V as ii,TM as ji,sM as ki,J as li,Q as mi,h as ni,xM as oi,zn as pi,Dn as qi,hM as ri,Bn as si,Gn as ti,Kn as ui,Hn as vi,Yn as wi,Fn as xi,XM as yi,qn as zi,Vn as Ai,Jn as Bi,Qn as Ci,jn as Di,Wn as Ei,Zn as Fi,kn as Gi,yn as Hi,ln as Ii,vn as Ji,nt as Ki,s as Li,d as Mi,Le as Ni,z as Oi,l as Pi,X as Qi,W_ as Ri};
44
+ export{B as Eh,nn as Fh,f as Gh,En as Hh,hn as Ih,C as Jh,ot as Kh,VM as Lh,W as Mh,jM as Nh,WM as Oh,ZM as Ph,ct as Qh,Ce as Rh,kM as Sh,he as Th,yM as Uh,Pt as Vh,n_ as Wh,t_ as Xh,M_ as Yh,__ as Zh,r_ as _h,Ct as $h,S_ as ai,E_ as bi,u_ as ci,o_ as di,Y as ei,Rn as fi,F as gi,q as hi,Xn as ii,V as ji,TM as ki,sM as li,J as mi,Q as ni,h as oi,xM as pi,zn as qi,Dn as ri,hM as si,Bn as ti,Gn as ui,Kn as vi,Hn as wi,Yn as xi,Fn as yi,XM as zi,qn as Ai,Vn as Bi,Jn as Ci,Qn as Di,jn as Ei,Wn as Fi,Zn as Gi,kn as Hi,yn as Ii,ln as Ji,vn as Ki,nt as Li,s as Mi,d as Ni,Le as Oi,z as Pi,l as Qi,X as Ri,W_ as Si};
@@ -0,0 +1 @@
1
+ import{ak as a,bk as b,ck as c}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -1,2 +1,2 @@
1
- import{vh as Q}from"./chunk-erhaedch.js";import{Ej as F,Gj as k,Jj as G}from"./chunk-5q4z0sfr.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
1
+ import{wh as Q}from"./chunk-06hkf59s.js";import{Fj as F,Hj as k,Kj as G}from"./chunk-2mk914vk.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
2
  export{Z as vf};
@@ -0,0 +1,6 @@
1
+ import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-sy59x1ts.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-rqz0589c.js";import{H as NH,ca as MH,ea as zH,fa as fH,ja as AH}from"./chunk-1xa8z2h3.js";import"./chunk-qm0j4szw.js";import"./chunk-atcpkhxt.js";import{$a as QH}from"./chunk-e12xrg41.js";import{Mb as e,Yb as FH,gc as EH}from"./chunk-10947adv.js";import"./chunk-wm896gnx.js";import{Rd as GH,Vd as PH,Xd as d,ge as t}from"./chunk-bwm0jt16.js";import"./chunk-9xbwtjac.js";import"./chunk-fd7ez529.js";import"./chunk-mh9nqbwa.js";import{qf as TH}from"./chunk-a9h3xfdj.js";import{sf as yH,tf as bH,uf as IH}from"./chunk-2n97dt2h.js";import{vf as SH}from"./chunk-6a16zba3.js";import"./chunk-wzqcea6x.js";import{Vf as _H}from"./chunk-ny2g84m0.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-s32yz7eq.js";import"./chunk-s6x7fme7.js";import"./chunk-3kszepm6.js";import{hh as c,lh as BH}from"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-mw3e5scz.js";import"./chunk-3y2x6fb6.js";import"./chunk-65cxn7bb.js";import{Ti as xH}from"./chunk-kv458q06.js";import{Yi as r,Zi as n}from"./chunk-5v0jcyea.js";import{bj as C}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Fj as UH,Hj as H,Ij as YH,Kj as Y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({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(HJ)}),VJ=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:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({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())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["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())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["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())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["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())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["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())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["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()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["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:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["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(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["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(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({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:Y(["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())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["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(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["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(Y(["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(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["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}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["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}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["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()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),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}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),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}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),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}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["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()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["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})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=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(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),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(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.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(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
2
+ `)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){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 HK(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(J,K))}
3
+ `)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
4
+ `);if(J)V.stdout.write(`
5
+ `)},content(J){if(Z==="jsonl"){q("content",{content:J});return}W(V.stdout,J)},structuredOutput(J){if(Z==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}W(V.stdout,JSON.stringify(J.output))},toolStart(J,K,D,x){if(Z==="jsonl"){q("tool_start",{tool_name:J,summary:K,target:D,tool_kind:x});return}W(V.stderr,`[tool:start] ${K}`)},toolProgress(J,K,D,x,j){if(Z==="jsonl"){q("tool_progress",{tool_name:J,message:K,progress:D,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}W(V.stderr,`[tool:progress] ${J}: ${K}`)},toolResult(J,K,D,x,j){if(Z==="jsonl"){q("tool_result",{tool_name:J,summary:K,target:D,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}W(V.stderr,`[tool:result] ${K}`)},mcpCatalogChanged(J){if(Z==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(Z==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(Z==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}W(V.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(Z==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}W(V.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(Z==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}W(V.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(Z==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}W(V.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(Z==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}W(V.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(Z==="jsonl"){q("project_rules_loaded",{files:J.files.map((K)=>({id:K.id,relative_path:K.relativePath,source:K.source,conditional:K.conditional,content_sha256:K.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}W(V.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,K,D){if(Z==="jsonl"){q("user_shell_started",{execution_id:J,command:K,auxiliary:D});return}W(V.stderr,`[user-shell:start] ${K}`)},userShellOutput(J,K,D,x){if(Z==="jsonl"){q("user_shell_output",{execution_id:J,stream:K,chunk:D,stream_truncated:x});return}(K==="stderr"?V.stderr:V.stdout).write(D)},userShellCompleted(J){if(Z==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}W(V.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,K,D,x={}){if(Z==="jsonl"){q("phase",{phase:J,status:K,message:D,turn:x.turn,tool_name:x.toolName,target:x.target});return}W(V.stderr,`[phase:${J}] ${D}`)},toolDetail(J,K){if(Z==="jsonl"){q("tool_detail",{tool_name:J,detail:K});return}W(V.stderr,K)},taskUpdate(J){if(Z==="jsonl"){q("task_update",{tasks:J});return}for(let K of J)W(V.stderr,rJ(K))},goalFrontier(J){if(Z==="jsonl"){q("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let K=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";W(V.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${K}`)},turnRecovery(J){let K=J.assessment;if(Z==="jsonl"){q("turn_recovery",{state:K.state,turn_id:K.turnId,input_message_count:K.inputMessageCount,reason:K.state==="requires_attention"?K.reason:void 0});return}W(V.stderr,`[turn-recovery:${K.state}] ${K.turnId}`)},goal(J){if(Z==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount,execution_host_failure_category:J.goal?.executionHostFailure?.category,execution_host_failure_count:J.goal?.executionHostFailure?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount,root_turn_id:J.goal?.turnLineage?.rootTurnId,current_turn_id:J.goal?.turnLineage?.currentTurnId,parent_turn_id:J.goal?.turnLineage?.parentTurnId});return}if(J.goal)W(V.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else W(V.stderr,"[goal:cleared]")},subagent(J){let K=J.kind==="subagent_spawned";if(Z==="jsonl"){q("subagent",{state:K?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:K?void 0:J.success,summary:K?void 0:J.summary,verification_verdict:K?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}W(V.stderr,`[subagent:${K?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(Z==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}W(V.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let K=J.phase==="start";if(Z==="jsonl"){q("compacting",{state:K?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason,memory:J.memory});return}W(V.stderr,K?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}${J.memory?.outcome==="written"?`; saved ${J.memory.entries} project memories`:""}`)},providerAdmission(J){if(Z==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}W(V.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(Z==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let K=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";W(V.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${K}`)},providerCircuit(J){if(Z==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let K=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";W(V.stderr,`[provider-circuit:${J.phase}] ${J.reason}${K}`)},providerStall(J){if(Z==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}W(V.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},providerRecovery(J){let K=J.recovery.snapshot;if(Z==="jsonl"){q("provider_recovery",{generation:J.recovery.generation,revision:J.recovery.revision,snapshot:K?{activity:K.activity,reason:K.reason,updated_at:K.updatedAt,next_action_at:K.nextActionAt,retry:K.retry?{attempt:K.retry.attempt,max_retries:K.retry.maxRetries,status_code:K.retry.statusCode,delay_ms:K.retry.delayMs,recovery_budget_ms:K.retry.recoveryBudgetMs,recovery_elapsed_ms:K.retry.recoveryElapsedMs,recovery_remaining_ms:K.retry.recoveryRemainingMs}:void 0,admission:K.admission?{request_class:K.admission.requestClass,scope:K.admission.scope,resource:K.admission.resource,queue_position:K.admission.queuePosition,queue_depth:K.admission.queueDepth,in_flight:K.admission.inFlight,limit:K.admission.limit,wait_ms:K.admission.waitMs,max_wait_ms:K.admission.maxWaitMs,recovery_remaining_ms:K.admission.recoveryRemainingMs}:void 0,circuit:K.circuit?{phase:K.circuit.phase,status_code:K.circuit.statusCode,retry_after_ms:K.circuit.retryAfterMs,next_probe_at:K.circuit.nextProbeAt,open_duration_ms:K.circuit.openDurationMs,sample_count:K.circuit.sampleCount,failure_count:K.circuit.failureCount,recovery_remaining_ms:K.circuit.recoveryRemainingMs}:void 0,stall:K.stall?{stall_count:K.stall.stallCount,duration_ms:K.stall.durationMs,warning_after_ms:K.stall.warningAfterMs,timeout_ms:K.stall.timeoutMs,output_started:K.stall.outputStarted}:void 0,fallback:K.fallback?{from:K.fallback.from,to:K.fallback.to,candidate:K.fallback.candidate,candidate_count:K.fallback.candidateCount,trigger:K.fallback.trigger.source==="retry"||K.fallback.trigger.source==="circuit"?{source:K.fallback.trigger.source,reason:K.fallback.trigger.reason,status_code:K.fallback.trigger.statusCode}:K.fallback.trigger}:void 0}:null});return}W(V.stderr,K?`[provider-recovery:${K.activity}] ${K.reason}`:"[provider-recovery:clear]")},turnActivity(J){if(Z!=="jsonl")return;let K=J.activity.snapshot;q("turn_activity",{generation:J.activity.generation,revision:J.activity.revision,snapshot:K?{phase:K.phase,started_at:K.startedAt,updated_at:K.updatedAt,turn:K.turn,max_turns:K.maxTurns,output_started:K.outputStarted,tool_calls_started:K.toolCallsStarted,tool_calls_completed:K.toolCallsCompleted,active_tools:K.activeTools.map((D)=>({name:D.name,kind:D.kind,started_at:D.startedAt,progress:D.progress,total:D.total})),active_tool_overflow:K.activeToolOverflow}:null})},modelFallback(J){let K=J.trigger.source==="retry"||J.trigger.source==="circuit"?{source:J.trigger.source,reason:J.trigger.reason,status_code:J.trigger.statusCode}:J.trigger;if(Z==="jsonl"){q("model_fallback",{from:J.from,to:J.to,candidate:J.candidate,candidate_count:J.candidateCount,trigger:K});return}W(V.stderr,`[provider-fallback] ${J.from.model} -> ${J.to.model}`)},actionStationarity(J){if(Z==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}W(V.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(Z==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}W(V.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(Z==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}W(V.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(Z==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}W(V.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,K=0){if(Z==="jsonl"){q("output",{content:J,exit_code:K});return}W(K===0?V.stdout:V.stderr,J)},error(J){if(Z==="jsonl"){q("error",{message:J});return}W(V.stderr,J)}}}async function JK(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new mH,K={targetLocked:!1},D,x,j,P=vJ(Q),T=!1,F=new o(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),p={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=jH(p,q),v=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await v()?N:1};try{let N=oJ(V);q=eJ(N.outputFormat);let y=await OH(N);B=jH(p,q,Boolean(y)),await gH();let HH=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await CH({message:N.message,_:N._,stdin:Q?.stdin}):await kH({...N,stdin:Q?.stdin}),M=HH===void 0,_=M?{mode:"agent",content:""}:await hH(HH);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>r)throw Error(`User prompt exceeds the ${r}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>n)throw Error(`User prompt exceeds the ${n}-byte durable input limit`);let h=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(h!==void 0&&N.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(h!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(N.taskIsolation&&(N.continue||N.resume||N.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:JH,metadata:KH}=await wH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??KH?.permissionMode??"yolo",VH=N.model&&N.model!=="inherit"?N.model:_H()?.id,U=N.taskIsolation?await RH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...VH?{modelId:VH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??KH?.projectPath??C();if(j=e.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let X=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],lH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(X.phase)||!A.includes(X.requestClass)||!S.includes(X.resource)||!I.includes(X.scope)||X.reason!==void 0&&!lH.includes(X.reason)||typeof X.queuePosition!=="number"||typeof X.queueDepth!=="number"||typeof X.inFlight!=="number"||typeof X.limit!=="number"||typeof X.waitMs!=="number"||typeof X.maxWaitMs!=="number"||X.recoveryRemainingMs!==void 0&&typeof X.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,...X.reason!==void 0?{reason:X.reason}:{},queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,...X.recoveryRemainingMs!==void 0?{recoveryRemainingMs:X.recoveryRemainingMs}:{}})}),!U)await t.setSessionPermissionMode(G,z,R);let cH=U?!1:await EH.cancelPendingNonInteractive(z,G);if(U)B.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??C(),isolation:N.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=e.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let uH={messages:cH?await t.loadSessionModelContext(G,z):[...JH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:nJ()};D=await MH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?SH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...JH.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&D.getPendingSteeringCount()>0,O=M&&!g?await D.getGoal():null,w=O?.status==="active"||O?.status==="verifying",l=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&l.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:l}),B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!w?await D.getRecoveredFinalResponse():void 0;if(M&&!g&&!w){if(!b)throw Error("No unfinished turn or active goal to resume");let $=l;if($.state!=="none")B.turnRecovery({kind:"turn_recovery",assessment:$});if(O)B.goal({kind:"goal_updated",goal:O});if(b.structuredOutput&&b.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else B.content(b.content);return B.phase("completed","done","Recovered headless run completed"),await E(0)}if(h!==void 0){let $=await D.executeUserShellCommand(h,{signal:P.signal,onEvent:async(X)=>{if(X.type==="started")B.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")B.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated);await v()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let dH=N.maxTurns??D.getConfig().maxTurns,pH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,vH=await AH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:pH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await FH(vH.chatStream(_.content,uH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...dH===-1?{onTurnLimitReached:async($)=>{return B.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||q==="jsonl")J.markAssistantContent();B.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let X=J.completeStream();B.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=zH(X.function.name,f),S=WH(X.function.name,f),I=HK(X.function.name,A,S,K);if(I.shouldLockTarget)K.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:X.function.name,target:S}),B.toolStart(X.function.name,A,S,$.toolKind)}catch{B.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),B.toolStart(X.function.name,X.function.name,void 0,$.toolKind)}break}case"tool_progress":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;B.toolProgress(X.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;let f;try{let S=JSON.parse(X.function.arguments);f=WH(X.function.name,S)}catch{f=void 0}let A=PH(fH(X.function.name,$.result),GH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:pJ($.result.metadata)}),A.detail)B.toolDetail(X.function.name,A.detail);break}case"token_usage":B.tokenUsage($.usage);break;case"compaction":B.compacting($);break;case"task_update":B.taskUpdate($.tasks);break;case"goal_frontier_updated":B.goalFrontier($);break;case"turn_recovery":B.turnRecovery($);break;case"structured_output":B.structuredOutput($);break;case"mcp_catalog_changed":B.mcpCatalogChanged($);break;case"mcp_content_changed":B.mcpContentChanged($);break;case"mcp_resource_updated":B.mcpResourceUpdated($);break;case"mcp_connection_changed":B.mcpConnectionChanged($);break;case"mcp_log":B.mcpLog($);break;case"mcp_instructions_changed":B.mcpInstructionsChanged($);break;case"mcp_task_changed":B.mcpTaskChanged($);break;case"project_rules_loaded":B.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":B.goal($);break;case"subagent_spawned":case"subagent_completed":B.subagent($);break;case"model_fallback":B.modelFallback($);break;case"provider_admission":B.providerAdmission($);break;case"provider_retry":B.providerRetry($);break;case"provider_circuit":B.providerCircuit($);break;case"provider_stall":B.providerStall($);break;case"provider_recovery":B.providerRecovery($);break;case"turn_activity":B.turnActivity($);break;case"action_stationarity":B.actionStationarity($);break;case"turn_start":if($.turn===1)K.targetLocked=!1;B.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let X=$}}await v()});if(m.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(m.metadata?.recoveryAttention)return B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!m.success)return B.error(`Error: ${m.error?.message??"Agent execution failed"}`),await E(1);return B.phase("completed","done","Headless run completed"),await E(0)}catch(N){if(!T){if(J.hasOpenThinking()&&q==="text")p.stderr.write(`
6
+ `);B.error(`Error: ${tJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function OK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":K,"max-turns":D,...x}=TH,j=uJ(dJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([bH,yH,IH]);return sJ(j),await j.parse(),!0}export{JK as runHeadless,OK as handleHeadlessMode,aJ as HeadlessOptionsSchema};
@@ -1 +1 @@
1
- import{ab as V,cb as W,db as O,vb as J}from"./chunk-7g76xzzg.js";import"./chunk-fx9vm1n5.js";import"./chunk-f2y0gxyq.js";import"./chunk-s56t6kzj.js";import"./chunk-514va7ce.js";import{aj as Q}from"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{ab as V,cb as W,db as O,vb as J}from"./chunk-e12xrg41.js";import"./chunk-mh9nqbwa.js";import"./chunk-w6qfbea8.js";import"./chunk-wcps5gjm.js";import"./chunk-5v0jcyea.js";import{bj as Q}from"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -0,0 +1,10 @@
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-x7gcmasv.js";import"./chunk-rrb49j43.js";import"./chunk-zj1g4nbq.js";import"./chunk-m7j6mq32.js";import"./chunk-srd0aqsm.js";import"./chunk-rqz0589c.js";import"./chunk-1xa8z2h3.js";import"./chunk-qm0j4szw.js";import"./chunk-atcpkhxt.js";import"./chunk-e12xrg41.js";import"./chunk-10947adv.js";import"./chunk-wm896gnx.js";import"./chunk-bwm0jt16.js";import"./chunk-9xbwtjac.js";import"./chunk-fd7ez529.js";import"./chunk-mh9nqbwa.js";import{xf as R}from"./chunk-cd150xf2.js";import"./chunk-wzqcea6x.js";import{Tf as Q}from"./chunk-ny2g84m0.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-s32yz7eq.js";import"./chunk-s6x7fme7.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-mw3e5scz.js";import"./chunk-3y2x6fb6.js";import"./chunk-65cxn7bb.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -0,0 +1 @@
1
+ import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-bwm0jt16.js";import"./chunk-9xbwtjac.js";import"./chunk-fd7ez529.js";import"./chunk-mh9nqbwa.js";import"./chunk-7wcxjbyg.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,4 +1,4 @@
1
- import{Qa as H}from"./chunk-h5xad96g.js";import"./chunk-wm896gnx.js";import"./chunk-9xbwtjac.js";import{Xf as $,bg as T}from"./chunk-r5dmdsjb.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-tp4yy3a6.js";import"./chunk-28tzj187.js";import"./chunk-ae0fws1f.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as k}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-f2jm4x5q.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{Qa as H}from"./chunk-atcpkhxt.js";import"./chunk-wm896gnx.js";import"./chunk-9xbwtjac.js";import{Xf as $,bg as T}from"./chunk-ny2g84m0.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-mw3e5scz.js";import"./chunk-3y2x6fb6.js";import"./chunk-65cxn7bb.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as k}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-s6x7fme7.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-mw3e5scz.js";import"./chunk-3y2x6fb6.js";import"./chunk-65cxn7bb.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-pe6kcmvn.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,2 +1,2 @@
1
- import{Wj as d,Yj as h}from"./chunk-f2jm4x5q.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Xj as d,Zj as h}from"./chunk-pe6kcmvn.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as qf,w as rf};
@@ -1,4 +1,4 @@
1
- import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{yh as Bt}from"./chunk-tp4yy3a6.js";import{$h as Gt,Dh as xt,Eh as vi,Fh as sn,Gh as zt,Hh as U,Ih as en,Jh as gt,Kh as mt,Mh as rn,Nh as Tn,Oh as B,Ph as dn,Qh as on,Rh as pn,Sh as lt,Th as un,Uh as cn,Vh as Mn,Xh as S,_h as wn,ai as Ut,bi as h,ci as Ht}from"./chunk-ae0fws1f.js";import{aj as It}from"./chunk-jsv3e4k6.js";import{Ej as X,Gj as x}from"./chunk-5q4z0sfr.js";import{Wj as tn,Xj as nn}from"./chunk-f2jm4x5q.js";import{Lk as ns}from"./chunk-sdapqhj0.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} 个错误):
1
+ import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{zh as Bt}from"./chunk-mw3e5scz.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-65cxn7bb.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-pe6kcmvn.js";import{Mk as ns}from"./chunk-eg3ms291.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
 
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d,o as e}from"./chunk-m9srdfa1.js";import"./chunk-pe6kcmvn.js";import"./chunk-eg3ms291.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +1 @@
1
- import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l,af as n,bf as o,cf as p,df as q,ef as r}from"./chunk-rv80nkve.js";import"./chunk-fx9vm1n5.js";import"./chunk-28tzj187.js";import"./chunk-5q4z0sfr.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
1
+ import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l,af as n,bf as o,cf as p,df as q,ef as r}from"./chunk-fd7ez529.js";import"./chunk-mh9nqbwa.js";import"./chunk-3y2x6fb6.js";import"./chunk-2mk914vk.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};