blade-code 0.10.5 → 0.10.6

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 (90) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-rh7v814a.js → chunk-0rp2ck29.js} +2 -2
  3. package/dist/chunk-10k6egwk.js +1 -0
  4. package/dist/chunk-17xtw88g.js +1 -0
  5. package/dist/chunk-1cvr3qtd.js +1482 -0
  6. package/dist/chunk-1kg9r8xp.js +2 -0
  7. package/dist/{chunk-51wtvmzn.js → chunk-383vbwmt.js} +1 -1
  8. package/dist/chunk-3kk3bk11.js +1 -0
  9. package/dist/{chunk-6tx8k249.js → chunk-45dcfkwe.js} +2 -2
  10. package/dist/chunk-47dsd91k.js +99 -0
  11. package/dist/chunk-4kaygjqv.js +10 -0
  12. package/dist/{chunk-35yktzm1.js → chunk-4y28hykg.js} +1 -1
  13. package/dist/chunk-50fq7r0h.js +22 -0
  14. package/dist/chunk-59eje513.js +1 -0
  15. package/dist/{chunk-qda309d9.js → chunk-6cv4gddv.js} +2 -2
  16. package/dist/{chunk-hh85pk77.js → chunk-710bvht9.js} +47 -47
  17. package/dist/{chunk-xv0maezy.js → chunk-76d7p64v.js} +1 -1
  18. package/dist/{chunk-bexgcc2d.js → chunk-7xm3vjkz.js} +1 -1
  19. package/dist/{chunk-19kg7yvw.js → chunk-9sfmrb1j.js} +2 -2
  20. package/dist/chunk-a9pbpgkg.js +9 -0
  21. package/dist/{chunk-gxmrakrk.js → chunk-b4n34hrn.js} +1 -1
  22. package/dist/{chunk-v93hcxe7.js → chunk-bn0ge244.js} +1 -1
  23. package/dist/{chunk-fvhc1yj8.js → chunk-bnrce0hg.js} +1 -1
  24. package/dist/{chunk-9ffr01c3.js → chunk-c2rhwxyn.js} +1 -1
  25. package/dist/chunk-c8rky275.js +6 -0
  26. package/dist/{chunk-epj56s0n.js → chunk-c9tzf9r5.js} +1 -1
  27. package/dist/{chunk-njyvrtje.js → chunk-dcvvxsa1.js} +2 -2
  28. package/dist/{chunk-5twefby5.js → chunk-evaht3v4.js} +1 -1
  29. package/dist/{chunk-0n97186m.js → chunk-frcg8gea.js} +2 -2
  30. package/dist/{chunk-drrdzmaa.js → chunk-g4q26d9a.js} +2 -2
  31. package/dist/{chunk-s645azsm.js → chunk-g9n211y4.js} +2 -2
  32. package/dist/{chunk-vntzy7bc.js → chunk-gb4n3hwj.js} +2 -2
  33. package/dist/{chunk-ea7wsges.js → chunk-hjsm6ejs.js} +2 -2
  34. package/dist/chunk-j1sd03h7.js +1 -0
  35. package/dist/chunk-jqyvnmfr.js +187 -0
  36. package/dist/chunk-jrh5tzc4.js +1 -0
  37. package/dist/{chunk-an96c54z.js → chunk-k0p9ecgc.js} +7 -7
  38. package/dist/{chunk-z906d5tb.js → chunk-kcs3xa8f.js} +2 -2
  39. package/dist/{chunk-63ysxybd.js → chunk-kcwq1e7h.js} +1 -1
  40. package/dist/chunk-kj1ah6kn.js +1 -0
  41. package/dist/{chunk-am8dtvff.js → chunk-m4htdpr9.js} +2 -2
  42. package/dist/chunk-n34z4c47.js +1 -0
  43. package/dist/{chunk-6eragc74.js → chunk-n5m2p0bq.js} +2 -2
  44. package/dist/{chunk-gxzbv67r.js → chunk-n9khyme2.js} +2 -2
  45. package/dist/{chunk-1vx4sf1y.js → chunk-nfmsn652.js} +2 -2
  46. package/dist/{chunk-ydtcvxsm.js → chunk-p196e4rq.js} +1 -1
  47. package/dist/{chunk-qm11hjd3.js → chunk-p4j4aawd.js} +1 -1
  48. package/dist/chunk-qvabd0vg.js +1 -0
  49. package/dist/{chunk-sanhjqpd.js → chunk-r083b7vn.js} +2 -2
  50. package/dist/{chunk-gb54hc78.js → chunk-rag8zchg.js} +1 -1
  51. package/dist/{chunk-ygx03mdh.js → chunk-rw6gv740.js} +1 -1
  52. package/dist/{chunk-jza1rsan.js → chunk-sf9pe2n6.js} +1 -1
  53. package/dist/chunk-t75wspk3.js +1 -0
  54. package/dist/{chunk-vpj0sv73.js → chunk-thvwt4kc.js} +3 -3
  55. package/dist/{chunk-yc53wz4r.js → chunk-v1p80wvh.js} +2 -2
  56. package/dist/chunk-vddqv6fv.js +1 -0
  57. package/dist/{chunk-948qe2pp.js → chunk-vvbd9fb5.js} +1 -1
  58. package/dist/{chunk-15d49qty.js → chunk-w154jyby.js} +1 -1
  59. package/dist/{chunk-dqvcgwhe.js → chunk-w4zvftrw.js} +2 -2
  60. package/dist/chunk-wa7v7akz.js +3 -0
  61. package/dist/chunk-wxwqz67n.js +1 -0
  62. package/dist/chunk-x9hm3p3a.js +1 -0
  63. package/dist/chunk-xd2g4zjx.js +1 -0
  64. package/dist/{chunk-tq52pbde.js → chunk-xkp4ph6v.js} +1 -1
  65. package/dist/{chunk-fz1vyc15.js → chunk-xsmtpkjm.js} +1 -1
  66. package/dist/{chunk-g6h6h8xr.js → chunk-yt39kfc6.js} +1 -1
  67. package/package.json +1 -1
  68. package/dist/chunk-069zpw09.js +0 -6
  69. package/dist/chunk-1m5r6mp2.js +0 -180
  70. package/dist/chunk-1q21sxhx.js +0 -1
  71. package/dist/chunk-1r6szcrj.js +0 -1
  72. package/dist/chunk-1x4fpe47.js +0 -1
  73. package/dist/chunk-2nkd1kjx.js +0 -1
  74. package/dist/chunk-417wefq7.js +0 -99
  75. package/dist/chunk-4ncbd4k0.js +0 -1
  76. package/dist/chunk-62881c2s.js +0 -1484
  77. package/dist/chunk-7443b95r.js +0 -1
  78. package/dist/chunk-79s052sw.js +0 -2
  79. package/dist/chunk-7jy60gnx.js +0 -1
  80. package/dist/chunk-c5tds5v0.js +0 -9
  81. package/dist/chunk-ccwskwb3.js +0 -1
  82. package/dist/chunk-f6mszdsd.js +0 -1
  83. package/dist/chunk-nz78b5c5.js +0 -10
  84. package/dist/chunk-r1764q6f.js +0 -1
  85. package/dist/chunk-r6mwyg3h.js +0 -3
  86. package/dist/chunk-rzzt21ef.js +0 -22
  87. package/dist/chunk-t8x2qpe2.js +0 -1
  88. package/dist/chunk-tjnfhm9v.js +0 -1
  89. package/dist/chunk-v0ygsjry.js +0 -1
  90. package/dist/chunk-zyz82mcd.js +0 -1
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as qe,T as re,A as se};
@@ -1,4 +1,4 @@
1
- import{X as H,Z as J}from"./chunk-62881c2s.js";import{qb as D}from"./chunk-417wefq7.js";import{Zc as G}from"./chunk-am8dtvff.js";import{re as B}from"./chunk-epj56s0n.js";async function U(){await G(B())}async function V(b){let f=b.message||b._?.[0];if(typeof f==="string"&&f.trim())return f;let q=b.stdin??process.stdin;if(!q.isTTY){let z=[];for await(let F of q)z.push(F);return Buffer.concat(z).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function X(b){if(!H(b))return{mode:"agent",content:b};let f=await J(b,{cwd:B(),surface:"headless",workspaceRoot:B()});if(!f.success)return{mode:"output",content:`Error: ${f.error||"未知错误"}`,exitCode:1};let q=f.data;if(q?.action==="invoke_skill"){let{skillName:z,skillArgs:F}=q;return{mode:"agent",content:F?`Please use the "${z}" skill to help me with: ${F}`:`Please use the "${z}" skill.`}}if(q?.action==="invoke_custom_command"||q?.action==="invoke_plugin_command"){let z=q.processedContent;return{mode:"agent",content:`# Custom Command: /${q.commandName}
1
+ import{W as H,Y as J}from"./chunk-1cvr3qtd.js";import{vb as D}from"./chunk-47dsd91k.js";import{cd as G}from"./chunk-m4htdpr9.js";import{we as B}from"./chunk-c9tzf9r5.js";async function U(){await G(B())}async function V(b){let f=b.message||b._?.[0];if(typeof f==="string"&&f.trim())return f;let q=b.stdin??process.stdin;if(!q.isTTY){let z=[];for await(let F of q)z.push(F);return Buffer.concat(z).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function X(b){if(!H(b))return{mode:"agent",content:b};let f=await J(b,{cwd:B(),surface:"headless",workspaceRoot:B()});if(!f.success)return{mode:"output",content:`Error: ${f.error||"未知错误"}`,exitCode:1};let q=f.data;if(q?.action==="invoke_skill"){let{skillName:z,skillArgs:F}=q;return{mode:"agent",content:F?`Please use the "${z}" skill to help me with: ${F}`:`Please use the "${z}" skill.`}}if(q?.action==="invoke_custom_command"||q?.action==="invoke_plugin_command"){let z=q.processedContent;return{mode:"agent",content:`# Custom Command: /${q.commandName}
2
2
 
3
3
  ${z}`}}return{mode:"output",content:f.content||f.message||"",exitCode:0}}function K(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function O(b){try{return await D.loadSession(b,B())}catch(f){if(K(f))return null;throw f}}async function $(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 z=B();return D.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:z,targetProjectPath:z})}let[f,q]=await Promise.all([D.loadSession(b.resume),D.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:f,metadata:q}}if(b.continue){let f=b.forkSession?await D.listSessions({cwd:B()}):await D.listSessions();if(f.length>0){let q=f[0].sessionId;if(b.forkSession){let z=B();return D.forkSession(q,{newSessionId:b.sessionId,sourceProjectPath:z,targetProjectPath:z})}return{sessionId:q,messages:await D.loadSession(q),metadata:f[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let f=await O(b.sessionId);return{sessionId:b.sessionId,messages:f??[],...f?{metadata:await D.findSessionMetadata(b.sessionId,B())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{U as m,V as n,X as o,$ as p};
@@ -0,0 +1 @@
1
+ import{Mc as a,Nc as b,Oc as c}from"./chunk-v1p80wvh.js";import"./chunk-0rp2ck29.js";import"./chunk-xkp4ph6v.js";import"./chunk-1kg9r8xp.js";import"./chunk-c9tzf9r5.js";import"./chunk-n9khyme2.js";import"./chunk-7xm3vjkz.js";import"./chunk-nfmsn652.js";import"./chunk-kcs3xa8f.js";import"./chunk-vvbd9fb5.js";import"./chunk-frcg8gea.js";import"./chunk-c2rhwxyn.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,2 +1,2 @@
1
- import{fd as W}from"./chunk-63ysxybd.js";import{ce as F,ee as k,he as H,ie as V}from"./chunk-tq52pbde.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{O as Ob};
1
+ import{kd as W}from"./chunk-kcwq1e7h.js";import{he as F,je as k,me as H,ne as V}from"./chunk-xkp4ph6v.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
+ export{O as Tb};
@@ -0,0 +1,99 @@
1
+ import{Ab as m,Bb as p0,Cb as Pq,Db as n0,Eb as i0,Fb as d0,Hb as C0,Kb as r0,Lb as hq,wb as P,xb as Iq,yb as c0,zb as uq}from"./chunk-k0p9ecgc.js";import{Kc as B0}from"./chunk-b4n34hrn.js";import{fd as H0}from"./chunk-4y28hykg.js";import{od as _q}from"./chunk-p4j4aawd.js";import{sd as Y0}from"./chunk-6cv4gddv.js";import{qe as mq,re as vq}from"./chunk-1kg9r8xp.js";import{we as Bq}from"./chunk-c9tzf9r5.js";import{Ce as Z0,Fe as Q0}from"./chunk-7xm3vjkz.js";import{Je as c}from"./chunk-nfmsn652.js";import{Qe as Sq,Re as V0,Te as D,Ue as j,We as l0,Xe as l,Ye as G0}from"./chunk-frcg8gea.js";import{readdir as Aq,readFile as s,rm as _0,stat as w$}from"node:fs/promises";import*as X from"node:path";import{nanoid as y}from"nanoid";import{createHash as rq,randomUUID as oq}from"node:crypto";import*as S from"node:fs/promises";import*as X0 from"node:path";var Hq=1;function aq(q,$){let T=rq("sha256").update($).digest("hex");return X0.join(V0(q),".locks",`${T}.lock`)}function O0(q,$){return q instanceof Error&&"code"in q&&q.code===$}async function E0(q){try{let $=JSON.parse(await S.readFile(q,"utf8"));if($.version!==Hq||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function Zq(q){let $=await E0(q);if($)return $;return await new Promise((T)=>setTimeout(T,10)),E0(q)}function tq(q){try{return process.kill(q,0),!0}catch($){return O0($,"EPERM")}}async function Qq(q,$){let T;try{return T=await S.open(q,"wx",384),await T.writeFile(`${JSON.stringify($)}
2
+ `,"utf8"),!0}catch(G){if(O0(G,"EEXIST"))return!1;if(T)await S.unlink(q).catch(()=>{return});throw G}finally{await T?.close().catch(()=>{return})}}class p extends Error{code="BLADE_SESSION_IN_USE";constructor(q){super(q?`Session is already active in another Blade process (PID ${q}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor(q,$){this.filePath=q;this.record=$}static async acquire(q,$=Bq()){let T=aq($,q),G={version:Hq,sessionId:q,ownerId:oq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await S.mkdir(X0.dirname(T),{recursive:!0,mode:448}),await Qq(T,G))return new n(T,G);let Z=await Zq(T);if(Z&&tq(Z.pid))throw new p(Z.pid);if(await S.unlink(T).catch((J)=>{if(!O0(J,"ENOENT"))throw J}),await Qq(T,G))return new n(T,G);throw new p((await Zq(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await E0(this.filePath))?.ownerId!==this.record.ownerId)return;await S.unlink(this.filePath).catch(($)=>{if(!O0($,"ENOENT"))throw $})}}function sq(q,$){for(let T of q){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let G=T.data.payload;if(!G||typeof G!=="object"||Array.isArray(G))continue;let Z=G;if(Z.toolCallId===$||T.data.partId===$||T.data.messageId===$)return Z}return}function Lq(q){let $=P(q),T=new Map;for(let G of $){if(G.type==="interaction_requested"){T.set(G.data.requestId,{request:G.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(G.type==="interaction_responded"){let Z=T.get(G.data.requestId);if(Z)Z.response=G.data;continue}if(G.type==="interaction_recovered"){let Z=T.get(G.data.requestId);if(Z)Z.recovery=G.data}}for(let G of T.values()){let Z=sq($,G.request.toolCallId);G.hasToolResult=Z!==void 0;let J=Z?.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0;G.hasRecoveryToolResult=J?.interactionRecovery===!0&&J.requestId===G.request.requestId}return[...T.values()]}function Oq(q){return Lq(q).reverse().find(($)=>!$.response&&!$.recovery)}function $T(q){let $=new Map;for(let T of Lq(q))$.set(T.request.toolCallId,T);return[...$.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function Vq(q){if(!q)return;return{type:q.request.interactionType,requestId:q.request.requestId}}var w0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function eq(q){try{if(q instanceof Error)return q.message;if(q!==null&&typeof q==="object"&&"message"in q&&typeof q.message==="string")return q.message;return String(q)}catch{return"Unknown error"}}function q$(q){let $=q.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test($))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test($))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test($))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test($))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test($))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test($))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test($))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test($))return"unsupported_input";return"runtime"}function $$(q){return{code:q,...w0[q]}}function Xq(q){return $$(q$(eq(q)))}function b0(q){if(!q||typeof q!=="object")return!1;let $=q;if(typeof $.code!=="string"||!($.code in w0))return!1;let T=w0[$.code];return $.message===T.message&&$.retryable===T.retryable}import{promises as q0,realpathSync as G$}from"node:fs";import K0 from"node:path";import*as d from"fs/promises";import*as W from"path";var Kq=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class i extends Error{code;constructor(q,$){super(q);this.code=$;this.name="PathSecurityError"}}class k0{static normalize(q,$){let T=W.isAbsolute(q)?q:W.resolve($,q),G=W.normalize(T),Z=W.normalize($);if(!this.isWithinWorkspace(G,Z))throw new i(`Path outside workspace: ${q} (resolved to ${G}, workspace: ${Z})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted(q){let $=q.split(W.sep);for(let T of Kq)if($.includes(T))throw new i(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(q){if(q.includes(".."))throw new i(`Path traversal not allowed: ${q}`,"PATH_TRAVERSAL")}static async validatePath(q,$){this.checkTraversal(q);let T=this.normalize(q,$);this.checkRestricted(T);try{await d.access(T)}catch(G){throw new i(`Path not found: ${q}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink(q,$){try{let T=await d.realpath(q),G=await d.realpath($);if(!this.isWithinWorkspace(T,G))throw new i(`Symlink points outside workspace: ${q} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof i)throw T;return q}}static getRelativePath(q,$){return W.relative($,q)}static isWithinWorkspace(q,$){let T=W.resolve(q),G=W.resolve($),Z=W.relative(G,T);return Z===""||Z!==".."&&!Z.startsWith(`..${W.sep}`)&&!W.isAbsolute(Z)}static async isWithinWorkspaceResolved(q,$){let T=W.resolve($),G=W.isAbsolute(q)?W.resolve(q):W.resolve(T,q);if(!this.isWithinWorkspace(G,T))return!1;let Z;try{Z=await d.realpath(T)}catch{return!1}let J=G;while(!0){try{let Q=await d.realpath(J);return this.isWithinWorkspace(Q,Z)}catch(Q){let H=Q.code;if(H!=="ENOENT"&&H!=="ENOTDIR")return!1}let B=W.dirname(J);if(B===J)return!1;J=B}}static isRestricted(q){let $=q.split(W.sep);return Kq.some((T)=>$.includes(T))}}var $0=Y0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead(q,$){try{let T=await q0.stat(q),G={filePath:K0.resolve(q),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(G),await this.recordAliases(q,G.filePath),$0.debug(`记录文件读取: ${q}`)}catch(T){$0.warn(`记录文件读取失败: ${q}`,T)}}async recordFileEdit(q,$,T="edit"){try{let G=await q0.stat(q),Z={filePath:K0.resolve(q),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:$,lastOperation:T};this.setRecord(Z),await this.recordAliases(q,Z.filePath),$0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${q}`)}catch(G){$0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${q}`,G)}}hasFileBeenRead(q,$){let T=this.accessedFiles.get(this.resolveTrackedPath(q));if(!T)return!1;return $?T.has($):T.size>0}async checkFileModification(q,$){let T=this.getFileRecord(q,$);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let G=await q0.stat(q);if(Math.abs(G.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${G.mtime.toISOString()})`};return{modified:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${Z.message}`}}}async checkExternalModification(q,$){let T=this.getFileRecord(q,$);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await q0.stat(q);if(G.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${G.mtime.toISOString()})`};return{isExternal:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return $0.warn(`检查文件外部修改失败: ${q}`,G),{isExternal:!1,message:`无法检查文件状态: ${Z.message}`}}}getFileRecord(q,$){let T=this.accessedFiles.get(this.resolveTrackedPath(q));if(!T)return;if($)return T.get($);return[...T.values()].sort((G,Z)=>Z.accessTime-G.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap((q)=>[...q.values()])}clearFileRecord(q,$){let T=this.resolveTrackedPath(q);if(!$){this.accessedFiles.delete(T),this.removeAliases(T);return}let G=this.accessedFiles.get(T);if(G?.delete($),G?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession(q,$){for(let[T,G]of this.accessedFiles.entries()){if($&&!k0.isWithinWorkspace(T,$))continue;if(G.delete(q),G.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord(q){let $=this.accessedFiles.get(q.filePath);if(!$)$=new Map,this.accessedFiles.set(q.filePath,$);$.set(q.sessionId,q)}async recordAliases(q,$){this.pathAliases.set(K0.resolve(q),$);let T=await q0.realpath(q).catch(()=>{return});if(T)this.pathAliases.set(T,$)}resolveTrackedPath(q){let $=K0.resolve(q);if(this.accessedFiles.has($))return $;let T=this.pathAliases.get($);if(T)return T;try{let G=G$.native($);return this.pathAliases.get(G)??G}catch{return $}}removeAliases(q){for(let[$,T]of this.pathAliases)if(T===q)this.pathAliases.delete($)}}import*as T0 from"node:crypto";import{promises as K}from"node:fs";import*as x from"node:path";import f0 from"write-file-atomic";var Yq="missing";class U0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor(q){if(D(q.sessionId),this.sessionId=q.sessionId,q.workspaceRoot&&!x.isAbsolute(q.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=q.workspaceRoot?x.resolve(q.workspaceRoot):void 0,this.enableCheckpoints=q.enableCheckpoints??!0,this.maxSnapshots=q.maxSnapshots??10;let $=G0();this.snapshotDir=x.join($,"file-history",this.sessionId),this.manifestPath=x.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await K.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let q=G0(),$=await K.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=T0.createHash("sha256").update($).digest("hex").slice(0,24),G=x.join(q,"file-history",this.sessionId),Z=x.join(q,"file-history","workspaces",T,this.sessionId),J=x.join(Z,"manifest.json");try{await K.access(J)}catch{await this.migrateLegacySnapshotDir(G,Z,$)}this.snapshotDir=Z,this.manifestPath=J}async migrateLegacySnapshotDir(q,$,T){let G;try{G=JSON.parse(await K.readFile(x.join(q,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((Z)=>this.isWithinWorkspace(Z.filePath,T)))return;await K.mkdir(x.dirname($),{recursive:!0,mode:493});try{await K.rename(q,$)}catch(Z){let J=Z.code;if(J!=="ENOENT"&&J!=="EEXIST"&&J!=="ENOTEMPTY")throw Z}}isWithinWorkspace(q,$){if(!x.isAbsolute(q))return!1;let T=x.relative($,x.resolve(q));return T===""||T!==".."&&!T.startsWith(`..${x.sep}`)&&!x.isAbsolute(T)}async createSnapshot(q,$){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity(q),G=!0;try{await K.access(T)}catch{G=!1}let Z=this.trackedFileBackups.get(T),J=Z?Z.version+1:1,B=this.generateFileHash(T,J),Q=this.getSnapshotPath(B,J),H=new Date;if(G){let L=await K.readFile(T);await K.writeFile(Q,L)}let O={backupFileName:B,version:J,backupTime:H};return this.trackedFileBackups.set(T,O),this.snapshots.push({messageId:$,backupFileName:B,timestamp:H,filePath:T,version:J,existedBefore:G}),await this.cleanupOldSnapshots(T),await this.persistManifest(),O}async recordPostEditState(q,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(q),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===$.backupFileName&&Z.version===$.version);if(!G)throw Error(`未找到待完成的快照: ${T}`);G.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot(q,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(q),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===$.backupFileName&&Z.version===$.version);if(!G)return;this.removeSnapshot(G),await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),await this.persistManifest()}async rewindLatest(q){let $=await this.resolveFileIdentity(q),T=this.snapshots.slice().reverse().find((J)=>J.filePath===$&&J.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${$}`);if(await this.hashFile($)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${$}`);let Z=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let J=await K.readFile(Z);await K.mkdir(x.dirname($),{recursive:!0}),await K.writeFile($,J)}else await K.rm($,{force:!0});return this.removeSnapshot(T),await K.rm(Z,{force:!0}),await this.persistManifest(),T}async restoreSnapshot(q,$){let T=await this.resolveFileIdentity(q),G=this.snapshots.slice().reverse().find((J)=>J.messageId===$&&J.filePath===T);if(!G)throw Error(`未找到快照: messageId=${$}, filePath=${T}`);let Z=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let J=await K.readFile(Z);await K.mkdir(x.dirname(T),{recursive:!0}),await K.writeFile(T,J)}else await K.rm(T,{force:!0})}async listSnapshots(q){let $=await this.resolveFileIdentity(q);return this.snapshots.filter((T)=>T.filePath===$)}async listAllSnapshots(){return this.snapshots.filter((q)=>q.postEditHash!==void 0)}async previewRewind(q){let $=this.buildRewindPlan(q);return{files:$.map((T)=>T.filePath),snapshotCount:$.reduce((T,G)=>T+G.selected.length,0)}}async rewindSnapshots(q){let $=this.buildRewindPlan(q);if($.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let Z of $){let J,B=!0;try{J=await K.readFile(Z.filePath)}catch(H){if(H.code!=="ENOENT")throw H;B=!1}if((J?T0.createHash("sha256").update(J).digest("hex"):Yq)!==Z.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${Z.filePath}`);if(T.set(Z.filePath,{existed:B,content:J}),Z.target.existedBefore)await K.access(this.getSnapshotPath(Z.target.backupFileName,Z.target.version))}let G=[...this.snapshots];try{for(let J of $)if(J.target.existedBefore){let B=await K.readFile(this.getSnapshotPath(J.target.backupFileName,J.target.version));await K.mkdir(x.dirname(J.filePath),{recursive:!0}),await f0(J.filePath,B)}else await K.rm(J.filePath,{force:!0});let Z=new Set($.flatMap((J)=>J.selected));this.snapshots=this.snapshots.filter((J)=>!Z.has(J)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...Z].map((J)=>K.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return})))}catch(Z){this.snapshots=G,this.rebuildTrackedFileBackups();let J=[];for(let[B,Q]of T)try{if(Q.existed&&Q.content)await f0(B,Q.content);else await K.rm(B,{force:!0})}catch(H){J.push(H)}if(J.length>0)throw AggregateError([Z,...J],"快照回退失败且无法完整恢复回退前状态");throw Z}return{files:$.map((Z)=>Z.filePath),snapshotCount:$.reduce((Z,J)=>Z+J.selected.length,0)}}async commitSnapshots(q){let $=this.buildRewindPlan(q),T=new Set($.flatMap((Z)=>Z.selected));if(T.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((Z)=>!T.has(Z)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(Z){throw this.snapshots=G,this.rebuildTrackedFileBackups(),Z}return await Promise.all([...T].map((Z)=>K.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return}))),{files:$.map((Z)=>Z.filePath),snapshotCount:T.size}}buildRewindPlan(q){let $=new Set(q),T=this.snapshots.filter((J)=>J.postEditHash!==void 0),G=T.filter((J)=>$.has(J.messageId));return[...new Set(G.map((J)=>J.filePath))].sort().map((J)=>{let B=T.filter((L)=>L.filePath===J),Q=B.filter((L)=>$.has(L.messageId)),H=B.indexOf(Q[0]),O=B.slice(H);if(O.length!==Q.length||O.some((L)=>!$.has(L.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${J}`);return{filePath:J,selected:Q,target:Q[0],latest:Q.at(-1)}})}async loadManifest(){try{let q=await K.readFile(this.manifestPath,"utf-8"),$=JSON.parse(q);if($.schemaVersion!==1||!Array.isArray($.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all($.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch(q){if(q.code!=="ENOENT")throw q;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await K.rm(this.manifestPath,{force:!0});return}let q={schemaVersion:1,snapshots:this.snapshots.map(($)=>({...$,timestamp:$.timestamp.toISOString()}))};await f0(this.manifestPath,JSON.stringify(q,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots(q){let T=this.snapshots.filter((G)=>G.filePath===q).slice(0,-this.maxSnapshots);for(let G of T)await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup(q=0){let $=this.snapshots.slice().sort((G,Z)=>Z.timestamp.getTime()-G.timestamp.getTime()),T=new Set($.slice(0,q));for(let G of this.snapshots)if(!T.has(G))await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0});this.snapshots=$.slice(0,q).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath(q,$){return x.join(this.snapshotDir,`${q}@v${$}`)}async resolveFileIdentity(q){let $=x.resolve(q),T=[],G=$;while(!0){try{let J=await K.realpath(G);return x.join(J,...T.reverse())}catch(J){let B=J.code;if(B!=="ENOENT"&&B!=="ENOTDIR")throw J}let Z=x.dirname(G);if(Z===G)return $;T.push(x.basename(G)),G=Z}}async hashFile(q){try{let $=await K.readFile(q);return T0.createHash("sha256").update($).digest("hex")}catch($){if($.code==="ENOENT")return Yq;throw $}}removeSnapshot(q){let $=this.snapshots.indexOf(q);if($>=0)this.snapshots.splice($,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let q of this.snapshots){let $=this.trackedFileBackups.get(q.filePath);if(!$||$.version<q.version)this.trackedFileBackups.set(q.filePath,{backupFileName:q.backupFileName,version:q.version,backupTime:q.timestamp})}}generateFileHash(q,$){let T=T0.createHash("md5");return T.update(`${q}:${$}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as N$}from"node:crypto";import Dq from"node:path";import{StringDecoder as B$}from"node:string_decoder";function J$(q,$){let T=$;while(T<q.length&&(q[T]&192)===128)T+=1;return T}class g0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor(q=1048576){this.maxBytes=q;if(!Number.isSafeInteger(q)||q<=0)throw Error("maxBytes must be a positive safe integer")}append(q){let $=Buffer.isBuffer(q)?Buffer.from(q):Buffer.from(q);if($.length===0)return;this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let q=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,q}trimToLimit(){while(this.retainedBytes>this.maxBytes){let q=this.chunks[0];if(!q)return;let $=this.retainedBytes-this.maxBytes;if(q.length<=$){this.chunks.shift(),this.retainedBytes-=q.length,this.omittedBytes+=q.length;continue}let T=J$(q,$);this.chunks[0]=q.subarray(T),this.retainedBytes-=T,this.omittedBytes+=T}}}var N0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},r={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},Uq={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Z$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Q$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:N0,summaryTemplate:(q)=>`Successfully processed ${q} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:N0,summaryTemplate:(q)=>`Package operation completed (${q} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:r,summaryTemplate:(q)=>`Build completed (${q} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:Uq},{pattern:/^git\s+(status|branch|remote)/i,config:r},{pattern:/^git\s+(log|diff|show)/i,config:Uq},{pattern:/^(ls|dir|tree)\s+/i,config:r,summaryTemplate:(q)=>`Listed ${q} items`},{pattern:/^find\s+/i,config:r,summaryTemplate:(q)=>`Found ${q} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:r,summaryTemplate:(q)=>`Found ${q} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:N0,summaryTemplate:(q)=>`Docker operation completed (${q} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:N0,summaryTemplate:(q)=>`Python package operation completed (${q} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:r,summaryTemplate:(q)=>`Rust operation completed (${q} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:r,summaryTemplate:(q)=>`Go operation completed (${q} lines)`}];class y0{static getConfigForCommand(q){for(let{pattern:$,config:T,summaryTemplate:G}of Q$)if($.test(q))return{config:T,summaryTemplate:G};return{config:Z$}}static truncate(q,$){let{config:T,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(q,T,G)}static truncateWithConfig(q,$,T){let G=q.length,Z=q.split(`
3
+ `),J=Z.length;if(J<=$.maxLines&&G<=$.maxChars)return{content:q,truncated:!1,originalLines:J,originalChars:G};let B=Z.slice(0,$.keepHead),Q=Z.slice(-$.keepTail),H=J-$.keepHead-$.keepTail,O=B.join(`
4
+ `);if(O+=`
5
+
6
+ ... (${H} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${J} total) ...
7
+
8
+ `,O+=Q.join(`
9
+ `),O.length>$.maxChars){let V=Math.floor($.maxChars/2)-50,Y=O.slice(0,V),U=O.slice(-V);O=`${Y}
10
+
11
+ ... (content truncated to ${$.maxChars} chars) ...
12
+
13
+ ${U}`}let L=$.summarize&&T?T(J,G):void 0;if(L)O+=`
14
+
15
+ [Summary: ${L}]`;return{content:O,truncated:!0,originalLines:J,originalChars:G,summary:L}}static truncateForLLM(q,$,T){let G=this.truncate(q,T),Z=this.truncate($,T),J;if(G.truncated||Z.truncated){let B=[];if(G.truncated)B.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
16
+ `).length} lines`);if(Z.truncated)B.push(`stderr: ${Z.originalLines} lines -> ${Z.content.split(`
17
+ `).length} lines`);J=`Output truncated: ${B.join(", ")}`}return{stdout:G.content,stderr:Z.content,truncationInfo:J}}static shouldTruncate(q,$){let{config:T}=this.getConfigForCommand($);return q.split(`
18
+ `).length>T.maxLines||q.length>T.maxChars}static getStats(q){return{lines:q.split(`
19
+ `).length,chars:q.length,words:q.split(/\s+/).filter(Boolean).length}}}var Nq=32768,H$=1048576,L$=65536,O$=3600000,xq=4096,V$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class j0{stream;executionId;onEvent;output=new g0(H$/2);decoder=new B$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(q,$,T){this.stream=q;this.executionId=$;this.onEvent=T}append(q){let $=Buffer.isBuffer(q)?q:Buffer.from(q);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<xq){let G=$.subarray(0,Math.min($.length,xq-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let T=Fq(this.decoder.write($));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let q=Fq(this.decoder.end());this.output.append(q),this.emit(q)}snapshot(){let q=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:q.content,omittedBytes:q.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(q){if(!q||!this.onEvent||this.streamTruncated)return;let $=L$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let T=X$(q,$);if(this.streamedBytes+=Buffer.byteLength(T),T.length<q.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:T,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function Fq(q){return q.replace(V$,"")}function X$(q,$){let T=Buffer.from(q);if(T.length<=$)return q;let G=$;while(G>0&&(T[G]&192)===128)G-=1;return T.subarray(0,G).toString("utf8")}function Wq(q){return q.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function K$(q){let $=q.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>Nq)throw Error(`User shell command exceeds ${Nq} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function Y$(){return{execute(q,$){return new Promise((T)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",Z=process.platform==="win32"?["/d","/s","/c",q]:["-l","-c",q],{child:J,processTree:B}=_q(G,Z,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),Q="",H="",O=!1,L=!1,V=!1,Y,U=()=>{return Y??=B.terminate(),Y},b=setTimeout(()=>{O=!0,U()},$.timeoutMs),z=()=>{L=!0,U()};if($.signal.addEventListener("abort",z,{once:!0}),$.signal.aborted)z();J.stdout?.on("data",(C)=>{$.onOutput?.("stdout",C)}),J.stderr?.on("data",(C)=>{$.onOutput?.("stderr",C)});let w=async(C)=>{if(V)return;if(V=!0,clearTimeout(b),$.signal.removeEventListener("abort",z),O||L)await U();T({...C,stdout:"",stderr:"",timedOut:O,aborted:L})};J.once("error",(C)=>{w({exitCode:null,error:C.message})}),J.once("close",(C)=>{w({exitCode:C})})})}}}async function _T(q,$){let T=K$(q),G=$.timeoutMs??O$,Z=new j0("stdout",$.executionId,$.onEvent),J=new j0("stderr",$.executionId,$.onEvent),B=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:T});let Q,H=!1,O=!1;try{Q=await($.executor??Y$()).execute(T,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(z,w)=>{if(z==="stdout")H=!0;else O=!0;(z==="stdout"?Z:J).append(w)}})}catch(z){Q={exitCode:null,stdout:"",stderr:"",error:z instanceof Error?z.message:String(z)}}if(!H)Z.append(Q.stdout);if(!O)J.append(Q.stderr);Z.finish(),J.finish(),await Promise.all([Z.flushEvents(),J.flushEvents()]);let L=Z.snapshot(),V=J.snapshot(),Y=y0.truncateForLLM(L.content.trim(),V.content.trim(),T),U=Q.aborted||$.signal.aborted?"aborted":Q.timedOut?"timed_out":Q.error?"spawn_error":Q.exitCode===0?"completed":"failed",b={version:1,command:T,status:U,exitCode:Q.exitCode,durationMs:Math.max(0,Date.now()-B),stdout:Y.stdout,stderr:Q.error?[Y.stderr,Q.error].filter(Boolean).join(`
20
+ `):Y.stderr,stdoutOmittedBytes:L.omittedBytes,stderrOmittedBytes:V.omittedBytes,binaryOutput:L.binary||V.binary,truncated:Boolean(Y.truncationInfo)||L.omittedBytes>0||V.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:b}),b}function CT(q){let $=[q.stdout?`stdout:
21
+ ${q.stdout}`:"",q.stderr?`stderr:
22
+ ${q.stderr}`:""].filter(Boolean).join(`
23
+ `);return["<user_shell_command>",`<command>${Wq(q.command)}</command>`,"<result>",`Status: ${q.status}`,`Exit code: ${q.exitCode??"null"}`,`Duration: ${(q.durationMs/1000).toFixed(3)} seconds`,`Output:
24
+ ${Wq($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
25
+ `)}function Cq(q){let $=[q.stdout,q.stderr?`stderr:
26
+ ${q.stderr}`:""].filter(Boolean).join(`
27
+ `);return[`! ${q.command}`,$||"(no output)"].join(`
28
+ `)}function U$(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if($.version!==1||typeof $.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String($.status))||$.exitCode!==null&&typeof $.exitCode!=="number"||typeof $.durationMs!=="number"||typeof $.stdout!=="string"||typeof $.stderr!=="string"||typeof $.stdoutOmittedBytes!=="number"||typeof $.stderrOmittedBytes!=="number"||typeof $.binaryOutput!=="boolean"||typeof $.truncated!=="boolean")return;return $}function x0(q){if(!q||typeof q!=="object"||Array.isArray(q))return;return U$(q.userShellCommand)}var F0=16777216,zq=65536,ET=1048576,x$=8,W0=200,F$=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,W$=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,_$=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,C$=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),z$=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function f(q,$){return q.count+=1,$}function D$(q){return F$.test(q.replace(/[A-Z]/g,($)=>`_${$.toLowerCase()}`))}function R$(q){return[...q].filter(($)=>{if($===`
29
+ `||$==="\r"||$==="\t")return!0;let T=$.codePointAt(0)??0;if(T<32||T===127)return!1;if(T>=57344&&T<=63743)return!1;if(T>=983040&&T<=1048573)return!1;if(T>=1048576&&T<=1114109)return!1;if(T>=917504&&T<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test($)}).join("")}function k(q,$){let T=q.normalize("NFKC"),G=T.replace(C$,"");if(G!==T)$.count+=1;T=G,T=T.replace(z$,()=>f($,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>f($,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>f($,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>f($,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(J,B,Q)=>`${B}${Q}${f($,"[redacted]")}`);let Z=R$(T);if(Z!==T)$.count+=1;return Z.replace(/\r\n?/g,`
30
+ `)}function Rq(q,$,T){if(/^data:[^;,]+;base64,/i.test(q))return f(T,"[binary omitted]");let G=k(q,T),Z=Dq.resolve($);for(let J of[Z,Z.startsWith("/private/")?Z.slice(8):`/private${Z}`])G=G.replaceAll(J,".");return G=G.replace(W$,(J)=>J.startsWith("./")?J:f(T,"[host-path]")),G=G.replace(_$,()=>f(T,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(J)=>{try{let B=new URL(J);if(B.username||B.password||B.search||B.hash)T.count+=1;return B.username="",B.password="",B.search="",B.hash="",B.toString()}catch{return f(T,"[redacted-url]")}}),G}function v0(q,$,T,G=0,Z){if(Z&&D$(Z))return f(T,"[redacted]");if(G>=x$)return f(T,"[depth limit]");if(typeof q==="string")return Rq(q,$,T);if(q===null||typeof q==="boolean"||typeof q==="number"&&Number.isFinite(q))return q;if(Array.isArray(q)){let J=q.slice(0,W0).map((B)=>v0(B,$,T,G+1));if(q.length>J.length)J.push(f(T,`[${q.length-J.length} items omitted]`));return J}if(q&&typeof q==="object"){let J={},B=Object.entries(q);for(let[Q,H]of B.slice(0,W0))J[k(Q,T)]=v0(H,$,T,G+1,Q);if(B.length>W0)J["[entries omitted]"]=B.length-W0;return J}return String(q)}function M$(q,$){let T=Buffer.from(q,"utf8");if(T.length<=$)return q;let G=T.subarray(0,$).toString("utf8");while(Buffer.byteLength(G,"utf8")>$)G=G.slice(0,-1);return G}function A$(q,$,T){let G=JSON.stringify(v0(q,$,T),null,2);if(Buffer.byteLength(G,"utf8")<=zq)return G;T.count+=1;let Z=`
31
+ ... [activity truncated]`;return M$(G,zq-Buffer.byteLength(Z))+Z}function I0(q,$=""){let T=Math.max(2,...[...q.matchAll(/`+/g)].map((Z)=>Z[0].length)),G="`".repeat(T+1);return`${G}${$}
32
+ ${q}
33
+ ${G}`}function S0(q){return q.replace(/\s+/g," ").trim()}function E$(q){let $=new Map,T=new Map,G=new Map,Z=0;for(let J of P(q)){if(J.type==="message_created"){let L=T.get(J.data.messageId);if(L)L.role=J.data.role,L.metadata=J.data.metadata,$.set(J.data.messageId,L),T.delete(J.data.messageId);else if(!$.has(J.data.messageId))$.set(J.data.messageId,{order:Z++,role:J.data.role,parts:[],metadata:J.data.metadata});continue}if(J.type!=="part_created"&&J.type!=="part_updated")continue;let B=$.get(J.data.messageId)??T.get(J.data.messageId);if(!B)B={order:Z++,role:"activity",parts:[]},T.set(J.data.messageId,B);let Q=`${J.data.messageId}\x00${J.data.partType}\x00${J.data.partId}`,H=G.get(Q);if(H){H.event=J;continue}let O={order:Z++,event:J};G.set(Q,O),B.parts.push(O)}return[...$.values(),...T.values()].sort((J,B)=>J.order-B.order)}function m0(q,$,T,G){return`## Activity: ${q}
34
+
35
+ ${I0(A$($,T.projectPath,G),"json")}`}function Mq(q,$,T={}){let G={count:0},Z=T.includeReasoning===!0,J=[],B=0,Q=0,H=0;for(let w of E$(q)){let C=x0(w.metadata);if(C){let R=k(C.command,G),M=k([C.stdout,C.stderr?`stderr:
36
+ ${C.stderr}`:""].filter(Boolean).join(`
37
+ `)||"(no output)",G);J.push(`## User shell command
38
+
39
+ ${I0(`$ ${R}
40
+ ${M}`,"console")}`),B+=1;continue}let I=[],o=[],_=[],u=Number.POSITIVE_INFINITY;for(let R of w.parts.sort((M,E)=>M.order-E.order)){let{partType:M,payload:E}=R.event.data;if(M==="text"){let N=E.text;if(typeof N==="string"&&N.trim())I.push(k(N,G)),u=Math.min(u,R.order)}else if(M==="image"){let N=E.mimeType;o.push(typeof N==="string"?`[Image: ${k(N,G)}]`:"[Image]"),u=Math.min(u,R.order)}else if(M==="reasoning"&&Z){let N=E.text;if(typeof N==="string"&&N.trim())_.push({order:R.order,markdown:`## Reasoning
41
+
42
+ ${k(N,G).trim()}`}),H+=1}else if(M==="tool_call"){let N=E,a=typeof N.toolName==="string"?k(N.toolName,G):"unknown";_.push({order:R.order,markdown:m0(`${a} call`,N.input??{},$,G)}),Q+=1}else if(M==="tool_result"){let N=E,a=typeof N.toolName==="string"?k(N.toolName,G):"unknown";_.push({order:R.order,markdown:m0(`${a} result`,typeof N.error==="string"?{error:N.error}:{output:N.output??null},$,G)}),Q+=1}else if(M==="summary"){let N=E.text;if(typeof N==="string"&&N.trim())_.push({order:R.order,markdown:`## Summary
43
+
44
+ ${k(N,G).trim()}`})}else if(M==="subtask_ref")_.push({order:R.order,markdown:m0("Subagent",E,$,G)}),Q+=1;else if(M==="diff"||M==="patch"){let N=typeof E==="string"?E:JSON.stringify(E,null,2);_.push({order:R.order,markdown:`## File changes
45
+
46
+ ${I0(Rq(N,$.projectPath,G),"diff")}`}),Q+=1}}if((w.role==="user"||w.role==="assistant")&&(I.length>0||o.length>0))_.push({order:u,markdown:`## ${w.role==="user"?"User":"Assistant"}
47
+
48
+ ${[...I,...o].join(`
49
+
50
+ `).trim()}`}),B+=1;J.push(..._.sort((R,M)=>R.order-M.order).map((R)=>R.markdown))}if(J.length===0)throw Error("No conversation content to export");let O=`${J.join(`
51
+
52
+ `)}
53
+ `,L=Buffer.byteLength(O,"utf8");if(L>F0)throw Error(`Session export exceeds ${F0} bytes`);let V=N$("sha256").update(O).digest("hex"),Y=Dq.basename($.taskSourceProjectPath??$.projectPath),U=$.selectedModelId??$.taskModelId,z=["# Blade conversation","",`- Session: \`${$.sessionId}\``,...$.title?[`- Title: ${S0(k($.title,G))}`]:[],`- Project: \`${S0(k(Y,G))}\``,...U?[`- Model: \`${S0(k(U,G))}\``]:[],...$.permissionMode?[`- Permission mode: ${$.permissionMode}`]:[],`- Created: ${$.firstMessageTime}`,`- Updated: ${$.lastMessageTime}`,`- State: ${$.archivedAt?"archived":"active"}`,`- Reasoning: ${Z?"included":"omitted"}`,...$.reasoningEffort?[`- Reasoning effort: ${$.reasoningEffort}`]:[],...$.serviceTier?[`- Service tier: ${$.serviceTier}`]:[],...$.responseVerbosity?[`- Response verbosity: ${$.responseVerbosity}`]:[],...$.communicationStyle?[`- Communication style: ${$.communicationStyle}`]:[],...$.communicationStyleDigest?[`- Communication style SHA-256: \`${$.communicationStyleDigest}\``]:[],...$.projectInstructionsDigest?[`- Project instructions SHA-256: \`${$.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${V}\``,`- Content bytes: ${L}`,`- Redactions: ${G.count}`,"","---",""].join(`
54
+ `)+`
55
+ `+O;if(Buffer.byteLength(z,"utf8")>F0)throw Error(`Session export exceeds ${F0} bytes`);return{filename:`blade-session-${$.sessionId.slice(0,12)}.md`,markdown:z,contentSha256:V,contentBytes:L,messageCount:B,activityCount:Q,reasoningIncluded:Z,reasoningCount:H,redactionCount:G.count}}var u0=Y0("Service"),Eq=new Set(["queued","running","completed","failed","cancelled","interrupted"]),o0=new Set(["local","worktree"]),b$=new Set(["default","autoEdit","yolo","plan"]),k$=new Set(["applied","discarded","conflicted"]);class a0 extends Error{}function wq(q){try{return process.kill(q,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}}function bq(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((G)=>typeof $[G]!=="string"||!$[G])||typeof $.sourceHadChanges!=="boolean"||$.sourceStateFingerprint!==void 0&&(typeof $.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test($.sourceStateFingerprint)))return;return $}function kq(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if(!k$.has(String($.status))||typeof $.updatedAt!=="string"||!Number.isFinite(Date.parse($.updatedAt))||$.sourceCommit!==void 0&&(typeof $.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test($.sourceCommit))||$.changedFiles!==void 0&&(typeof $.changedFiles!=="number"||!Number.isInteger($.changedFiles)||$.changedFiles<0)||$.message!==void 0&&(typeof $.message!=="string"||!$.message.trim()||$.message.length>500))return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...typeof $.changedFiles==="number"?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function fq(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if(["changedFiles","additions","deletions","commits"].some((G)=>typeof $[G]!=="number"||!Number.isInteger($[G])||$[G]<0))return;return $}function gq(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if($.version!==1||typeof $.prompt!=="string"||!$.prompt.trim()||$.prompt.length>32000||typeof $.sourceProjectPath!=="string"||!X.isAbsolute($.sourceProjectPath)||!o0.has($.isolation)||!z0($.permissionMode)||$.title!==void 0&&(typeof $.title!=="string"||!$.title.trim()||$.title.length>200)||$.modelId!==void 0&&(typeof $.modelId!=="string"||!$.modelId.trim()||$.modelId.length>500)||$.reasoningEffort!==void 0&&!B0($.reasoningEffort)||$.serviceTier!==void 0&&!Q0($.serviceTier)||$.responseVerbosity!==void 0&&!Z0($.responseVerbosity)||$.communicationStyle!==void 0&&!H0($.communicationStyle)||$.communicationStyleDigest!==void 0&&(typeof $.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))||$.projectInstructionsDigest!==void 0&&(typeof $.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest)))return;let T;if($.attachments!==void 0){if(!Array.isArray($.attachments)||$.attachments.length>mq)return;let G=0;for(let Z of $.attachments){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let J=Z;if(!["file","image","url"].includes(String(J.type)))return;for(let B of["path","url","content","mimeType","name"])if(J[B]!==void 0&&typeof J[B]!=="string")return;G+=typeof J.content==="string"?Buffer.byteLength(J.content):0}if(G>vq)return;T=$.attachments.map((Z)=>{let J=Z;return{type:J.type,...J.path!==void 0?{path:J.path}:{},...J.url!==void 0?{url:J.url}:{},...J.content!==void 0?{content:J.content}:{},...J.mimeType!==void 0?{mimeType:J.mimeType}:{},...J.name!==void 0?{name:J.name}:{}}})}return{version:1,prompt:$.prompt,...typeof $.title==="string"?{title:$.title}:{},sourceProjectPath:X.resolve($.sourceProjectPath),isolation:$.isolation,permissionMode:$.permissionMode,...typeof $.modelId==="string"?{modelId:$.modelId}:{},...B0($.reasoningEffort)?{reasoningEffort:$.reasoningEffort}:{},...Q0($.serviceTier)?{serviceTier:$.serviceTier}:{},...Z0($.responseVerbosity)?{responseVerbosity:$.responseVerbosity}:{},...H0($.communicationStyle)?{communicationStyle:$.communicationStyle}:{},...typeof $.communicationStyleDigest==="string"?{communicationStyleDigest:$.communicationStyleDigest}:{},...typeof $.projectInstructionsDigest==="string"?{projectInstructionsDigest:$.projectInstructionsDigest}:{},...T?{attachments:T}:{}}}function z0(q){return typeof q==="string"&&b$.has(q)}function yq(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q;if(typeof $.sessionId!=="string"||!$.sessionId||typeof $.projectPath!=="string"||!X.isAbsolute($.projectPath))return;return{sessionId:$.sessionId,projectPath:X.resolve($.projectPath)}}var lq={stat(q){return w$(q,{bigint:!0})},readFile(q){return s(q,"utf-8")}},J0=lq;function aT(q){J0=q}function tT(){J0=lq}class cq extends Error{constructor(q){super(`Session has no durable creation record: ${q}`);this.name="SessionMissingCreationError"}}class e extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor(q,$){super(q===$?`Session is archived: ${q}`:`Session is archived by ancestor ${$}: ${q}`);this.sessionId=q;this.archivedBySessionId=$;this.name="SessionArchivedError"}}class v extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor(q){super(q);this.name="SessionArchiveConflictError"}}function P0(q,$){return`${q}\x00${$}`}function pq(q){return typeof q==="string"&&q.length<=64&&Number.isFinite(Date.parse(q))}function f$(q){let $=new Map(q.map((T)=>[P0(T.projectPath,T.sessionId),T]));return q.map((T)=>{let G=T,Z=new Set;while(G){let H=P0(G.projectPath,G.sessionId);if(Z.has(H))break;if(Z.add(H),pq(G.archivedAt))return{...T,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?$.get(P0(G.projectPath,G.parentId)):void 0}let{archivedAt:J,archivedBySessionId:B,...Q}=T;return Q})}function h0(q,$){let T=f$(q);if($===null)return T;return T.filter((G)=>Boolean(G.archivedAt)===$)}class F{static toUISafeMessages(q){let $=Date.now(),T=q.length,G=[];return q.forEach((Z,J)=>{if(Z.role!=="user"&&Z.role!=="assistant")return;let B;if(typeof Z.content==="string")B=Z.content;else if(Array.isArray(Z.content))B=Z.content.map((V)=>V.type==="text"?V.text:"[Image]").join("");else B="";let Q=B.trim();if(!Q)return;let H=x0(Z.metadata),O=H?Cq(H):Q,L=G[G.length-1];if(L&&L.role===Z.role&&L.content===O)return;G.push({id:`restored-${$}-${J}`,role:Z.role,content:O,timestamp:$-(T-J)*1000,metadata:Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0})}),G}static async listSessionPage(q={}){let $=n0(q),T=await this.listSessionPageFromProjection($);if(T)return T;let Z=(await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,$.cursor?5000:0,$.archived)).sort(i0),J=d0(Z,$);return{sessions:J.sessions.map((B)=>this.toPublicMetadata(B)),nextCursor:J.nextCursor}}static async listSessionPageFromProjection(q){let $=Pq(q);try{let T=await C0();if(!T)return null;await r0(T,this.projectionDeriver(),q.cursor?5000:0);let G=[],Z=[];if(q.cwd)G.push("s.project_path = ?"),Z.push(q.cwd);if(!q.includeSubagents)G.push("s.is_subagent = 0");if(G.push(q.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),$){G.push(`(
56
+ s.last_message_time < ?
57
+ OR (
58
+ s.last_message_time = ?
59
+ AND (
60
+ s.project_sort_key > ?
61
+ OR (s.project_sort_key = ? AND s.session_sort_key > ?)
62
+ )
63
+ )
64
+ )`);let H=p0($.projectPath);Z.push($.lastMessageTime,$.lastMessageTime,H,H,p0($.sessionId))}let B=T.prepare(`WITH RECURSIVE archive_members(
65
+ project_path, session_id, archive_root_id, effective_archived_at, depth
66
+ ) AS (
67
+ SELECT project_path, session_id, session_id, archived_at, 0
68
+ FROM sessions
69
+ WHERE archived_at IS NOT NULL
70
+ UNION ALL
71
+ SELECT child.project_path, child.session_id, parent.archive_root_id,
72
+ parent.effective_archived_at, parent.depth + 1
73
+ FROM sessions child
74
+ JOIN archive_members parent
75
+ ON child.project_path = parent.project_path
76
+ AND child.parent_id = parent.session_id
77
+ WHERE parent.depth < 128
78
+ ),
79
+ ranked_archive AS (
80
+ SELECT project_path, session_id, archive_root_id,
81
+ effective_archived_at,
82
+ ROW_NUMBER() OVER (
83
+ PARTITION BY project_path, session_id
84
+ ORDER BY depth ASC, archive_root_id ASC
85
+ ) AS rank
86
+ FROM archive_members
87
+ )
88
+ SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
89
+ FROM sessions s
90
+ LEFT JOIN ranked_archive a
91
+ ON a.project_path = s.project_path
92
+ AND a.session_id = s.session_id
93
+ AND a.rank = 1
94
+ ${G.length>0?`WHERE ${G.join(" AND ")}`:""}
95
+ ORDER BY s.last_message_time DESC,
96
+ s.project_sort_key ASC,
97
+ s.session_sort_key ASC
98
+ LIMIT ?`).all(...Z,q.limit+1).map((H)=>{let O=JSON.parse(H.metadata_json);if(H.archive_root_id&&H.effective_archived_at)return{...O,archivedAt:H.effective_archived_at,archivedBySessionId:H.archive_root_id};let{archivedAt:L,archivedBySessionId:V,...Y}=O;return Y}),Q=d0(B,q);return{sessions:Q.sessions.map((H)=>this.toPublicMetadata(H)),nextCursor:Q.nextCursor}}catch{return null}}static async listSessions(q={}){let $=n0(q),T=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived),G=new Set;return T.sort(i0).flatMap((Z)=>{let J=`${Z.projectPath}\x00${Z.sessionId}`;if(G.has(J))return[];return G.add(J),[this.toPublicMetadata(Z)]})}static async findSessionMetadata(q,$){if(D(q),$!==void 0){if(!X.isAbsolute($))throw Error("Session catalog cwd must be absolute");let G=X.resolve($),Z=this.getSessionFilePath(G,q);try{let J=await this.readStoredSessionMetadata(Z,q,G);if(J.projectPath!==G)return;if(!J.parentId||J.archivedAt)return this.toPublicMetadata(h0([J],null)[0]??J);let B=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(B.find((Q)=>Q.sessionId===q)??J)}catch(J){if(J.code==="ENOENT")return;throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((G)=>G.sessionId===q);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${q}`);return this.toPublicMetadata(T[0])}static async loadSession(q,$){try{if($){if(!X.isAbsolute($))throw Error("Session catalog cwd must be absolute");let G=X.resolve($),Z=this.getSessionFilePath(G,q);try{return await this.loadSessionFromFile(Z,q,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${q}`);throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===q);if(!T)throw Error(`未找到会话: ${q}`);return await this.loadSessionFromFile(T.filePath,q)}catch(T){throw u0.error(`[SessionService] 加载会话失败 (${q}):`,T),T}}static async exportSessionMarkdown(q,$,T={}){D(q);let G=this.resolveCatalogWorkspace($),Z=j(G,q),J;try{J=await this.readStableSessionSnapshot(Z,q)}catch(H){throw this.sanitizeStoredSessionError(H,q)}let B=this.projectMetadataFromEntries(J,q,G,Z);if(B.projectPath!==G)throw Error(`Session export workspace mismatch: ${q}`);let Q=B.archivedAt;if(!Q&&B.parentId)Q=(await this.findArchivedAncestor(B.parentId,G))?.archivedAt;return Mq(J,{...B,archivedAt:Q},T)}static async listRewindCheckpoints(q,$){D(q);let T=this.resolveCatalogWorkspace($),G=j(T,q),Z=await this.readStableSessionSnapshot(G,q);this.validateSessionWorkspace(Z,q,T);let J=new U0({sessionId:q,workspaceRoot:T});await J.initialize();let B=Iq(Z),Q=[];for(let H of B){let O=c0(Z,H.messageId),L=await J.previewRewind(O.snapshotMessageIds);Q.push({...H,fileCount:L.files.length})}return Q}static async rewindSession(q,$,T){D(q);let G=this.resolveCatalogWorkspace($);await this.assertSessionWritable(q,G);let Z=j(G,q),J=new m(Z),B;try{await J.appendValidatedAsync(async(Q)=>{this.validateSessionWorkspace(Q,q,G);let H=c0(Q,T.targetMessageId),O=new U0({sessionId:q,workspaceRoot:G});await O.initialize();let L=await O.previewRewind(H.snapshotMessageIds),V=T.mode==="conversation"?await O.commitSnapshots(H.snapshotMessageIds):await O.rewindSnapshots(H.snapshotMessageIds),Y=new Date().toISOString(),U={id:y(),sessionId:q,timestamp:Y,type:"session_rewound",cwd:G,gitBranch:l(G),version:c(),data:{rewindId:y(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:V.files,createdAt:Y}},b=P([...Q,U]);return B={checkpoint:{...H.checkpoint,fileCount:L.files.length},mode:T.mode,removedTurns:H.removedTurns,restoredFiles:U.data.restoredFiles,messages:this.convertJSONLToMessages(b)},U})}catch(Q){throw this.sanitizeStoredSessionError(Q,q)}if(!B)throw Error(`Session rewind did not produce a result: ${q}`);for(let Q of B.restoredFiles)h.getInstance().clearFileRecord(Q);return B}static async forkSession(q,$){D(q);let T=$.newSessionId??`fork-${Date.now()}-${y(8)}`;D(T);let G=this.resolveForkWorkspace($.sourceProjectPath),Z=this.resolveForkWorkspace($.targetProjectPath);if(G!==Z)throw Error("Session forks must stay in the source workspace");let J=j(G,q),B=await this.readStableSessionSnapshot(J,q),Q=this.getSessionCreatedEntry(B,q);if(Q.data.sessionId!==q)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!X.isAbsolute(Q.cwd)||X.resolve(Q.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let H=this.projectMetadataFromEntries(B,q,G,J);if(H.archivedAt)throw new e(q,q);if(H.parentId){let A=await this.findArchivedAncestor(H.parentId,G);if(A)throw new e(q,A.sessionId)}let O=P(B),L=new Date().toISOString(),V=Q.data.rootId||q,Y=l(Z),U=c(),{status:b,taskStatus:z,taskStatusReason:w,taskFailure:C,taskStartedAt:I,taskCompletedAt:o,taskOwnerPid:_,taskPromptSummary:u,taskDispatch:R,taskModelId:M,taskRetriedFrom:E,taskDelivery:N,taskIsolation:a,taskSourceProjectPath:D0,taskWorktree:t0,taskDiffStat:s0,taskQueuePosition:e0,taskQueueDepth:qq,taskConcurrencyLimit:$q,pendingInteraction:Tq,...R0}=Q.data,M0={id:y(),sessionId:T,timestamp:L,type:"session_created",cwd:Z,gitBranch:Y,version:U,data:{...R0,sessionId:T,rootId:V,parentId:q,relationType:"fork",taskStatus:"completed",taskCompletedAt:L,taskIsolation:"local",taskSourceProjectPath:Z,createdAt:L,updatedAt:L}},L0=O.filter((A)=>A.type!=="session_created"&&A.type!=="inbox_acknowledged"&&A.type!=="interaction_requested"&&A.type!=="interaction_responded"&&A.type!=="interaction_recovered").map((A)=>{let A0={...A,id:y(),sessionId:T,cwd:Z,gitBranch:Y,version:U};if(A.type==="session_updated"){let{status:iq,taskStatus:Jq,taskStatusReason:g$,taskFailure:y$,taskStartedAt:j$,taskCompletedAt:S$,taskOwnerPid:m$,taskPromptSummary:v$,taskDispatch:I$,taskModelId:u$,taskRetriedFrom:P$,taskDelivery:h$,taskIsolation:l$,taskSourceProjectPath:c$,taskWorktree:p$,taskDiffStat:n$,taskQueuePosition:i$,taskQueueDepth:d$,taskConcurrencyLimit:r$,pendingInteraction:o$,...dq}=A.data;return{...A0,type:"session_updated",data:{...dq,sessionId:T,rootId:V,parentId:q,relationType:"fork"}}}if(A.type==="message_created"){let{inboxMessageId:iq,...Jq}=A.data;return{...A0,type:"message_created",data:Jq}}return A0}),g={id:y(),sessionId:T,timestamp:L,type:"session_updated",cwd:Z,gitBranch:Y,version:U,data:{sessionId:T,rootId:V,parentId:q,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:L,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:Z,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:L}},t=[M0,...L0,g],Gq=j(Z,T);try{await new m(Gq).createExclusive(t)}catch(A){if(A.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:A});throw A}let nq=this.projectMetadataFromEntries(t,T,Z,Gq);return{sessionId:T,parentSessionId:q,projectPath:Z,messages:this.convertJSONLToMessages(t),metadata:this.toPublicMetadata(nq)}}static async deleteSession(q,$){if(D(q),$){if(!X.isAbsolute($))throw Error("Session catalog cwd must be absolute");let G=X.resolve($),Z=this.getSessionFilePath(G,q),J=new m(Z),B;try{B=await J.deleteValidated((Q)=>{return this.projectMetadataFromEntries(Q,q,G,Z).projectPath===G})}catch(Q){if(!this.isCorruptSessionJSONLError(Q))throw Q;B=await J.delete()}if(!B)return 0;return await _0(X.join(X.dirname(Z),`${q}.inbox.json`),{force:!0}),await _0(l0(G,q),{force:!0}),await this.removeFromProjection(q,G),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((G)=>G.sessionId===q);if(T.length===0)return 0;return await Promise.all(T.map(async(G)=>{await new m(G.filePath).delete(),await _0(X.join(X.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await _0(l0(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),T.length}static async removeFromProjection(q,$){try{let T=await C0();if(T)hq(T,q,$)}catch{}}static validateTaskMetadataUpdate(q,$){if(q.taskPromptSummary!==void 0&&q.taskPromptSummary!==null&&(!q.taskPromptSummary.trim()||q.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(q.taskFailure!==void 0&&q.taskFailure!==null&&!b0(q.taskFailure))throw Error("Invalid session task failure");if(q.taskDispatch!==void 0&&q.taskDispatch!==null&&!gq(q.taskDispatch))throw Error("Invalid durable task dispatch");if(q.taskModelId!==void 0&&q.taskModelId!==null&&(!q.taskModelId.trim()||q.taskModelId.length>500))throw Error("Invalid session task model ID");if(q.selectedModelId!==void 0&&q.selectedModelId!==null&&(!q.selectedModelId.trim()||q.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(q.permissionMode!==void 0&&q.permissionMode!==null&&!z0(q.permissionMode))throw Error("Invalid session permission mode");if(q.reasoningEffort!==void 0&&q.reasoningEffort!==null&&!B0(q.reasoningEffort))throw Error("Invalid session reasoning effort");if(q.serviceTier!==void 0&&q.serviceTier!==null&&!Q0(q.serviceTier))throw Error("Invalid session service tier");if(q.responseVerbosity!==void 0&&q.responseVerbosity!==null&&!Z0(q.responseVerbosity))throw Error("Invalid session response verbosity");if(q.communicationStyle!==void 0&&q.communicationStyle!==null&&!H0(q.communicationStyle))throw Error("Invalid session communication style");if(q.communicationStyleDigest!==void 0&&q.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))throw Error("Invalid session communication style digest");if(q.projectInstructionsDigest!==void 0&&q.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(q.taskRetriedFrom!==void 0&&q.taskRetriedFrom!==null&&!yq(q.taskRetriedFrom))throw Error("Invalid session task retry source");if(q.taskDelivery!==void 0&&q.taskDelivery!==null&&!kq(q.taskDelivery))throw Error("Invalid session task delivery");if(q.taskIsolation!==void 0&&q.taskIsolation!==null&&!o0.has(q.taskIsolation))throw Error(`Invalid session task isolation: ${String(q.taskIsolation)}`);if(q.taskSourceProjectPath!==void 0&&q.taskSourceProjectPath!==null&&!X.isAbsolute(q.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(q.taskWorktree!==void 0&&q.taskWorktree!==null){let T=bq(q.taskWorktree);if(!T||T.sessionId!==$||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((G)=>X.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if(q.taskDiffStat!==void 0&&q.taskDiffStat!==null&&!fq(q.taskDiffStat))throw Error("Invalid session task diff stat");if(q.taskQueuePosition!==void 0&&q.taskQueuePosition!==null&&(!Number.isInteger(q.taskQueuePosition)||q.taskQueuePosition<1))throw Error("Invalid session task queue position");if(q.taskQueueDepth!==void 0&&q.taskQueueDepth!==null&&(!Number.isInteger(q.taskQueueDepth)||q.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(q.taskConcurrencyLimit!==void 0&&q.taskConcurrencyLimit!==null&&(!Number.isInteger(q.taskConcurrencyLimit)||q.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof q.taskQueuePosition==="number"&&typeof q.taskQueueDepth==="number"&&q.taskQueuePosition>q.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(q,$,T={}){D(q),F.validateTaskMetadataUpdate(T,q);let G=F.resolveCatalogWorkspace($);if(T.taskWorktree&&X.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=new Date().toISOString(),J={id:y(),sessionId:q,timestamp:Z,type:"session_created",cwd:G,gitBranch:l(G),version:c(),data:{sessionId:q,rootId:q,...T.title!==void 0?{title:T.title}:{},taskStatus:T.taskStatus??"queued",...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},createdAt:Z,updatedAt:Z}},B=F.getSessionFilePath(G,q);return await new m(B).createExclusive([J]),F.toPublicMetadata(F.projectMetadataFromEntries([J],q,G,B))}static async assertSessionWritable(q,$){let T=await this.findSessionMetadata(q,$);if(!T)throw Error(`Session not found: ${q}`);if(T.archivedAt)throw new e(q,T.archivedBySessionId??q);return T}static async findArchivedAncestor(q,$){let T=new Set,G=q;while(G){if(T.has(G))throw Error("Session lineage contains a cycle");T.add(G),D(G);let Z=j($,G),J;try{J=await s(Z,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let B=this.projectMetadataFromEntries(this.parseStoredSession(J,G),G,$,Z);if(B.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(B.archivedAt)return{sessionId:B.sessionId,archivedAt:B.archivedAt};G=B.parentId}return}static async listSessionArchiveMembers(q,$){D(q);let T=this.resolveCatalogWorkspace($),G=await this.scanStoredSessions(T,!0,0,null);if(!G.some((B)=>B.sessionId===q))throw Error(`Session not found: ${q}`);let Z=new Set([q]),J=!0;while(J){J=!1;for(let B of G)if(B.parentId&&Z.has(B.parentId)&&!Z.has(B.sessionId))Z.add(B.sessionId),J=!0}return G.filter((B)=>Z.has(B.sessionId)).sort((B,Q)=>B.sessionId.localeCompare(Q.sessionId)).map((B)=>this.toPublicMetadata(B))}static async archiveSession(q,$){D(q);let T=this.resolveCatalogWorkspace($),G=await this.findSessionMetadata(q,T);if(!G)throw Error(`Session not found: ${q}`);if(G.archivedAt)return G;let Z=await this.listSessionArchiveMembers(q,T),J=Z.find((Q)=>Q.taskStatus==="queued"||Q.taskStatus==="running");if(J)throw new v(`Stop session ${J.sessionId} before archiving this session tree`);let B=[];try{for(let L of Z)B.push(await n.acquire(L.sessionId,T));let Q=j(T,q),H=new m(Q),O=[];return await H.appendValidated((L)=>{let V=this.projectMetadataFromEntries(L,q,T,Q);if(V.archivedAt)throw new v(`Session archive state changed concurrently: ${q}`);if(V.taskStatus==="queued"||V.taskStatus==="running")throw new v(`Stop session ${q} before archiving it`);let Y=new Date().toISOString(),U={id:y(),sessionId:q,timestamp:Y,type:"session_updated",cwd:T,gitBranch:l(T),version:c(),data:{sessionId:q,archivedAt:Y,updatedAt:Y}};return O=[...L,U],U}),this.toPublicMetadata({...this.projectMetadataFromEntries(O,q,T,Q),archivedBySessionId:q})}catch(Q){if(Q instanceof v)throw Q;if(Q instanceof p)throw new v(Q.message);throw this.sanitizeStoredSessionError(Q,q)}finally{for(let Q of B.reverse())await Q.release()}}static async unarchiveSession(q,$){D(q);let T=this.resolveCatalogWorkspace($),G=await this.findSessionMetadata(q,T);if(!G)throw Error(`Session not found: ${q}`);if(!G.archivedAt)return G;if(G.archivedBySessionId&&G.archivedBySessionId!==q)throw new v(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${q}`);let Z;try{Z=await n.acquire(q,T);let J=j(T,q),B=new m(J),Q=[];return await B.appendValidated((H)=>{if(!this.projectMetadataFromEntries(H,q,T,J).archivedAt)throw new v(`Session archive state changed concurrently: ${q}`);let L=new Date().toISOString(),V={id:y(),sessionId:q,timestamp:L,type:"session_updated",cwd:T,gitBranch:l(T),version:c(),data:{sessionId:q,archivedAt:null,updatedAt:L}};return Q=[...H,V],V}),this.toPublicMetadata(this.projectMetadataFromEntries(Q,q,T,J))}catch(J){if(J instanceof v)throw J;if(J instanceof p)throw new v(J.message);throw this.sanitizeStoredSessionError(J,q)}finally{await Z?.release()}}static async updateSessionMetadata(q,$,T){if(D(q),F.validateTaskMetadataUpdate(T,q),T.taskStatus!==void 0&&!Eq.has(T.taskStatus))throw Error(`Invalid session task status: ${String(T.taskStatus)}`);if(T.taskOwnerPid!==void 0&&T.taskOwnerPid!==null&&(!Number.isInteger(T.taskOwnerPid)||T.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let G=F.resolveCatalogWorkspace($);if(T.taskWorktree&&X.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=F.getSessionFilePath(G,q),J=new m(Z),B=[];try{await J.appendValidatedAsync(async(Q)=>{let H=F.getSessionCreatedEntry(Q,q);if(H.data.sessionId!==q)throw Error(`Session metadata creation record sessionId mismatch: ${q}`);if(!X.isAbsolute(H.cwd)||X.resolve(H.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${q}`);let O=F.projectMetadataFromEntries(Q,q,G,Z);if(O.archivedAt)throw new e(q,q);if(O.parentId){let Y=await F.findArchivedAncestor(O.parentId,G);if(Y)throw new e(q,Y.sessionId)}let L=new Date().toISOString(),V={id:y(),sessionId:q,timestamp:L,type:"session_updated",cwd:G,gitBranch:l(G),version:c(),data:{sessionId:q,...T.title!==void 0?{title:T.title}:{},...T.taskStatus!==void 0?{taskStatus:T.taskStatus}:{},...T.taskStatusReason!==void 0?{taskStatusReason:T.taskStatusReason}:{},...T.taskFailure!==void 0?{taskFailure:T.taskFailure}:{},...T.taskStartedAt!==void 0?{taskStartedAt:T.taskStartedAt}:{},...T.taskCompletedAt!==void 0?{taskCompletedAt:T.taskCompletedAt}:{},...T.taskOwnerPid!==void 0?{taskOwnerPid:T.taskOwnerPid}:{},...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskDelivery!==void 0?{taskDelivery:T.taskDelivery}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.taskDiffStat!==void 0?{taskDiffStat:T.taskDiffStat}:{},...T.taskQueuePosition!==void 0?{taskQueuePosition:T.taskQueuePosition}:{},...T.taskQueueDepth!==void 0?{taskQueueDepth:T.taskQueueDepth}:{},...T.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:T.taskConcurrencyLimit}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},updatedAt:L}};return B=[...Q,V],V})}catch(Q){throw F.sanitizeStoredSessionError(Q,q)}return F.toPublicMetadata(F.projectMetadataFromEntries(B,q,G,Z))}static async setSessionPermissionMode(q,$,T){if(D(q),!z0(T))throw Error("Invalid session permission mode");let G=F.resolveCatalogWorkspace($),Z=await F.findSessionMetadata(q,G);if(Z?.permissionMode===T)return Z;if(Z)return F.updateSessionMetadata(q,G,{permissionMode:T});try{return await F.createSessionMetadata(q,G,{taskStatus:"completed",permissionMode:T})}catch(J){if(J.code!=="EEXIST")throw J;return F.updateSessionMetadata(q,G,{permissionMode:T})}}static async findSessionTaskWorktree(q,$){D(q);let T=F.resolveCatalogWorkspace($),G=F.getSessionFilePath(T,q);try{return(await F.readStoredSessionMetadata(G,q,T)).taskWorktree}catch(Z){if(Z.code==="ENOENT")return;throw F.sanitizeStoredSessionError(Z,q)}}static async findSessionTaskDispatch(q,$){D(q);let T=F.resolveCatalogWorkspace($),G=F.getSessionFilePath(T,q);try{return(await F.readStoredSessionMetadata(G,q,T)).taskDispatch}catch(Z){if(Z.code==="ENOENT")return;throw F.sanitizeStoredSessionError(Z,q)}}static async loadSessionFromFile(q,$,T){let G=await s(q,"utf-8"),Z=this.parseStoredSession(G,$);if(T!==void 0){if(this.projectMetadataFromEntries(Z,$,T,q).projectPath!==T)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(Z)}static convertJSONLToMessages(q){let $=[],T=new Map,G=new Map,Z=new Map,J=new Map,B=new Map;for(let Q of P(q)){if(Q.type==="message_created"){let H=Q.data.role==="assistant"&&Q.data.parentMessageId?Z.get(Q.data.parentMessageId):void 0,O=H??{role:Q.data.role,content:"",...Q.data.metadata||Q.data.inboxMessageId?{metadata:{...Q.data.metadata&&typeof Q.data.metadata==="object"&&!Array.isArray(Q.data.metadata)?Q.data.metadata:{},...Q.data.inboxMessageId?{inboxMessageId:Q.data.inboxMessageId}:{}}}:{}};if(T.set(Q.data.messageId,O),G.set(Q.data.messageId,[]),!H)$.push(O)}if(Q.type==="part_created"){if(Q.data.partType==="reasoning"){let H=T.get(Q.data.messageId);if(H){let O=Q.data.payload;H.reasoningContent=(H.reasoningContent??"")+(O.text??"")}}if(Q.data.partType==="text"){let H=T.get(Q.data.messageId);if(H){let O=Q.data.payload,L=G.get(Q.data.messageId);if(L)L.push({type:"text",text:O.text??""}),H.content=jq(L);else H.content=O.text??""}}if(Q.data.partType==="image"){let H=T.get(Q.data.messageId);if(H){let O=Q.data.payload,L=G.get(Q.data.messageId);if(L&&O.dataUrl)L.push({type:"image_url",image_url:{url:O.dataUrl}}),H.content=jq(L)}}if(Q.data.partType==="tool_call"){let H=T.get(Q.data.messageId);if(H?.role!=="assistant"){if(H=Z.get(Q.data.messageId),!H)H={role:"assistant",content:"",tool_calls:[]},Z.set(Q.data.messageId,H),$.push(H)}if(H.role==="assistant"){let O=Q.data.payload,L=O.toolCallId??Q.data.partId;J.set(Q.data.partId,L),B.set(L,H),H.tool_calls??=[],H.tool_calls.push({id:L,type:"function",function:{name:O.toolName??"unknown",arguments:JSON.stringify(O.input??{})}})}}if(Q.data.partType==="tool_result"){let H=Q.data.payload,O=typeof H.error==="string"?`Error: ${H.error}`:typeof H.output==="string"?H.output:JSON.stringify(H.output??""),L=H;$.push({role:"tool",content:O,tool_call_id:J.get(Q.data.messageId)??H.toolCallId,name:H.toolName,metadata:L})}if(Q.data.partType==="summary"){let H=Q.data.payload,O=Q.data.payload;$.push({role:"system",content:H.text??"",metadata:O})}if(Q.data.partType==="subtask_ref"){let H=T.get(Q.data.messageId)??B.get(Q.data.messageId);if(H){let O=Q.data.payload,L=H.metadata??{};H.metadata={...L,subtaskRef:O}}}}}return $}static projectionDeriver(){return(q,$,T)=>{try{let G=j(T,$);return this.projectMetadataFromEntries(q,$,T,G)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(q,$,T=0,G=!1){try{let Z=await C0();if(!Z)return null;await r0(Z,this.projectionDeriver(),T);let J=q?Z.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all(q):Z.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),B=[];for(let Q of J){if(!$&&Q.is_subagent===1)continue;try{let H=JSON.parse(Q.metadata_json);if(q!==void 0&&H.projectPath!==q)continue;B.push(H)}catch{}}return h0(B,G)}catch{return null}}static async scanStoredSessions(q,$=!1,T=0,G=!1){let Z=q?X.resolve(q):void 0,J=await this.scanStoredSessionsFromProjection(Z,$,T,G);if(J)return J;let B=Z?[{storagePath:V0(Z),projectPath:Z}]:await this.listAllProjectStorageDirectories(),Q=[];for(let H of B){let O;try{O=await Aq(H.storagePath)}catch(L){if(L.code==="ENOENT")continue;throw L}for(let L of O){if(!L.endsWith(".jsonl"))continue;let V=L.slice(0,-6),Y=X.join(H.storagePath,L);try{let U=await this.readStoredSessionMetadata(Y,V,H.projectPath);if(Z!==void 0&&U.projectPath!==Z){u0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!$&&U.relationType==="subagent")continue;Q.push(U)}catch(U){let b=U.code;if(b==="ENOENT")continue;if(b)throw U;u0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return h0(Q,G)}static async listAllProjectStorageDirectories(){let q=X.join(G0(),"projects"),$;try{$=await Aq(q,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return $.filter((T)=>T.isDirectory()).map((T)=>({storagePath:X.join(q,T.name),projectPath:Sq(T.name)}))}static async readStoredSessionMetadata(q,$,T){let G=await s(q,"utf-8"),Z=this.parseStoredSession(G,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(Z,$,T,q))}static async reconcileInterruptedTask(q){let $=q.taskOwnerPid;if(q.taskStatus!=="running"||$===void 0||wq($))return q;let T;try{T=await n.acquire(q.sessionId,q.projectPath)}catch(J){if(!(J instanceof p))throw J;let B=await s(q.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(B,q.sessionId),q.sessionId,q.projectPath,q.filePath)}let G=new m(q.filePath),Z;try{try{await G.appendValidated((J)=>{let B=this.projectMetadataFromEntries(J,q.sessionId,q.projectPath,q.filePath);if(B.taskStatus!=="running"||B.taskOwnerPid!==$||wq($))throw new a0;let Q=new Date().toISOString(),H={id:y(),sessionId:q.sessionId,timestamp:Q,type:"session_updated",cwd:q.projectPath,gitBranch:l(q.projectPath),version:c(),data:{sessionId:q.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Q,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Q}};return Z=[...J,H],H})}catch(J){if(!(J instanceof a0))throw J}if(!Z){let J=await s(q.filePath,"utf-8");Z=this.parseStoredSession(J,q.sessionId)}return this.projectMetadataFromEntries(Z,q.sessionId,q.projectPath,q.filePath)}finally{await T.release()}}static projectMetadataFromEntries(q,$,T,G){if(q.length===0)throw Error(`Empty session transcript: ${$}`);let Z=this.getSessionCreatedEntry(q,$),J=q.reduce((g,t)=>t.type==="session_updated"?{...g,...t.data}:g,{...Z.data}),B=P(q),Q=Vq(Oq(B)),H=B.filter((g)=>g.type==="message_created"&&["user","assistant"].includes(g.data.role)).length,O=B.some((g)=>g.type==="part_created"&&g.data.partType==="tool_result"&&typeof g.data.payload.error==="string"),V=(Eq.has(J.taskStatus)?J.taskStatus:void 0)??(O?"failed":"completed"),Y=typeof J.taskOwnerPid==="number"&&Number.isInteger(J.taskOwnerPid)&&J.taskOwnerPid>0?J.taskOwnerPid:void 0,U=o0.has(J.taskIsolation)?J.taskIsolation:void 0,b=typeof J.taskSourceProjectPath==="string"&&X.isAbsolute(J.taskSourceProjectPath)?X.resolve(J.taskSourceProjectPath):void 0,z=Z.cwd;if(z!==void 0&&!X.isAbsolute(z))throw Error(`Session catalog cwd must be absolute: ${$}`);let w=z===void 0?T:X.resolve(z),C=bq(J.taskWorktree),I=C?.sessionId===$&&X.resolve(C.workspaceRoot)===w?C:void 0,o=fq(J.taskDiffStat),_=gq(J.taskDispatch),u=typeof J.taskModelId==="string"&&J.taskModelId.trim()?J.taskModelId:_?.modelId,R=typeof J.selectedModelId==="string"&&J.selectedModelId.trim()?J.selectedModelId:u,M=z0(J.permissionMode)?J.permissionMode:_?.permissionMode,E=B0(J.reasoningEffort)?J.reasoningEffort:_?.reasoningEffort,N=Q0(J.serviceTier)?J.serviceTier:_?.serviceTier,a=Z0(J.responseVerbosity)?J.responseVerbosity:_?.responseVerbosity,D0=H0(J.communicationStyle)?J.communicationStyle:_?.communicationStyle,t0=Object.hasOwn(J,"communicationStyleDigest")?typeof J.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(J.communicationStyleDigest)?J.communicationStyleDigest:void 0:D0===_?.communicationStyle?_?.communicationStyleDigest:void 0,s0=Object.hasOwn(J,"projectInstructionsDigest")?typeof J.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(J.projectInstructionsDigest)?J.projectInstructionsDigest:void 0:_?.projectInstructionsDigest,e0=pq(J.archivedAt)?J.archivedAt:void 0,qq=yq(J.taskRetriedFrom),$q=kq(J.taskDelivery),Tq=typeof J.taskQueuePosition==="number"&&Number.isInteger(J.taskQueuePosition)&&J.taskQueuePosition>0?J.taskQueuePosition:void 0,R0=typeof J.taskQueueDepth==="number"&&Number.isInteger(J.taskQueueDepth)&&J.taskQueueDepth>=0?J.taskQueueDepth:void 0,M0=typeof J.taskConcurrencyLimit==="number"&&Number.isInteger(J.taskConcurrencyLimit)&&J.taskConcurrencyLimit>0?J.taskConcurrencyLimit:void 0,L0=b0(J.taskFailure)?J.taskFailure:V==="failed"&&typeof J.taskStatusReason==="string"?Xq(J.taskStatusReason):void 0;return{sessionId:$,projectPath:w,gitBranch:Z.gitBranch,rootId:J.rootId||$,parentId:J.parentId,relationType:J.relationType,resumedFrom:J.resumedFrom,rootAgentId:J.rootAgentId,resumeDepth:J.resumeDepth,title:J.title,agentType:J.agentType,model:J.model,selectedModelId:R,permissionMode:M,reasoningEffort:E,serviceTier:N,responseVerbosity:a,communicationStyle:D0,communicationStyleDigest:t0,projectInstructionsDigest:s0,pendingInteraction:Q,taskStatus:V,taskStatusReason:L0?.message??(typeof J.taskStatusReason==="string"?J.taskStatusReason:void 0),taskFailure:L0,taskStartedAt:typeof J.taskStartedAt==="string"?J.taskStartedAt:void 0,taskCompletedAt:typeof J.taskCompletedAt==="string"?J.taskCompletedAt:void 0,taskPromptSummary:typeof J.taskPromptSummary==="string"?J.taskPromptSummary:void 0,taskModelId:u,taskRetryAvailable:_!==void 0,taskRetriedFrom:qq,taskDelivery:$q,taskIsolation:U,taskSourceProjectPath:b,taskWorktreePath:I?.worktreeRoot,taskWorktreeBranch:I?.branch,taskBaseCommit:I?.baseCommit,taskDiffStat:o,taskQueuePosition:Tq,taskQueueDepth:R0,taskConcurrencyLimit:M0,archivedAt:e0,taskOwnerPid:Y,taskWorktree:I,taskDispatch:_,messageCount:H,firstMessageTime:q[0].timestamp,lastMessageTime:q.at(-1).timestamp,hasErrors:O||V==="failed",filePath:G}}static toPublicMetadata(q){let{filePath:$,taskOwnerPid:T,taskWorktree:G,taskDispatch:Z,...J}=q;return J}static getSessionFilePath(q,$){return j(q,$)}static getSessionCreatedEntry(q,$){let T=q.find((G)=>G.type==="session_created");if(!T)throw new cq($);return T}static resolveCatalogWorkspace(q){if(!X.isAbsolute(q))throw Error("Session catalog cwd must be absolute");return X.resolve(q)}static validateSessionWorkspace(q,$,T){let G=this.getSessionCreatedEntry(q,$);if(G.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!X.isAbsolute(G.cwd)||X.resolve(G.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(q){if(!X.isAbsolute(q))throw Error("Fork workspace paths must be absolute");return X.resolve(q)}static parseStoredSession(q,$){return uq(q,`session ${$}`)}static isCorruptSessionJSONLError(q){return q instanceof Error&&q.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(q,$){if(!this.isCorruptSessionJSONLError(q)||!(q instanceof Error))return q;let T=q.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${T?` at line ${T}`:""}`,{cause:q.cause})}static async readStableSessionSnapshot(q,$,T=3){for(let G=0;G<T;G+=1){let Z=await J0.stat(q),J=await J0.readFile(q),B=this.parseStoredSession(J,$),Q=await J0.stat(q);if(Z.size===Q.size&&Z.mtimeNs===Q.mtimeNs&&Z.dev===Q.dev&&Z.ino===Q.ino)return B}throw Error("Session changed while creating fork; retry the operation")}}function jq(q){if(q.length===1&&q[0]?.type==="text")return q[0].text;return[...q]}
99
+ export{k0 as bb,p as cb,n as db,Oq as eb,$T as fb,Xq as gb,h as hb,U0 as ib,g0 as jb,y0 as kb,_T as lb,CT as mb,Cq as nb,x0 as ob,ET as pb,aT as qb,tT as rb,cq as sb,e as tb,v as ub,F as vb};
@@ -0,0 +1,10 @@
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-wa7v7akz.js";import"./chunk-rw6gv740.js";import"./chunk-w154jyby.js";import"./chunk-76d7p64v.js";import"./chunk-1cvr3qtd.js";import"./chunk-g9n211y4.js";import"./chunk-jqyvnmfr.js";import"./chunk-sf9pe2n6.js";import"./chunk-47dsd91k.js";import"./chunk-k0p9ecgc.js";import"./chunk-g4q26d9a.js";import{pc as M}from"./chunk-r083b7vn.js";import"./chunk-yt39kfc6.js";import"./chunk-bnrce0hg.js";import"./chunk-w4zvftrw.js";import"./chunk-hjsm6ejs.js";import"./chunk-b4n34hrn.js";import"./chunk-v1p80wvh.js";import"./chunk-m4htdpr9.js";import"./chunk-4y28hykg.js";import"./chunk-kcwq1e7h.js";import"./chunk-thvwt4kc.js";import"./chunk-p4j4aawd.js";import"./chunk-6cv4gddv.js";import"./chunk-0rp2ck29.js";import"./chunk-xkp4ph6v.js";import"./chunk-1kg9r8xp.js";import"./chunk-c9tzf9r5.js";import"./chunk-n9khyme2.js";import"./chunk-7xm3vjkz.js";import{Je as J}from"./chunk-nfmsn652.js";import"./chunk-kcs3xa8f.js";import"./chunk-vvbd9fb5.js";import"./chunk-frcg8gea.js";import"./chunk-c2rhwxyn.js";import b from"chalk";import H from"open";var $=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await M(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${J()}
9
+ `)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
10
+ `)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as ad,z as bd,H as cd,W as dd,Z as ed};
18
+ export{R as fd,z as gd,H as hd,W as id,Z as jd};
@@ -0,0 +1,22 @@
1
+ import{q as t}from"./chunk-76d7p64v.js";import{D as k,F as S,G as C,I as f,W as u,X as g,Y as c,Z as v,t as K}from"./chunk-1cvr3qtd.js";import{ha as o}from"./chunk-g9n211y4.js";import{Ca as I,Na as M,za as y}from"./chunk-jqyvnmfr.js";import{Ya as A}from"./chunk-sf9pe2n6.js";import{nb as E,ob as T,sb as V,vb as L}from"./chunk-47dsd91k.js";import"./chunk-k0p9ecgc.js";import"./chunk-g4q26d9a.js";import"./chunk-r083b7vn.js";import"./chunk-yt39kfc6.js";import{Bc as r}from"./chunk-bnrce0hg.js";import"./chunk-w4zvftrw.js";import"./chunk-hjsm6ejs.js";import{Kc as a}from"./chunk-b4n34hrn.js";import"./chunk-v1p80wvh.js";import"./chunk-m4htdpr9.js";import{fd as n}from"./chunk-4y28hykg.js";import"./chunk-kcwq1e7h.js";import"./chunk-thvwt4kc.js";import"./chunk-p4j4aawd.js";import{sd as R}from"./chunk-6cv4gddv.js";import"./chunk-0rp2ck29.js";import"./chunk-xkp4ph6v.js";import{qe as N,re as x,se as P}from"./chunk-1kg9r8xp.js";import{we as d}from"./chunk-c9tzf9r5.js";import"./chunk-n9khyme2.js";import{Ce as l,Fe as i}from"./chunk-7xm3vjkz.js";import"./chunk-nfmsn652.js";import"./chunk-kcs3xa8f.js";import"./chunk-vvbd9fb5.js";import"./chunk-frcg8gea.js";import"./chunk-c2rhwxyn.js";import{Readable as WJ,Writable as YJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as zJ}from"@agentclientprotocol/sdk";import m from"node:path";import{nanoid as q}from"nanoid";var X=R("Agent");function h(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function JJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:h(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:h("headers"in J?J.headers:void 0)};return null}function QJ(J){let Z={};for(let Q of J){let Y=JJ(Q);if(Y)Z[Q.name]=Y}return Z}function p(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,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function ZJ(J){let Z=T(J.metadata);return Z?[{type:"text",text:E(Z)}]:p(J.content)}function $J(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class _{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,Y,z={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=z;this.messages=[...z.initialMessages??[]],this.mode=this.mapPermissionModeToMode(z.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 f.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(X.debug(`[AcpSession ${this.id}] Initializing...`),await L.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),K.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),await M.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await L.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Q=K.getInstance().getTerminalService(this.id);this.runtime=await k.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,D)=>{let $=await Q.execute(z,{cwd:D.cwd,env:D.env,timeout:D.timeoutMs,signal:D.signal,allowLocalFallback:!1,onOutput:(W)=>D.onOutput?.("stdout",W)});return{exitCode:$.exitCode,stdout:$.stdout,stderr:$.stderr,...$.error?{error:$.error}:{},timedOut:$.error==="Command timed out",aborted:$.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.agent=await this.createAgent(),await g(this.cwd),X.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=I.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 Y=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Y?.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 ZJ(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);X.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{X.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 W=await this.runtime.rewindSession($);return this.messages=[...W.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),W}},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($,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let H=!1,F,j=(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}`}}]})},G=this.runtime.resumeSubagent({agentId:$,prompt:W,onCompleted:(B)=>{if(H)j(B);else F=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),H=!0,F)j(F);return G}},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($,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,W,H)},complete:async($,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,W,H)},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($,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,W)},getLogs:async($,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,W)},setLoggingLevel:async($,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,W,H)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(H);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:($,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await c(J,Q),z=Y.data?.action;if(z==="start_goal"||z==="resume_goal")this.schedulePendingResume();if(z==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages];if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages)this.messages=[...Y.data.compactedMessages];let D=Y.content||Y.message;if(D)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:D}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return X.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=v(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((z)=>!Z.includes(z.name)).map((z)=>{let D;if(z.usage){let $=z.usage.replace(/^\/\w+\s*/,"").trim();if($)D=$}if(z.aliases?.length){let $=`Aliases: ${z.aliases.join(", ")}`;D=D?`${D} | ${$}`:$}return{name:z.name,description:z.description,input:D?{hint:D}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((z)=>z.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),X.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(K.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,z=Q.displayText;if(z.trimStart().startsWith("!"))return this.handleUserShellCommand(z);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(z.trim()))return this.handleSlashCommand(z,this.pendingPrompt.signal);let $=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!$.accepted)throw Error($.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(X.debug(`[AcpSession ${this.id}] Queued steering for active turn (${$.queued})`),$.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController;this.pendingPrompt=D;try{if(X.debug(`[AcpSession ${this.id}] Received prompt: ${z.slice(0,100)}...`),u(z))return await this.handleSlashCommand(z,D.signal);let $={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}};if(await y(this.agent.chatStream(Y,$,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly}),async(W)=>{switch(W.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let H=W.toolCall,F=H.function.name,j=this.mapToolKind(W.toolKind),G=`Executing ${F}`;if(F==="Task"&&"function"in H)try{let B=JSON.parse(H.function.arguments),U=B.resume_from??B.resume;if(typeof U==="string")G=`Resuming ${String(B.subagent_type||"subagent")} from ${U}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:H.id,status:"in_progress",title:G,content:[],kind:j});break}case"tool_progress":{let H=W.toolCall;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let{toolCall:H,result:F}=W,j=[],G=F.metadata;if(G?.kind==="patch"&&Array.isArray(G.changes))for(let U of G.changes){if(!U||typeof U!=="object"||!("path"in U)||typeof U.path!=="string")continue;j.push({type:"diff",path:U.path,oldText:"oldContent"in U&&typeof U.oldContent==="string"?U.oldContent:null,newText:"newContent"in U&&typeof U.newContent==="string"?U.newContent:null})}else if(G?.kind==="edit"&&typeof G.file_path==="string"&&typeof G.oldContent==="string"&&(typeof G.newContent==="string"||G.newContent===void 0))j.push({type:"diff",path:G.file_path,oldText:G.oldContent,newText:G.newContent??null});else{let U=H.function.name,s=C(S(U,F));j.push({type:"content",content:{type:"text",text:s}})}if(H.function.name==="Task"&&(G?.verificationVerdict==="pass"||G?.verificationVerdict==="fail"||G?.verificationVerdict==="partial"))j.unshift({type:"content",content:{type:"text",text:`Verification result: ${G.verificationVerdict.toUpperCase()}`}});let B=F.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:B,content:j});break}case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
+ `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
+ `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
5
+ `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
6
+ `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
7
+ `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
8
+ `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
9
+ `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
10
+ `}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let H of W.messages){if(!H.recovered||H.persisted)continue;for(let F of p(H.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:F})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
11
+ `}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
12
+ `}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...$.messages],D.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch($){if(D.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,$),$}finally{if(this.pendingPrompt===D){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 Y,z="";try{let D=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(Y=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){z+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let W=E($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:z?$J($.record):W}}]})}});if(this.messages.push({role:"user",content:D.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(D.record))}}),D.delivery==="next_turn")this.schedulePendingResume();return{stopReason:D.record.status==="aborted"?"cancelled":"end_turn"}}catch(D){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:D instanceof Error?D.message:String(D)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw D}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((Y)=>{X.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){X.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)X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await L.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,X.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(X.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 V)&&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((Y)=>{X.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});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 V)&&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 V)&&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 V)&&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(Y){if(!(Y instanceof V)&&Y.code!=="ENOENT")throw Y;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(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}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,Y=async(z)=>{try{await z()}catch(D){Q??=D}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>K.destroySession(this.id)),X.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,z=0,D=0,$=(H)=>{if(Q.length>0)Q.push({type:"text",text:`
13
+ `}),D+=1;if(Q.push(H),H.type==="text")D+=H.text.length};for(let H of J)if(H.type==="text")Z.push(H.text),$({type:"text",text:H.text});else if(H.type==="image"){let F=`data:${H.mimeType};base64,${H.data}`;Y+=1,z+=F.length,Z.push(`[Image: ${H.mimeType}]`),$({type:"image_url",image_url:{url:F}})}else if(H.type==="resource"){let F=H.resource;if("text"in F){let j=`<file path="${F.uri}">
14
+ ${F.text}
15
+ </file>`;Z.push(j),$({type:"text",text:j})}}else if(H.type==="resource_link"){let F=`[Resource: ${H.uri}]`;Z.push(F),$({type:"text",text:F})}if(Y>N)throw Error(`ACP prompt contains more than ${N} images`);if(z>x)throw Error("ACP prompt images exceed the 5 MiB limit");if(D>P)throw Error(`ACP prompt text exceeds ${P} characters`);let W=Z.join(`
16
+ `);return{content:Y>0?Q:W,displayText:W}}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)=>{X.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}));X.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 X.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=q(),z=[];if(J.message)z.push({type:"content",content:{type:"text",text:J.message}});if(J.details)z.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)z.push({type:"content",content:{type:"text",text:`Risks:
17
+ - ${J.risks.join(`
18
+ - `)}`}});let D=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:Y,status:"pending",title:J.title||"Permission Required",content:z,kind:D}},W=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!W)return{approved:!1,reason:A};let H=W.outcome;if(H.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let F=H.optionId;if(F==="allow_always")return{approved:!0,scope:"project"};if(F==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let j=F==="allow_once";return{approved:j,scope:"once",reason:j?void 0:"User denied the operation"}}catch(Y){return X.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{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((z)=>z.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[z,D]of Q.entries()){let $=D.options.map((j,G)=>`answer:${z}:${G}`),W=`answer:${z}:cancel`,H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...D.options.map((j,G)=>({optionId:$[G],name:j.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:q(),status:"pending",title:D.header,kind:"think",content:[{type:"content",content:{type:"text",text:[D.question,...D.options.map((j)=>`${j.label}: ${j.description}`)].join(`
19
+ `)}}]}}),Z);if(!H)return{approved:!1,reason:A};if(H.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let F=$.indexOf(H.outcome.optionId);if(F<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[D.header]=D.options[F].label}return{approved:!0,answers:Y}}catch(z){return X.warn(`[AcpSession ${this.id}] Question request failed:`,z),{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 z=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(z==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:z==="decline"?"User declined URL":"User cancelled",elicitation:{action:z==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let z of Q.fields??[]){let D=await this.collectAcpElicitationField(z,Z);if(D.cancelled)return{approved:!1,reason:D.reason,elicitation:{action:"cancel"}};if(D.value!==void 0)Y[z.name]=D.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return X.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{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((D,$)=>({id:`option:${$}`,label:D.label,value:D.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
+ `),[...Q.map((D)=>({id:D.id,label:D.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let z=Q.find((D)=>D.id===Y);if(!z)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:z.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,Y){let z=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((D)=>({optionId:D.id,name:D.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:q(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return z?.outcome.outcome==="selected"?z.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let z=!1,D=(W)=>{if(z)return;z=!0,Z.removeEventListener("abort",$),W()},$=()=>D(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((W)=>D(()=>Q(W)),(W)=>D(()=>Y(W)))})}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 w=R("Agent");class b{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return w.info("[BladeAgent] Initializing ACP connection"),w.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:zJ,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=r("acp"),Q=J.cwd||d(),Y=J._meta?.["blade/taskIsolation"],z=Y==="local"||Y==="worktree"?Y:void 0,D=J._meta?.["blade/taskPrompt"],$=z?await t.createSessionTask({sessionId:Z,prompt:typeof D==="string"&&D.trim()?D:"ACP task session",sourceProjectPath:Q,isolation:z}):void 0,W=$?.metadata.projectPath??Q;w.info(`[BladeAgent] Creating new session: ${Z}`),w.debug(`[BladeAgent] Session cwd: ${W}`);let H=new _(Z,W,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await H.initialize(),this.assertNotDestroyed()}catch(F){throw await H.destroy().catch(()=>{return}),F}return this.sessions.set(Z,H),w.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,H.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!m.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(),!m.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 _(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(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),w.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)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,Y]=await Promise.all([L.loadSession(J.sessionId,J.cwd),L.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let z=new _(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await z.initialize(),await z.replayHistory(),this.assertNotDestroyed()}catch(D){throw await z.destroy().catch(()=>{return}),D}return this.sessions.set(J.sessionId,z),z.sendAvailableCommandsDelayed(),this.buildSessionSetup(z.getModelConfiguration(),z.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??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,z=[{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"}],D=[];if(Q.length>0)D.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)D.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)D.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)D.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)D.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:z,currentModeId:Z},configOptions:D.length>0?D: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){w.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)w.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else w.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){w.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")w.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&a(J.value))w.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&i(J.value))w.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&l(J.value))w.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&n(J.value))w.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 o.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function cJ(){let J=YJ.toWeb(process.stdout),Z=WJ.toWeb(process.stdin),Q=O.ndJsonStream(J,Z);await new O.AgentSideConnection((z)=>new b(z),Q).closed}export{cJ as runAcpIntegration};
@@ -0,0 +1 @@
1
+ import{Qb as a,Rb as b,Sb as c}from"./chunk-9sfmrb1j.js";import"./chunk-45dcfkwe.js";import"./chunk-r083b7vn.js";import"./chunk-yt39kfc6.js";import"./chunk-bnrce0hg.js";import"./chunk-kcwq1e7h.js";import"./chunk-6cv4gddv.js";import"./chunk-0rp2ck29.js";import"./chunk-xkp4ph6v.js";import"./chunk-1kg9r8xp.js";import"./chunk-c9tzf9r5.js";import"./chunk-n9khyme2.js";import"./chunk-7xm3vjkz.js";import"./chunk-nfmsn652.js";import"./chunk-kcs3xa8f.js";import"./chunk-vvbd9fb5.js";import"./chunk-frcg8gea.js";import"./chunk-c2rhwxyn.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,3 +1,3 @@
1
- import{Te as j}from"./chunk-0n97186m.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{Ye as j}from"./chunk-frcg8gea.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
- export{m as kd,I as ld,M as md,V as nd,h as od};
3
+ export{m as pd,I as qd,M as rd,V as sd,h as td};