blade-code 0.10.7 → 0.10.9

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 (123) hide show
  1. package/dist/blade.js +3 -3
  2. package/dist/{chunk-jpy61wna.js → chunk-095x2ykj.js} +1 -1
  3. package/dist/chunk-17g172md.js +9 -0
  4. package/dist/{chunk-4hhkbyja.js → chunk-25cqav2f.js} +2 -2
  5. package/dist/chunk-27dr7bz0.js +2 -0
  6. package/dist/{chunk-vcq624qv.js → chunk-2c9ssx8y.js} +2 -2
  7. package/dist/{chunk-tc83e1b0.js → chunk-2wmnzxfz.js} +1 -1
  8. package/dist/chunk-2zwyvfbm.js +2 -0
  9. package/dist/chunk-39xzkky9.js +1 -0
  10. package/dist/chunk-3e5etzj8.js +2 -0
  11. package/dist/{chunk-m86ekqp0.js → chunk-41wym9fn.js} +2 -2
  12. package/dist/chunk-469ht1ty.js +194 -0
  13. package/dist/{chunk-p3ahf1fh.js → chunk-484ve631.js} +1 -1
  14. package/dist/chunk-4gegd63m.js +1 -0
  15. package/dist/{chunk-qqwgb9ja.js → chunk-4gkn11cb.js} +2 -2
  16. package/dist/chunk-4gptj397.js +1 -0
  17. package/dist/chunk-4v7h259s.js +2 -0
  18. package/dist/chunk-4xsqe5sn.js +2 -0
  19. package/dist/chunk-4yh4yeep.js +1 -0
  20. package/dist/chunk-5410er6c.js +1 -0
  21. package/dist/{chunk-p0j8994h.js → chunk-5ehe3xra.js} +1 -1
  22. package/dist/chunk-60764481.js +5 -0
  23. package/dist/{chunk-vafn0spm.js → chunk-686at39n.js} +1 -1
  24. package/dist/{chunk-7pkrwh10.js → chunk-6c1qjy1v.js} +1 -1
  25. package/dist/{chunk-7a200q5g.js → chunk-6rcwvrd1.js} +2 -2
  26. package/dist/{chunk-az4b6106.js → chunk-7by8mhzq.js} +1 -1
  27. package/dist/chunk-8g4n4578.js +4 -0
  28. package/dist/{chunk-1sw9z975.js → chunk-8j01ssaf.js} +1 -1
  29. package/dist/chunk-9dd2qmky.js +22 -0
  30. package/dist/chunk-afbky4f9.js +100 -0
  31. package/dist/chunk-amp9a6rq.js +2 -0
  32. package/dist/{chunk-wrbm6rch.js → chunk-b3qwhhpy.js} +2 -2
  33. package/dist/{chunk-yyvx1avz.js → chunk-bzvwcyma.js} +3 -3
  34. package/dist/{chunk-tcc3v4n2.js → chunk-c23vgww8.js} +1 -1
  35. package/dist/chunk-cgk8cft8.js +1 -0
  36. package/dist/chunk-cr7ncgsh.js +6 -0
  37. package/dist/chunk-dg6abzwy.js +1 -0
  38. package/dist/{chunk-847e0sk9.js → chunk-e0vwbx8b.js} +1 -1
  39. package/dist/chunk-e2f1kgt4.js +1 -0
  40. package/dist/chunk-f8nw8dcq.js +1481 -0
  41. package/dist/{chunk-qk2z6gag.js → chunk-gk1wq9rv.js} +2 -2
  42. package/dist/{chunk-kqpwz9b7.js → chunk-gv15jmxf.js} +2 -2
  43. package/dist/chunk-h4azdqke.js +10 -0
  44. package/dist/{chunk-43j2f1b5.js → chunk-h7szqxtg.js} +2 -2
  45. package/dist/chunk-jdy3ceqv.js +6 -0
  46. package/dist/{chunk-mt4328yf.js → chunk-jxhpwm5k.js} +2 -2
  47. package/dist/{chunk-0n04bmta.js → chunk-jzn1qtrc.js} +2 -2
  48. package/dist/chunk-k0n4prs1.js +2 -0
  49. package/dist/{chunk-tp9zk241.js → chunk-kg4xd3yf.js} +1 -1
  50. package/dist/chunk-m4b00d6v.js +1 -0
  51. package/dist/{chunk-ne7zdjrh.js → chunk-mzgwy44f.js} +1 -1
  52. package/dist/{chunk-x3780wpy.js → chunk-n2hn6tn2.js} +16 -16
  53. package/dist/chunk-n4e454dw.js +2 -0
  54. package/dist/{chunk-1v7hpr34.js → chunk-ncxavkjp.js} +1 -1
  55. package/dist/chunk-nezwz71s.js +1 -0
  56. package/dist/{chunk-rn908m3v.js → chunk-ns9emet3.js} +2 -2
  57. package/dist/chunk-p7s0rwk3.js +1 -0
  58. package/dist/{chunk-g3wgzyhx.js → chunk-p839x5dd.js} +48 -48
  59. package/dist/chunk-qtypjqb8.js +3 -0
  60. package/dist/{chunk-0xm8hn2h.js → chunk-r7mhhrp6.js} +2 -2
  61. package/dist/chunk-racbf4zb.js +1 -0
  62. package/dist/chunk-smpky1s8.js +1 -0
  63. package/dist/{chunk-w01sec4f.js → chunk-st9vr8w3.js} +2 -2
  64. package/dist/{chunk-0z7q89w7.js → chunk-tfefpqz1.js} +1 -1
  65. package/dist/{chunk-ahxc3n3g.js → chunk-vtwvwcz9.js} +2 -2
  66. package/dist/chunk-wc7dt3vm.js +1 -0
  67. package/dist/{chunk-y573s5r8.js → chunk-wr9p5hk3.js} +2 -2
  68. package/dist/chunk-xnb07jbj.js +1 -0
  69. package/dist/{chunk-qycwavck.js → chunk-y9d70cks.js} +2 -2
  70. package/dist/{chunk-3fdyzgpv.js → chunk-ybvdac8k.js} +1 -1
  71. package/dist/{chunk-e9ckf8e7.js → chunk-zns1crmz.js} +1 -1
  72. package/dist/web/assets/ChatView-BPzsdviX.js +7 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-CC4e9nFc.js → CodeBlockHighlighter-7DiEw-B3.js} +1 -1
  74. package/dist/web/assets/{FilePreview-C3HEoLYS.js → FilePreview-5FjwAe93.js} +2 -2
  75. package/dist/web/assets/{MarkdownRenderer-COycrGUX.js → MarkdownRenderer-CjsMv0q1.js} +18 -18
  76. package/dist/web/assets/SettingsModal-EPwoV6vp.js +5 -0
  77. package/dist/web/assets/TaskSwitcher-BOKaxmnf.js +1 -0
  78. package/dist/web/assets/{TerminalPanel-DqQ-7CTG.js → TerminalPanel-CZJYrbjQ.js} +1 -1
  79. package/dist/web/assets/index-CU-jckjp.css +1 -0
  80. package/dist/web/assets/index-I_DKONsY.js +32 -0
  81. package/dist/web/assets/{vendor-icons-D_AkWmWB.js → vendor-icons-ICv1v-tf.js} +81 -71
  82. package/dist/web/assets/{vendor-radix-DBy9B2DN.js → vendor-radix-DXRuAJHH.js} +1 -1
  83. package/dist/web/index.html +4 -4
  84. package/package.json +3 -1
  85. package/dist/chunk-4rhssb85.js +0 -2
  86. package/dist/chunk-598egka3.js +0 -22
  87. package/dist/chunk-5ak9tw83.js +0 -100
  88. package/dist/chunk-738pkjf8.js +0 -1
  89. package/dist/chunk-7xfmzvxp.js +0 -1
  90. package/dist/chunk-867rz2ss.js +0 -1
  91. package/dist/chunk-a3e97syg.js +0 -3
  92. package/dist/chunk-akev4wsz.js +0 -2
  93. package/dist/chunk-f7854pbx.js +0 -187
  94. package/dist/chunk-fwt0kje3.js +0 -1
  95. package/dist/chunk-g1q27q6q.js +0 -2
  96. package/dist/chunk-g4snq0dx.js +0 -1
  97. package/dist/chunk-ggm04adj.js +0 -1
  98. package/dist/chunk-hpytxsge.js +0 -1
  99. package/dist/chunk-htr91q9c.js +0 -1
  100. package/dist/chunk-hwcp940f.js +0 -1
  101. package/dist/chunk-j5ysjbyr.js +0 -10
  102. package/dist/chunk-m8k1mv0j.js +0 -4
  103. package/dist/chunk-pt659n0v.js +0 -1466
  104. package/dist/chunk-q1gfeadm.js +0 -1
  105. package/dist/chunk-rk1w5pry.js +0 -2
  106. package/dist/chunk-rz2ftt6h.js +0 -5
  107. package/dist/chunk-rz9yh6e4.js +0 -6
  108. package/dist/chunk-tzh4ahry.js +0 -6
  109. package/dist/chunk-v0rn831t.js +0 -1
  110. package/dist/chunk-vynsgc2g.js +0 -1
  111. package/dist/chunk-w0ena7fe.js +0 -9
  112. package/dist/chunk-wmdgb5pz.js +0 -2
  113. package/dist/chunk-ydwjttdz.js +0 -1
  114. package/dist/chunk-z9fsh3kn.js +0 -1
  115. package/dist/chunk-zjf1z27e.js +0 -2
  116. package/dist/web/assets/ChatView-BYfHmxKJ.js +0 -7
  117. package/dist/web/assets/McpModal-CDgr9kVq.js +0 -5
  118. package/dist/web/assets/SettingsModal-CvdVIbeG.js +0 -1
  119. package/dist/web/assets/SkillsModal-lSX1ZKTu.js +0 -1
  120. package/dist/web/assets/TaskSwitcher-peKi9KvN.js +0 -1
  121. package/dist/web/assets/index-BF5HEN_f.js +0 -32
  122. package/dist/web/assets/index-BrkTYxtS.css +0 -1
  123. package/dist/web/assets/useRequest-BvqVDnKl.js +0 -1
@@ -0,0 +1 @@
1
+ import{Ea as J,la as V,na as W,oa as O}from"./chunk-4xsqe5sn.js";import"./chunk-st9vr8w3.js";import"./chunk-n4e454dw.js";import"./chunk-4v7h259s.js";import{ef as Q}from"./chunk-7by8mhzq.js";import"./chunk-vtwvwcz9.js";import"./chunk-e0vwbx8b.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,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as _e,T as $e,A as af};
@@ -0,0 +1,2 @@
1
+ import{ae as o}from"./chunk-st9vr8w3.js";import{We as J,Xe as $,Ye as O,Ze as W}from"./chunk-n4e454dw.js";import{$e as S,_e as v,af as l}from"./chunk-4v7h259s.js";import{Gf as n}from"./chunk-vtwvwcz9.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,K){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[K,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let K=f.get(Z);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,K);let B=Object.fromEntries(K.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,K){let B=t(Z,K);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,K){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,K))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let K=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let X=K[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let K=E[Z];if(Q%K===0)return`${Q/K}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,K){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((K??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(W(["default","autoEdit","yolo","plan"]));var N=$(W(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(W(["queued","running","completed","failed","cancelled","interrupted"])),F=$(W(["local","worktree"])),JJ=$(W(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:W(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(W(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:W(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:W(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:W(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean()})),L=$(W(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(W(["auto","standard","fast","flex"])),M=$(W(["auto","low","medium","high"])),b=$(J.Union([W(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(W(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:W(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(W(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=W(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(W(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:W(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:W(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:W(["apply","discard"])})),q=$(J.Object({kind:W(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(W(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=W(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(W(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:W(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(W(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:W(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:W(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(W(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(W(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(W(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(W(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(W(["vs-dark","vs-light","hc-black"])),GJ=$(W(["light","dark","system"])),OJ=$(J.Object({language:J.String(),theme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let K=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)K.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((K)=>K.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,K=_(Z);if(K)throw Error(K);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===Q);if(B===-1)return;let X=K[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),K=Z.filter((B)=>B.id!==Q);if(K.length===Z.length)return!1;return await this.writeFile(K),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
2
+ export{DJ as la,A as ma,_ as na,FJ as oa,qJ as pa,z as qa,lJ as ra,uJ as sa,oJ as ta,sJ as ua,iJ as va,x as wa,aJ as xa,tJ as ya,rJ as za,TJ as Aa,yJ as Ba,eJ as Ca,I as Da,LQ as Ea};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-jxhpwm5k.js";import"./chunk-e0vwbx8b.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -0,0 +1 @@
1
+ import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-afbky4f9.js";import"./chunk-b3qwhhpy.js";import"./chunk-8j01ssaf.js";import"./chunk-mzgwy44f.js";import"./chunk-2wmnzxfz.js";import"./chunk-st9vr8w3.js";import"./chunk-4v7h259s.js";import"./chunk-7by8mhzq.js";import"./chunk-5ehe3xra.js";import"./chunk-27dr7bz0.js";import"./chunk-vtwvwcz9.js";import"./chunk-e0vwbx8b.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -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 Me,p as Ne,u as Oe,S as Pe,c as Qe,l as Re};
2
+ export{f as kf,p as lf,u as mf,S as nf,c as of,l as pf};
@@ -0,0 +1,5 @@
1
+ import{ae as g}from"./chunk-st9vr8w3.js";import{hf as _,jf as M}from"./chunk-41wym9fn.js";import{mf as U}from"./chunk-5ehe3xra.js";var H={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},v=(e)=>H[e]||{};var $=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function C(e){return typeof e==="string"&&$.has(e)}function se(e){if(!e.aborted)return;if(C(e.reason))return e.reason;return"user-cancel"}function ue(e){if(C(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function R(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let n=AbortSignal;if(typeof n.any==="function")return n.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,o=new Map;for(let i of t){let c=()=>{r.abort(i.reason);for(let[m,a]of o)m.removeEventListener("abort",a)};o.set(i,c)}for(let[i,c]of o)i.addEventListener("abort",c,{once:!0});return r.signal}function T(e,t,n){let r=n?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((o,i)=>{let c,m=setTimeout(()=>{if(t&&c)t.removeEventListener("abort",c);o()},e);if(t)c=()=>{if(clearTimeout(m),r)i(new DOMException("Aborted","AbortError"));else o()},t.addEventListener("abort",c,{once:!0})})}var q=g("Chat"),N={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function x(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
2
+ `)}function G(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return q.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function J(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function K(e,t){let n=J(e);if(n)return{type:"image",...n};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function A(e,t,n,r,o){let i=e.filter((a)=>a.role==="system").map((a)=>x(a.content)).filter(Boolean).join(`
3
+
4
+ `),c=[];for(let a of e){if(a.role==="system")continue;if(a.role==="user"){let l=t.input.includes("image"),s=typeof a.content==="string"?a.content:await Promise.all(a.content.map((u)=>u.type==="text"?Promise.resolve({type:"text",text:u.text}):l?K(u.image_url.url,r):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));c.push({role:"user",content:s,timestamp:Date.now()});continue}if(a.role==="assistant"){let l=[];if(a.reasoningContent?.trim())l.push({type:"thinking",thinking:a.reasoningContent});let s=x(a.content);if(s)l.push({type:"text",text:s});for(let u of a.tool_calls??[]){if(!("function"in u))continue;l.push({type:"toolCall",id:u.id,name:u.function.name,arguments:G(u.function.arguments)})}c.push({role:"assistant",content:l,api:t.api,provider:t.provider,model:t.id,usage:N,stopReason:a.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}c.push({role:"toolResult",toolCallId:a.tool_call_id??"",toolName:a.name??"unknown",content:[{type:"text",text:x(a.content)}],isError:!1,timestamp:Date.now()})}let m=n?.filter((a)=>!o||a.name===o).map((a)=>({name:a.name,description:a.description,parameters:a.parameters,constrainedSampling:a.constrainedSampling}));return{...i?{systemPrompt:i}:{},messages:c,...m?.length?{tools:m}:{}}}function I(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.role==="tool")continue;let o=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!o){t.push(r);continue}let i=[],c=n+1;while(c<e.length&&e[c].role==="tool")i.push(e[c++]);let m=new Set(o.map((s)=>s.id)),a=i.filter((s)=>s.tool_call_id&&m.has(s.tool_call_id)),l=new Set(a.map((s)=>s.tool_call_id));if(m.size===o.length&&a.length===m.size&&l.size===m.size)t.push(r,...a);n=c-1}return t}function P(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function O(e,t){return{...e,...t.baseUrl?{baseUrl:_(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function k(e){let t=e.modelCatalog??M();return{models:t.models,model:O(t.getModel(e.provider,e.model),e)}}function S(e,t){let n=e.modelCatalog??M();return O(n.getModel(t.provider,t.model),e)}function D(e,t){let n=e.onPayload;e.onPayload=async(r,o)=>{let i=n?await n(r,o):r;return t(i===void 0?r:i,o)}}function X(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Z(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function Q(e,t,n,r){let o=r?void 0:X(n);if(!o){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=o;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Z(o)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=o;break;default:e.reasoningEffort=o}}function Y(e,t,n){if(!n)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:n};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:n}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:n};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function ee(e,t,n){let r=n.serviceTier;if(!r)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=r;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&r==="fast"))return;D(e,(o)=>{if(!o||typeof o!=="object"||Array.isArray(o))return o;return t.api==="anthropic-messages"?{...o,speed:"fast"}:{...o,service_tier:r}})}function te(e,t,n){let r=n.responseVerbosity;if(!r)return;if(U(t,r),t.api==="openai-codex-responses"){e.textVerbosity=r;return}D(e,(o)=>{if(!o||typeof o!=="object"||Array.isArray(o))return o;if(t.api==="openai-completions")return{...o,verbosity:r};let i="text"in o&&o.text&&typeof o.text==="object"&&!Array.isArray(o.text)?o.text:{};return{...o,text:{...i,verbosity:r}}})}function L(e,t,n,r,o=!1){let i={apiKey:e.apiKey,headers:e.customHeaders,signal:n,temperature:r?.temperature??e.temperature??0,maxTokens:r?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(Q(i,t,e,o),Y(i,t.api,r?.toolChoice?.toolName),ee(i,t,e),te(i,t,e),t.api==="azure-openai-responses")i.azureBaseUrl=e.baseUrl,i.azureApiVersion=e.apiVersion,i.azureDeploymentName=t.id;return i}function z(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}function y(e){if(e!==null&&typeof e==="object"&&"code"in e&&e.code==="STREAM_IDLE_TIMEOUT")return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some((o)=>t.includes(o)))return!1;if(/^(?:error:\s*)?(?:408|409|429|5\d\d)\b/.test(t))return!0;if(t.match(/\b(?:status(?:\s+code)?|http)[:\s]+(408|409|429|5\d\d)\b/))return!0;return["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up","stream closed before completion","temporarily unavailable","upstream_error"].some((o)=>t.includes(o))}var b=300000;class W extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class B extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function j(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function oe(e,t){let n=t.idleTimeoutMs&&t.idleTimeoutMs>0?t.idleTimeoutMs:b;if(t.signal?.aborted)return Promise.reject(j(t.signal));return new Promise((r,o)=>{let i=!1,c=()=>{clearTimeout(s),t.signal?.removeEventListener("abort",l)},m=(u)=>{if(i)return;i=!0,c(),r(u)},a=(u)=>{if(i)return;i=!0,c(),o(u)},l=()=>{if(!t.signal)return;a(j(t.signal))},s=setTimeout(()=>{if(i)return;let u=new W(n);i=!0,t.signal?.removeEventListener("abort",l),t.abort?.(u),o(u)},n);if(t.signal?.addEventListener("abort",l,{once:!0}),t.signal?.aborted){l();return}Promise.resolve().then(()=>e.next()).then(m,(u)=>a(u instanceof Error?u:Error(String(u))))})}async function*F(e,t,n,r,o={}){let c=e.stream(t,n,r)[Symbol.asyncIterator](),m=0,a=!1;try{while(!0){let l=await oe(c,o);if(l.done)throw new B;let s=l.value;switch(s.type){case"text_delta":yield{content:s.delta};break;case"thinking_delta":yield{reasoningContent:s.delta};break;case"toolcall_end":yield{toolCalls:[{index:m++,id:s.toolCall.id,type:"function",function:{name:s.toolCall.name,arguments:JSON.stringify(s.toolCall.arguments)}}]};break;case"done":a=!0,yield{finishReason:s.reason,usage:z(s.message.usage)};return;case"error":throw Error(s.error.errorMessage??`Request ${s.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!a)Promise.resolve(c.return?.()).catch(()=>{return})}}var V=g("Chat");function ne(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}class w{config;models;model;constructor(e){let t=k(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,V.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,n,r){let o="",i="",c=[],m,a;for await(let l of this.streamChat(e,t,n,r)){o+=l.content??"",i+=l.reasoningContent??"";for(let s of l.toolCalls??[])if(s.id&&s.type==="function"&&s.function?.name)c.push(s);m=l.usage??m,a=l.finishReason??a}return{content:o,...i?{reasoningContent:i}:{},...c.length>0?{toolCalls:c}:{},usage:m,finishReason:a}}async*streamChat(e,t,n,r){let o=r?.toolChoice?.toolName;if(o&&!t?.some((p)=>p.name===o))throw Error(`Required tool is unavailable: ${o}`);let i=I(e);if(i.some((p)=>ne(p))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let c=Boolean(o)||P(i),m=await A(i,this.model,t,n,o),a=(p)=>{let d=new AbortController,h=n?R(n,d.signal):d.signal;return F(this.models,p,m,L(this.config,p,h,r,c),{idleTimeoutMs:this.config.streamIdleTimeout??b,signal:h,abort:(f)=>d.abort(f)})},l=this.config.maxRetries??2,s,u=!1;for(let p=0;p<=l;p++)try{for await(let d of a(this.model))u=!0,yield d;return}catch(d){if(s=d,this.logIdleTimeout(d,u,this.model),await this.handleAbort(n),u||!y(d))throw d;if(p<l)await T(1000*2**p,n,{throwOnAbort:!0})}for(let p of this.config.fallbackModels??[]){yield{modelFallback:!0};let d=!1,h;try{h=S(this.config,p);for await(let f of a(h))d=!0,yield f;return}catch(f){if(s=f,h)this.logIdleTimeout(f,d,h);if(await this.handleAbort(n),d||!y(f))throw f}}throw s}async handleAbort(e){if(e?.aborted)await T(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,n){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;V.warn("[PiAIChatService] Provider stream idle timeout",{provider:n.provider,model:n.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},n=k(t);this.config={...t,maxContextTokens:n.model.contextWindow,maxOutputTokens:t.maxOutputTokens??n.model.maxTokens},this.models=n.models,this.model=n.model}}var re=g("Service");async function Se(e){let t=e;if(t.provider){let n=v(t.provider);if(Object.keys(n).length>0)t={...t,customHeaders:{...n,...t.customHeaders}},re.debug(`Injected ${t.provider} specific headers:`,Object.keys(n))}return ie(t)}function ie(e){return new w(e)}
5
+ export{se as gd,ue as hd,R as id,w as jd,Se as kd};
@@ -1,4 +1,4 @@
1
- import{ja as H}from"./chunk-rn908m3v.js";import"./chunk-jpy61wna.js";import{Fc as T,zc as $}from"./chunk-x3780wpy.js";import"./chunk-tp9zk241.js";import"./chunk-3fdyzgpv.js";import"./chunk-yyvx1avz.js";import"./chunk-tc83e1b0.js";import"./chunk-w01sec4f.js";import"./chunk-vcq624qv.js";import"./chunk-akev4wsz.js";import"./chunk-rk1w5pry.js";import{Ge as k}from"./chunk-az4b6106.js";import"./chunk-m86ekqp0.js";import"./chunk-p0j8994h.js";import"./chunk-g1q27q6q.js";import"./chunk-0n04bmta.js";import"./chunk-1v7hpr34.js";import"./chunk-ahxc3n3g.js";import"./chunk-847e0sk9.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{ka as H}from"./chunk-ns9emet3.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-n2hn6tn2.js";import"./chunk-kg4xd3yf.js";import"./chunk-ybvdac8k.js";import"./chunk-bzvwcyma.js";import"./chunk-2wmnzxfz.js";import"./chunk-st9vr8w3.js";import"./chunk-2c9ssx8y.js";import"./chunk-amp9a6rq.js";import"./chunk-n4e454dw.js";import"./chunk-4v7h259s.js";import{ef as k}from"./chunk-7by8mhzq.js";import"./chunk-41wym9fn.js";import"./chunk-5ehe3xra.js";import"./chunk-27dr7bz0.js";import"./chunk-jzn1qtrc.js";import"./chunk-ncxavkjp.js";import"./chunk-vtwvwcz9.js";import"./chunk-e0vwbx8b.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 字符串添加服务器
@@ -1 +1 @@
1
- import{h as o}from"./chunk-mt4328yf.js";import"./chunk-847e0sk9.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-jxhpwm5k.js";import"./chunk-e0vwbx8b.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,2 +1,2 @@
1
- import{B as o}from"./chunk-pt659n0v.js";import{Bb as i}from"./chunk-5ak9tw83.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
- export{m as r};
1
+ import{C as o}from"./chunk-f8nw8dcq.js";import{$b as i}from"./chunk-afbky4f9.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
+ export{m as s};
@@ -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 De,D as Ee,P as Fe,V as Ge};
2
+ export{N as bf,D as cf,P as df,V as ef};
@@ -0,0 +1,4 @@
1
+ import{$ as F,Z as y}from"./chunk-f8nw8dcq.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-afbky4f9.js";import{Jd as $}from"./chunk-y9d70cks.js";import{ef as K}from"./chunk-7by8mhzq.js";async function O(){await $(K())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
+
3
+ ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function P(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await Q.loadSession(b,K())}catch(q){if(J(q))return null;throw q}}async function T(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=K();return Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}let[q,z]=await Promise.all([Q.loadSession(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:K()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=K();return Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}return{sessionId:z,messages:await Q.loadSession(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,K())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
+ export{O as m,j as n,I as o,P as p,T as q};
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as Qc,g as Rc};
2
+ export{s as od,g as pd};
@@ -0,0 +1,22 @@
1
+ import{r as A}from"./chunk-gv15jmxf.js";import{s as zJ}from"./chunk-6rcwvrd1.js";import{$ as r,F as v,I as p,J as m,L as d,Z as l,_ as i,aa as a,v as N}from"./chunk-f8nw8dcq.js";import{ka as $J}from"./chunk-ns9emet3.js";import"./chunk-4xsqe5sn.js";import{Va as u,Ya as g,hb as c}from"./chunk-469ht1ty.js";import{sb as I}from"./chunk-095x2ykj.js";import{$b as L,Fb as S,Kb as R,Nb as C,Tb as y,Ub as f,Yb as _}from"./chunk-afbky4f9.js";import"./chunk-b3qwhhpy.js";import"./chunk-r7mhhrp6.js";import"./chunk-n2hn6tn2.js";import"./chunk-kg4xd3yf.js";import{fd as JJ}from"./chunk-ybvdac8k.js";import"./chunk-60764481.js";import"./chunk-4gkn11cb.js";import{od as QJ}from"./chunk-8j01ssaf.js";import"./chunk-wr9p5hk3.js";import"./chunk-y9d70cks.js";import"./chunk-tfefpqz1.js";import{Pd as ZJ}from"./chunk-mzgwy44f.js";import"./chunk-zns1crmz.js";import"./chunk-bzvwcyma.js";import"./chunk-2wmnzxfz.js";import{ae as O}from"./chunk-st9vr8w3.js";import"./chunk-2c9ssx8y.js";import"./chunk-amp9a6rq.js";import"./chunk-n4e454dw.js";import{$e as k,_e as x,af as h}from"./chunk-4v7h259s.js";import{ef as t}from"./chunk-7by8mhzq.js";import"./chunk-41wym9fn.js";import{kf as s,nf as e}from"./chunk-5ehe3xra.js";import"./chunk-27dr7bz0.js";import"./chunk-jzn1qtrc.js";import"./chunk-ncxavkjp.js";import"./chunk-vtwvwcz9.js";import"./chunk-e0vwbx8b.js";import{Readable as LJ,Writable as BJ}from"node:stream";import*as E from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as DJ}from"@agentclientprotocol/sdk";import o from"node:path";import{RequestError as HJ}from"@agentclientprotocol/sdk";import{nanoid as b}from"nanoid";var D=O("Agent");function M(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function FJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:M(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:M("headers"in J?J.headers:void 0)};return null}function GJ(J){let Z={};for(let Q of J){let W=FJ(Q);if(W)Z[Q.name]=W}return Z}function n(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function XJ(J){let Z=f(J.metadata);return Z?[{type:"text",text:y(Z)}]:n(J.content)}function jJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,W,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=W;this.options=H;this.messages=[...H.initialMessages??[]],this.mode=this.mapPermissionModeToMode(H.permissionMode)}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return d.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(D.debug(`[AcpSession ${this.id}] Initializing...`),await L.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),D.debug(`[AcpSession ${this.id}] ACP service context initialized`),await c.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await L.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?GJ(this.options.mcpServers):void 0,Q=N.getInstance().getTerminalService(this.id);if(this.runtime=await v.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await A.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await L.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await i(this.cwd),D.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=g.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of XJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);D.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{D.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,j,Y=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},X=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(B)=>{if(F)Y(B);else j=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.session.id,status:"in_progress",title:`Resuming ${X.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${X.source.id} at depth ${X.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,j)Y(j);return X}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await A.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(X)=>{if(X.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.toolCall.id,status:"in_progress",title:`Review: ${X.toolCall.function.name}`,content:[],kind:this.mapToolKind(X.toolKind)});else if(X.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.toolCall.id,status:X.result.success?"completed":"failed",content:[]})}}),j=await F.completion,Y=(await A.list(this.cwd,this.id)).find((X)=>X.start.reviewId===F.reviewId);if(!Y)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await L.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:j.status,findings:j.findings.length,content:S(Y.start,j)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let j=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Y=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:Y})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},W=await r(J,Q),H=W.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages];if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages)this.messages=[...W.data.compactedMessages];let z=W.content||W.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return{stopReason:W.success?"end_turn":"cancelled"}}catch(Q){return D.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=a(this.cwd),Z=["model","permissions","theme","config","exit","ide"],W=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});D.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),D.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(J){D.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),W=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=C(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let F=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(D.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(D.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),l(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Y)=>{this.mode=this.mapPermissionModeToMode(Y),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}},j=await u(this.agent.chatStream(W,F,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(Y)=>{switch(Y.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let X=Y.toolCall,B=X.function.name;if(B===R)break;let U=this.mapToolKind(Y.toolKind),V=`Executing ${B}`;if(B==="Task"&&"function"in X)try{let q=JSON.parse(X.function.arguments),w=q.resume_from??q.resume;if(typeof w==="string")V=`Resuming ${String(q.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.id,status:"in_progress",title:V,content:[],kind:U});break}case"tool_progress":{let X=Y.toolCall;if(X.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Y.update.message}}]});break}case"tool_result":{let X=Y.toolCall;if(X.function.name===R)break;let B=Y.result,U=[],V=B.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;U.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))U.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=X.function.name,WJ=m(p(w,B));U.push({type:"content",content:{type:"text",text:WJ}})}if(X.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))U.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let q=B.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.id,status:q,content:U});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Y.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
3
+ `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Y.contentKind} r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
4
+ `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Y.revision} (${Y.serverName}): ${Y.uri}
5
+ `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Y.revision} (${Y.serverName}): ${Y.phase} ${Y.attempt}/${Y.maxAttempts}
6
+ `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Y.revision} (${Y.serverName}) ${Y.level}${Y.logger?` logger=${Y.logger}`:""}: ${Y.message}
7
+ `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Y.revision} (${Y.serverName}): ${Y.action}${Y.detailsOmitted?" details-omitted":""}
8
+ `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Y.revision} ${Y.taskId} (${Y.serverName}/${Y.toolName}): ${Y.status}${Y.hasResult?" result-available":""}
9
+ `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Y.files.length}${Y.blockedWrite?" (write retry required)":""}
10
+ `}});break;case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let X of Y.messages){if(!X.recovered||X.persisted)continue;for(let B of n(X.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:B})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
11
+ `}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
12
+ `}});break;case"goal_continuation_started":break;default:break}});if(this.messages=[...F.messages],!j.success){let Y=j.error?.type??"unknown";throw HJ.internalError({failureType:Y},`Agent turn failed (${Y})`)}if(G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn",...j.metadata?.structuredOutput?{_meta:{structuredOutput:j.metadata.structuredOutput,outputSchemaDigest:j.metadata.structuredOutputSchemaDigest}}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw D.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let W,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(W=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=y($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?jJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((W)=>{D.error(`[AcpSession ${this.id}] Failed to resume pending input:`,W)})}cancel(){D.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)D.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",W=this.mapModeIdToPermissionMode(Q);await L.setSessionPermissionMode(this.id,this.cwd,W),this.mode=Q,D.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(D.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await L.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((W)=>{D.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(W){if(!(W instanceof _)&&W.code!=="ENOENT")throw W;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:Z.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,W=async(H)=>{try{await H()}catch(z){Q??=z}};if(await W(()=>this.cancel()),J)await W(()=>J.destroy());if(Z)await W(()=>Z.dispose());if(await W(()=>N.destroySession(this.id)),D.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],W=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
+ `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let j=`data:${F.mimeType};base64,${F.data}`;W+=1,H+=j.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:j}})}else if(F.type==="resource"){let j=F.resource;if("text"in j){let Y=`<file path="${j.uri}">
14
+ ${j.text}
15
+ </file>`;Z.push(Y),$({type:"text",text:Y})}}else if(F.type==="resource_link"){let j=`[Resource: ${F.uri}]`;Z.push(j),$({type:"text",text:j})}if(W>x)throw Error(`ACP prompt contains more than ${x} images`);if(H>k)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>h)throw Error(`ACP prompt text exceeds ${h} characters`);let G=Z.join(`
16
+ `);return{content:W>0?Q:G,displayText:G}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{D.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));D.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return D.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return D.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=b(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
+ - ${J.risks.join(`
18
+ - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:W,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:I};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let j=F.optionId;if(j==="allow_always")return{approved:!0,scope:"project"};if(j==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let Y=j==="allow_once";return{approved:Y,scope:"once",reason:Y?void 0:"User denied the operation"}}catch(W){return D.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[H,z]of Q.entries()){let $=z.options.map((Y,X)=>`answer:${H}:${X}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((Y,X)=>({optionId:$[X],name:Y.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((Y)=>`${Y.label}: ${Y.description}`)].join(`
19
+ `)}}]}}),Z);if(!F)return{approved:!1,reason:I};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let j=$.indexOf(F.outcome.optionId);if(j<0)return{approved:!1,reason:"User cancelled the question prompt"};W[z.header]=z.options[j].label}return{approved:!0,answers:W}}catch(H){return D.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
+ `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)W[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return D.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),W=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
+ `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(W==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===W);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
+ `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,W){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),W);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,W)=>{let H=!1,z=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>W(G)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var K=O("Agent");class T{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:DJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=JJ("acp"),Q=J.cwd||t(),W=J._meta?.["blade/taskIsolation"],H=W==="local"||W==="worktree"?W:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await zJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new P(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(j){throw await F.destroy().catch(()=>{return}),j}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!o.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await L.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!o.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await L.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new P(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(W){throw await Q.destroy().catch(()=>{return}),W}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),K.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),W=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,W);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===W)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await L.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,W]=await Promise.all([L.loadSession(J.sessionId,J.cwd),L.findSessionMetadata(J.sessionId,J.cwd)]);if(!W)throw Error(`Session not found: ${J.sessionId}`);let H=new P(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:W.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],W=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&QJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&s(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await $J.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function tJ(){let J=BJ.toWeb(process.stdout),Z=LJ.toWeb(process.stdin),Q=E.ndJsonStream(J,Z);await new E.AgentSideConnection((H)=>new T(H),Q).closed}export{tJ as runAcpIntegration};